title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Implicit initialization of variables with 0 or 1 in C - GeeksforGeeks
19 Jun, 2018 In C programming language, the variables should be declared before a value is assigned to it.For Example: // declaration of variable a and // initializing it with 0. int a = 0; // declaring array arr and initializing // all the values of arr as 0. int arr[5] = {0}; However, variables can be assigned with 0 or 1 without even declaring them. Let us see an example to see how it can be done: #include <stdio.h>#include <stdlib.h> // implicit initialization of variablesa, b, arr[3]; // value of i is initialized to 1int main(i){ printf("a = %d, b = %d\n\n", a, b); printf("arr[0] = %d, \narr[1] = %d, \narr[2] = %d," "\n\n", arr[0], arr[1], arr[2]); printf("i = %d\n", i); return 0;} a = 0, b = 0 arr[0] = 0, arr[1] = 0, arr[2] = 0, i = 1 In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0.Let us see another example to illustrate this. #include <stdio.h>#include <stdlib.h> int main(){ // size of the array is 5, but only array[0], // array[1] and array[2] are initialized int arr[5] = { 1, 2, 3 }; // printing all the elements of the array int i; for (i = 0; i < 5; i++) { printf("arr[%d] = %d\n", i, arr[i]); } return 0;} arr[0] = 1 arr[1] = 2 arr[2] = 3 arr[3] = 0 arr[4] = 0 C-Variable Declaration and Scope C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Multiple Inheritance in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C How to split a string in C/C++, Python and Java? UDP Server-Client implementation in C
[ { "code": null, "e": 26030, "s": 26002, "text": "\n19 Jun, 2018" }, { "code": null, "e": 26136, "s": 26030, "text": "In C programming language, the variables should be declared before a value is assigned to it.For Example:" }, { "code": null, "e": 26319, "s": 26136, "text": " // declaration of variable a and \n // initializing it with 0.\n int a = 0;\n\n // declaring array arr and initializing \n // all the values of arr as 0.\n int arr[5] = {0}; \n" }, { "code": null, "e": 26444, "s": 26319, "text": "However, variables can be assigned with 0 or 1 without even declaring them. Let us see an example to see how it can be done:" }, { "code": "#include <stdio.h>#include <stdlib.h> // implicit initialization of variablesa, b, arr[3]; // value of i is initialized to 1int main(i){ printf(\"a = %d, b = %d\\n\\n\", a, b); printf(\"arr[0] = %d, \\narr[1] = %d, \\narr[2] = %d,\" \"\\n\\n\", arr[0], arr[1], arr[2]); printf(\"i = %d\\n\", i); return 0;}", "e": 26771, "s": 26444, "text": null }, { "code": null, "e": 26832, "s": 26771, "text": "a = 0, b = 0\n\narr[0] = 0, \narr[1] = 0, \narr[2] = 0, \n\ni = 1\n" }, { "code": null, "e": 27013, "s": 26832, "text": "In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0.Let us see another example to illustrate this." }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ // size of the array is 5, but only array[0], // array[1] and array[2] are initialized int arr[5] = { 1, 2, 3 }; // printing all the elements of the array int i; for (i = 0; i < 5; i++) { printf(\"arr[%d] = %d\\n\", i, arr[i]); } return 0;}", "e": 27337, "s": 27013, "text": null }, { "code": null, "e": 27393, "s": 27337, "text": "arr[0] = 1\narr[1] = 2\narr[2] = 3\narr[3] = 0\narr[4] = 0\n" }, { "code": null, "e": 27426, "s": 27393, "text": "C-Variable Declaration and Scope" }, { "code": null, "e": 27437, "s": 27426, "text": "C Language" }, { "code": null, "e": 27535, "s": 27437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27573, "s": 27535, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27599, "s": 27573, "text": "Exception Handling in C++" }, { "code": null, "e": 27621, "s": 27599, "text": "'this' pointer in C++" }, { "code": null, "e": 27641, "s": 27621, "text": "Multithreading in C" }, { "code": null, "e": 27682, "s": 27641, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27710, "s": 27682, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 27752, "s": 27710, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 27788, "s": 27752, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 27837, "s": 27788, "text": "How to split a string in C/C++, Python and Java?" } ]
GATE | GATE-CS-2007 | Question 78 - GeeksforGeeks
14 Sep, 2021 Consider the CFG with {S,A,B) as the non-terminal alphabet, {a,b) as the terminal alphabet, S as the start symbol and the following set of production rules S --> aB S --> bA B --> b A --> a B --> bS A --> aS B --> aBB A --> bAA Which of the following strings is generated by the grammar?(A) aaaabb(B) aabbbb(C) aabbab(D) abbbbaAnswer: (C)Explanation: Given below production rules. S --> aB S --> bA B --> b A --> a B --> bS A --> aS B --> aBB A --> bAA We can derive aabbab using below sequence S -> aB [Using S --> aB] -> aaBB [Using B --> aBB] -> aabB [Using B --> b] -> aabbS [Using B --> bS] -> aabbaB [Using S --> aB] -> aabbab [Using B --> b] YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0032:36 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25871, "s": 25843, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26027, "s": 25871, "text": "Consider the CFG with {S,A,B) as the non-terminal alphabet, {a,b) as the terminal alphabet, S as the start symbol and the following set of production rules" }, { "code": null, "e": 26127, "s": 26027, "text": "S --> aB S --> bA\nB --> b A --> a\nB --> bS A --> aS\nB --> aBB A --> bAA" }, { "code": null, "e": 26280, "s": 26127, "text": "Which of the following strings is generated by the grammar?(A) aaaabb(B) aabbbb(C) aabbab(D) abbbbaAnswer: (C)Explanation: Given below production rules." }, { "code": null, "e": 26380, "s": 26280, "text": "S --> aB S --> bA\nB --> b A --> a\nB --> bS A --> aS\nB --> aBB A --> bAA" }, { "code": null, "e": 26422, "s": 26380, "text": "We can derive aabbab using below sequence" }, { "code": null, "e": 26608, "s": 26422, "text": "S -> aB [Using S --> aB] \n -> aaBB [Using B --> aBB]\n -> aabB [Using B --> b]\n -> aabbS [Using B --> bS]\n -> aabbaB [Using S --> aB]\n -> aabbab [Using B --> b]" }, { "code": null, "e": 27521, "s": 26608, "text": "YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0032:36 / 58:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LdMTs93sekg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 27534, "s": 27521, "text": "GATE-CS-2007" }, { "code": null, "e": 27552, "s": 27534, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 27557, "s": 27552, "text": "GATE" }, { "code": null, "e": 27655, "s": 27557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27689, "s": 27655, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27723, "s": 27689, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27757, "s": 27723, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27790, "s": 27757, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27826, "s": 27790, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27860, "s": 27826, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27896, "s": 27860, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27930, "s": 27896, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27964, "s": 27930, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Underscore.js _.once() Function - GeeksforGeeks
25 Nov, 2021 The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects. The _.once function is used in conditions where we want a particular function to be executed only a single time. Even though we execute or call this function multiple times then also it will have no effect. The original function’s values will only be returned each time it is called.It is mostly used for the initialize() functions which are used to assign only the initial values to the variables. Syntax: _.once(function) Parameters:It takes only one argument, i.e., the function that needs to be called only a single time.Return value:It returns the original call’s value each time the function is iteratively or repeatedly called. Performing addition function with the _.once() function:The function that is passed to the _.once() function adds 10 to the variable 10 which originally has 10 value. Then the _.once() function is assigned to the another function ‘startFunc()’. Then the first time the ‘startFunc()’ is called the value of ‘a’ is incremented by 10 and becomes 20. So the output of first time calling is 20. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be incremented by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 20. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.Examples:<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 10; function add() { a += 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:Performing multiplication operation with the _.once() function:The function that is passed to the _.once() function multiplies by 10 the variable ‘a’ which has value 10 originally. Then the _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is multiplied by 10 and becomes 100. So the output of first time calling is 100. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again multiplied by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 100. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 10; function add() { a *= 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:Passing strings to the _.once() function:The function that is passed to the _.once() function appends the original string of the variable ‘a’ with the other string. The _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is appended by ” appended” string and hence becomes “xyz appended”. So the output of first time calling is “xyz appended”. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again appended but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., “xyz appended”. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is “xyz”.<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 'xyz'; function add() { a += " appended "; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:Passing both number and string to the _.once() function:Here we perform _.once() function on a function which both appends the string to a variable ‘a’ whose original value is “xyz” and also adds 10 to a variable ‘b’ whose original value is 5. On the first line the original values of both the variables ‘a’ and ‘b’ will be displayed. After that when we first time call the ‘startFunc()’ the ‘a’ variable is appended by ” appended” string and the ‘b’ variable’s value is incremented by 10. So, ‘a’ becomes “xyz appended” and ‘b’ becomes 15. Now each time the ‘startFunc()’ is used the values of ‘a’ and ‘b’ will remain same as we have use _.once() function in the definition of ‘startFunc()’.<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 'xyz', b = 5; function add() { a += " appended "; b += 10; } var startFunc = _.once(add); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); </script></body> </html>Output: Performing addition function with the _.once() function:The function that is passed to the _.once() function adds 10 to the variable 10 which originally has 10 value. Then the _.once() function is assigned to the another function ‘startFunc()’. Then the first time the ‘startFunc()’ is called the value of ‘a’ is incremented by 10 and becomes 20. So the output of first time calling is 20. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be incremented by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 20. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.Examples:<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 10; function add() { a += 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 10; function add() { a += 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html> Output: Performing multiplication operation with the _.once() function:The function that is passed to the _.once() function multiplies by 10 the variable ‘a’ which has value 10 originally. Then the _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is multiplied by 10 and becomes 100. So the output of first time calling is 100. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again multiplied by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 100. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 10; function add() { a *= 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 10; function add() { a *= 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html> Output: Passing strings to the _.once() function:The function that is passed to the _.once() function appends the original string of the variable ‘a’ with the other string. The _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is appended by ” appended” string and hence becomes “xyz appended”. So the output of first time calling is “xyz appended”. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again appended but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., “xyz appended”. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is “xyz”.<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 'xyz'; function add() { a += " appended "; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 'xyz'; function add() { a += " appended "; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html> Output: Passing both number and string to the _.once() function:Here we perform _.once() function on a function which both appends the string to a variable ‘a’ whose original value is “xyz” and also adds 10 to a variable ‘b’ whose original value is 5. On the first line the original values of both the variables ‘a’ and ‘b’ will be displayed. After that when we first time call the ‘startFunc()’ the ‘a’ variable is appended by ” appended” string and the ‘b’ variable’s value is incremented by 10. So, ‘a’ becomes “xyz appended” and ‘b’ becomes 15. Now each time the ‘startFunc()’ is used the values of ‘a’ and ‘b’ will remain same as we have use _.once() function in the definition of ‘startFunc()’.<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 'xyz', b = 5; function add() { a += " appended "; b += 10; } var startFunc = _.once(add); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); </script></body> </html>Output: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var a = 'xyz', b = 5; function add() { a += " appended "; b += 10; } var startFunc = _.once(add); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); </script></body> </html> Output: NOTE:These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows: <script type="text/javascript" src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> Akanksha_Rai ManasChhabra2 JavaScript - Underscore.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 34957, "s": 34929, "text": "\n25 Nov, 2021" }, { "code": null, "e": 35113, "s": 34957, "text": "The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects." }, { "code": null, "e": 35512, "s": 35113, "text": "The _.once function is used in conditions where we want a particular function to be executed only a single time. Even though we execute or call this function multiple times then also it will have no effect. The original function’s values will only be returned each time it is called.It is mostly used for the initialize() functions which are used to assign only the initial values to the variables." }, { "code": null, "e": 35520, "s": 35512, "text": "Syntax:" }, { "code": null, "e": 35537, "s": 35520, "text": "_.once(function)" }, { "code": null, "e": 35748, "s": 35537, "text": "Parameters:It takes only one argument, i.e., the function that needs to be called only a single time.Return value:It returns the original call’s value each time the function is iteratively or repeatedly called." }, { "code": null, "e": 41008, "s": 35748, "text": "Performing addition function with the _.once() function:The function that is passed to the _.once() function adds 10 to the variable 10 which originally has 10 value. Then the _.once() function is assigned to the another function ‘startFunc()’. Then the first time the ‘startFunc()’ is called the value of ‘a’ is incremented by 10 and becomes 20. So the output of first time calling is 20. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be incremented by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 20. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.Examples:<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 10; function add() { a += 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:Performing multiplication operation with the _.once() function:The function that is passed to the _.once() function multiplies by 10 the variable ‘a’ which has value 10 originally. Then the _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is multiplied by 10 and becomes 100. So the output of first time calling is 100. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again multiplied by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 100. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 10; function add() { a *= 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:Passing strings to the _.once() function:The function that is passed to the _.once() function appends the original string of the variable ‘a’ with the other string. The _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is appended by ” appended” string and hence becomes “xyz appended”. So the output of first time calling is “xyz appended”. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again appended but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., “xyz appended”. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is “xyz”.<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 'xyz'; function add() { a += \" appended \"; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:Passing both number and string to the _.once() function:Here we perform _.once() function on a function which both appends the string to a variable ‘a’ whose original value is “xyz” and also adds 10 to a variable ‘b’ whose original value is 5. On the first line the original values of both the variables ‘a’ and ‘b’ will be displayed. After that when we first time call the ‘startFunc()’ the ‘a’ variable is appended by ” appended” string and the ‘b’ variable’s value is incremented by 10. So, ‘a’ becomes “xyz appended” and ‘b’ becomes 15. Now each time the ‘startFunc()’ is used the values of ‘a’ and ‘b’ will remain same as we have use _.once() function in the definition of ‘startFunc()’.<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 'xyz', b = 5; function add() { a += \" appended \"; b += 10; } var startFunc = _.once(add); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); </script></body> </html>Output:" }, { "code": null, "e": 42339, "s": 41008, "text": "Performing addition function with the _.once() function:The function that is passed to the _.once() function adds 10 to the variable 10 which originally has 10 value. Then the _.once() function is assigned to the another function ‘startFunc()’. Then the first time the ‘startFunc()’ is called the value of ‘a’ is incremented by 10 and becomes 20. So the output of first time calling is 20. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be incremented by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 20. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.Examples:<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 10; function add() { a += 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:" }, { "code": "<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 10; function add() { a += 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>", "e": 42801, "s": 42339, "text": null }, { "code": null, "e": 42809, "s": 42801, "text": "Output:" }, { "code": null, "e": 44143, "s": 42809, "text": "Performing multiplication operation with the _.once() function:The function that is passed to the _.once() function multiplies by 10 the variable ‘a’ which has value 10 originally. Then the _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is multiplied by 10 and becomes 100. So the output of first time calling is 100. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again multiplied by 10 but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., 100. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is 10.<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 10; function add() { a *= 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:" }, { "code": "<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 10; function add() { a *= 10; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>", "e": 44605, "s": 44143, "text": null }, { "code": null, "e": 44613, "s": 44605, "text": "Output:" }, { "code": null, "e": 45987, "s": 44613, "text": "Passing strings to the _.once() function:The function that is passed to the _.once() function appends the original string of the variable ‘a’ with the other string. The _.once() function is assigned to another function ‘startFunc()’. The first time the ‘startFunc()’ is called the value of ‘a’ is appended by ” appended” string and hence becomes “xyz appended”. So the output of first time calling is “xyz appended”. Then the next time when ‘startFunc()’ is called the value of ‘a’ is again supposed to be again appended but this does not happen. This is because the ‘startFunc()’ has a function ‘_.once()’ in its definition which prevents it from being executed more than one times. So, the output of the second and third calls will be the same as first, i.e., “xyz appended”. On the first line, the value of ‘a’ is getting printed before calling the ‘startFunc()’ hence the output is “xyz”.<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 'xyz'; function add() { a += \" appended \"; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>Output:" }, { "code": "<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 'xyz'; function add() { a += \" appended \"; } var startFunc = _.once(add); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); startFunc(); console.log(a); </script></body> </html>", "e": 46462, "s": 45987, "text": null }, { "code": null, "e": 46470, "s": 46462, "text": "Output:" }, { "code": null, "e": 47694, "s": 46470, "text": "Passing both number and string to the _.once() function:Here we perform _.once() function on a function which both appends the string to a variable ‘a’ whose original value is “xyz” and also adds 10 to a variable ‘b’ whose original value is 5. On the first line the original values of both the variables ‘a’ and ‘b’ will be displayed. After that when we first time call the ‘startFunc()’ the ‘a’ variable is appended by ” appended” string and the ‘b’ variable’s value is incremented by 10. So, ‘a’ becomes “xyz appended” and ‘b’ becomes 15. Now each time the ‘startFunc()’ is used the values of ‘a’ and ‘b’ will remain same as we have use _.once() function in the definition of ‘startFunc()’.<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 'xyz', b = 5; function add() { a += \" appended \"; b += 10; } var startFunc = _.once(add); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); </script></body> </html>Output:" }, { "code": "<html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var a = 'xyz', b = 5; function add() { a += \" appended \"; b += 10; } var startFunc = _.once(add); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); startFunc(); console.log(a, b); </script></body> </html>", "e": 48219, "s": 47694, "text": null }, { "code": null, "e": 48227, "s": 48219, "text": "Output:" }, { "code": null, "e": 48455, "s": 48227, "text": "NOTE:These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows:" }, { "code": "<script type=\"text/javascript\" src =\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"></script>", "e": 48580, "s": 48455, "text": null }, { "code": null, "e": 48593, "s": 48580, "text": "Akanksha_Rai" }, { "code": null, "e": 48607, "s": 48593, "text": "ManasChhabra2" }, { "code": null, "e": 48634, "s": 48607, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 48645, "s": 48634, "text": "JavaScript" }, { "code": null, "e": 48662, "s": 48645, "text": "Web Technologies" }, { "code": null, "e": 48760, "s": 48662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48800, "s": 48760, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 48845, "s": 48800, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 48906, "s": 48845, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 48978, "s": 48906, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 49047, "s": 48978, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 49087, "s": 49047, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 49120, "s": 49087, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 49165, "s": 49120, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 49208, "s": 49165, "text": "How to fetch data from an API in ReactJS ?" } ]
Building Jarvis, the Generative Chatbot with an Attitude | by Agustinus Nalwan | Towards Data Science
Carsales.com, the company I work for, is holding a hackathon event. This is an annual event where everyone (tech or non tech) comes together to form a team and build anything — anything at all. Well, preferably you would build something that has a business purpose, but it is really up to you. This idea for this chatbot actually came from Jason Blackman, our Chief Information Officer at carsales.com. Given that our next hackathon is an online event, thanks to COVID-19, wouldn’t it be cool if we could host a Zoom webinar, where any carsales.com employee could jump in to hang out and chat with an AI bot which we could call Jarvis, who would always be available to chat with you. After tossing around ideas, I came up with a high-level scope. Jarvis would need to have a visual presence, just as would a human webinar participant. He needs to be able to listen to what you say and respond contextually with a voice. I wanted him to be as creative as possible in his replies and to be able to generate a reply on the fly. Most chatbot systems are retrieval based, meaning that they have hundreds or thousands of prepared sentence pairs (source and target), which form their knowledge bases. When the bot hears a sentence, it will then try to find the most similar source sentence from its knowledge base and simply return the paired target sentence. Retrieval based bots such as Amazon Alexa and Google Home are a lot easier to build and work very well to deliver specific tasks like booking a restaurant or turning the lights on or off, whereas the conversation scope is limited. However, for entertainment purposes like casual chatting, they lack creativity in their replies when compared to the generative counterpart. For that reason, I wanted a generative based system for Jarvis. I am fully aware that it is likely I will not achieve a good result. However, I really want to know how far the current generative chatbot technology has come and what it can do. Ok, so I knew what I wanted. Now it was time to really contemplate how on earth I was going to build this bot. We know that the first component needed is a mechanism to route audio and video. Our bot needed to be able to hear conversations on Zoom, so we needed a way to route the audio from Zoom into our bot. This audio would then need to be passed into a speech recognition module, which would give us the conversation as text. We would then need to pass this text into our generative AI model to get a reply, which would be turned into speech by using text-to-speech tech. While the audio reply is being played, we would need an animated avatar, which, apart from fidgeting, could also move his lips in sync with the audio playback. The avatar animation and audio playback needed to be sent back to Zoom for all meeting participants to hear and see. Wow! It was indeed a pretty complex system. To summarise, we needed the following components: Audio/video routing Speech recognition Generative AI model Text to Speech Animated avatar Controller I love it when someone else has done the hard work for me. Loopback is an audio tool that allows you to redirect audio from any application into a virtual microphone. All I needed were two audio routings. The first one was to route the audio from the Zoom app into a virtual microphone, from which my bot would listen. The second routing was to route the chatbot audio output into yet another virtual microphone, where both the Zoom app and our avatar tool would listen to. It is obvious that Zoom would need to listen to this audio. However, why would our avatar tool need this audio? For lip-syncing, so that our avatar could move his lips according to the audio playback. You will see more details on this in later sections of this blog. This module is responsible for processing incoming audio from Zoom via a virtual microphone and turning it into a text. There were a couple of offline and online speech recognition frameworks to choose from. The one I ended up using was Google Speech API. It is an online API with an awesome python interface that delivers superb accuracy, and more importantly, allows you to stream and recognise audio in chunks, which minimises the processing time significantly. I would like to emphasise that latency (how long it takes for the bot to respond to a query) is very critical for a chat bot. A slow responding bot can look very robotic and unrealistic. Most of the time, the Google Speech API returns a response in less than a second after a sentence is fully heard. This is the part that I spent most of my time on. After spending a day or two catching up with the recent developments in generative chatbot techniques, I found out that Neural Machine Translation models seemed to have been quite popular recently. The concept was to feed an encoder-decoder LSTM model with word embedding from an input sentence, and to be able to generate a contextual output sentence. This technique is normally used for language translation. However, given that the job is simply mapping out one sentence to another, it can also be used to generate a reply to a sentence (in theory). In layman’s terms, an input sentence is broken up into words. Each word is then mapped into an integer id, which is then passed into an embedding layer. During training, the embedding layer learns to turn this list of ids into a list of embedding vectors, which are ‘x’ dimension in size. This vector is constructed in such a way that words with similar meanings yield similar vectors, which will provide deeper information, rather than just a single integer value. These vectors are then passed into an LSTM encoder layer that turns them into a thought vector (some call them a latent vector), which contains information about the whole input sentence. Please note that there is a popular misconception that there are many LSTM layers or blocks, when in fact there is only one. The many blocks in the diagram above show the same LSTM block being called one-time step after another processing word by word. The decoder on the right-hand side of the model is responsible for turning this thought vector into an output sentence. A special beginning of sentence <BOS> word is passed as an initial input to the LSTM layer, together with the thought vector, to generate the first word, which is forwarded to the same LSTM layer as an input to generate the next word, and so on and so forth. Going slightly deeper into technical realms, the output of an LSTM decoder unit is actually a number that is passed into a softmax (classification) layer, which returns the probability of each possible word in our vocabulary. The word with the highest probability (in the case above it is ‘I’) is the one picked as an output word, and also passed on as an input to the LSTM decoder layer to generate the next word. There are a few examples online on how to build this model architecture. However, why build one if someone else has already done the hard work for you? Introducing: The Amazon SageMaker! Amazon SageMaker is a collection of tools and a pipeline to expedite building ML models, and comes with vast array of amazing built-in algorithms such as image classification, object detection, neural style transfer and seq2seq, which is a close variant of the Neural Machine Translation but with an extra attention mechanism. The Amazon SageMaker seq2seq model is highly customisable. You can choose how many LSTM units are used, the number of hidden cells, embedding vector dimensions, the number of LSTM layers, etc., which gives me more than enough flexibility to experiment with different parameters to achieve better results. The selection of the training set is crucial to the success of your chatbot responding with contextual and meaningful replies. The training set needs to be a collection of conversation exchanges between two parties. Specifically, we needed to construct a pair, a source sentence and a target sentence for each entry. For example, ‘Source: How are you?’ ‘Target: I am fine.’ ‘Source: Where do you live?’ ‘Target: I live in Australia’. This type of training set is very hard to get without a significant manual clean-up effort. The most popular dataset that people use is the Cornell Movie Dialogue Corpus Dataset, which is not great (you will see why a little later), but is the best you can get right now. This data set consists of 220k lines of conversations taken from a movie dialogue. Each line comprises dialogue from one or more persons. The three example lines below show you some good examples where the conversation starts with a question (in bold) from one person and is followed by an answer from another. You know French? Sure do ... my Mom’s from Canada And where’re you going? If you must know, we were attempting to go to a small study group of friends. How many people go here? Couple thousand. Most of them evil However, there are many more bad examples of lines where the follow up sentence does not make sense because you need the context of the prior conversation or a visual reference for it to make sense. For example, see the following: What’s the worst? You get the girl. No kidding. He’s a criminal. It’s a lung cancer issue. Her favorite uncle There is no easy way to remove the bad lines without putting in manual labour, which I was not really prepared to do. And even if I did, I would have ended up with much less dataset; not enough to train my AI model with. Hence, I decided to proceed regardless and see how far I could get with this. I generated multiple pairs of source and target sentences from each conversation line and from each two consecutive sentences, regardless of who said the sentence. ‘What’s the worst? You are broke? What to do next?’ will be turned into two pairs of conversation lines. What’s the worst? You are broke? You are broke? What to do next? This way, I managed to enlarge my dataset. I was fully aware that I could potentially and mistakenly pair a source and target sentence spoken by the same person. However, half of the time, the target sentence still made sense if it was in a reply from others, as shown in the example below. What’s the worst? You are broke? What do do next? Tokenising/splitting sentences can be done in two lines of code using the nltk library. tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')sentences = tokenizer.tokenize(text) I also trimmed a sentence if it was longer than 20 words, as my model could only read an input of up to 20 words and an output of 20 words. Besides this, longer sentences mean a greater context and higher variation, which is a lot harder for an AI model to learn given the size of our training set is not that big. With the above methods, I managed to get 441k pairs of conversation lines. The next step was to pre-process this training set further, which involved several steps. The first step was to remove and replace unwanted strings from the pairs such as all the xml and html tags and multiple dots and dashes.The next step was to expand the contraction words, for example, ‘you’ll’ was expanded to ‘you will’, ‘I’m’ to ‘I am’, etc., which increased my AI model accuracy. The reason for this is that in later steps, sentences would be turned into lists of words by splitting against delimiter characters like spaces, new lines or tabs. All unique words would form our vocabulary. Contractions like ‘I’m’ would be considered as a new word in the vocabulary, which would increase our vocabulary size unnecessarily, and reduce the effectiveness of our training sets due to fragmentation; hence making it harder for our AI to learn. I used a very handy python framework called ‘contractions’, which expanded contractions in a sentence with one line of code. text = contractions.fix(text) Punctuation was the next thing to tackle. I separated the punctuation from sentences (e.g., ‘How are you?’ was turned into ‘How are you ?’) This was done for similar reasons as for the contractions; to make sure that the punctuation itself would be considered as a word, and that it wouldn’t be merged together with the previous word as a new word, such as ‘you?’ in the example above. By going through all the steps above, I gained about 441k pairs of training sets and 56k words for the vocabulary. As a final step, I added a vocabulary pruning so that I could control what the maximum number of words was to support in the vocabulary. The pruning was easily done by removing less frequently used words. A smaller vocabulary size and a larger training set are more favourable. This make sense — imagine the difficulties of teaching your kids five new words by giving them 100 sample sentences, as opposed to 100 new words with the same 100 sample sentences. Using fewer words more frequently in more sentences will of course help you learn better. From my many experiments, I found that a vocabulary of 15k words gave me the best results, which yielded 346k training sets, equal to a ratio of 23 as opposed to the original 441k/56k =7.9. Kick starting the training was super easy thanks to Amazon SageMaker, which already provided an example Jupyter notebook on how to train a Seq2Seq model. I just needed to customise the S3 bucket, where my training file was located, and add my data pre-processing code. Next, I will show you how easy it is to train a seq2seq model in SageMaker, by showing you snippet of coding here and there. Check out my jupyter notebook if you want to see the complete source code. First, you need to let SageMaker know which built-in algorithm you want to use. Each algorithm is containerised and available from a specific URL. from sagemaker.amazon.amazon_estimator import get_image_uricontainer = get_image_uri(region_name, 'seq2seq') Next, you need to construct the training job description which provides a few important information you need to set about the training job. First, you need to set the location of the training set and where you store the final model. "InputDataConfig": [ { "ChannelName": "train", "DataSource": { "S3DataSource": { "S3DataType": "S3Prefix", "S3Uri": "s3://{}/{}/train/".format(bucket, prefix), "S3DataDistributionType": "FullyReplicated" } }, },...."OutputDataConfig": { "S3OutputPath": "s3://{}/{}/".format(bucket, prefix)}, After this, you need to choose what machine or instance you want to run this training on. Seq2seq is quite a heavy model, so you need a GPU machine. My recommendation is ml.p3.8xlarge, which has four NVIDIA V100 GPUs. "ResourceConfig": { "InstanceCount": 1, "InstanceType": "ml.p3.8xlarge", "VolumeSizeInGB": 50} Finally, you need to set the hyper-parameters. This is where I spent 30% of my time, a close second to experimenting with data preparation strategy. I built various models under different settings and compared their performances to come up with the best configuration. Remember, I chose to limit my sentences to 20 words. The first two lines below are the reason why. My LSTM model was only trained to recognise an input of up to 20 words and an output of up to 20 words. "HyperParameters": { "max_seq_len_source": "20", "max_seq_len_target": "20", "optimized_metric": "bleu", "bleu_sample_size": "1000", "batch_size": "512", "checkpoint_frequency_num_batches": "1000", "rnn_num_hidden": "2048", "num_layers_encoder": "1", "num_layers_decoder": "1", "num_embed_source": "512", "num_embed_target": "512", "max_num_batches": "40100", "checkpoint_threshold": "3"}, Normally, the larger your batch-size (if your GPU RAM can handle it), the better, as you can train more data in one go to speed up the training process. 512 seems to be the max size for p3.8xlarge. Some people may argue that different batch sizes produce slightly different accuracies, however I was not aiming to win a Nobel prize here, so small accuracy differences did not really matter much to me. I used one layer for each encoder and decoder, each having 2,048 hidden cells with the word embedding size of 512. A checkpoint and evaluation were then performed at each batch of 1,000, which was equal to 1,000 x 512 samples per batch (512k pair samples). So, the training would go to 1.5x the overall training sets (346k in total) until it performed an evaluation against this model. At each checkpoint, the best evaluated model was kept and then, finally, saved into our output S3 bucket. SageMaker also has the capability to early termination. For example, if the model does not improve after three consecutive checkpoints (‘checkpoint_threshold’), the training will stop. Also, ‘max_num_batches’ is a safety net that can stop the training regardless. In the case that your model keeps improving forever (which is a good thing), this will protect you so that the training cost won’t break your bank (which is not a good thing) It only takes two lines of code to kick start the training. Then you just have to wait patiently for a few hours, depending on the instance type you use. It took me one and a half hours using p3.8xlarge instance. sagemaker_client = boto3.Session().client(service_name='sagemaker')sagemaker_client.create_training_job(**create_training_params) As you can see below, the validation metrics found the best performing model at checkpoint number eight. I intentionally skipped the discussion of the ‘optimized_metric’ earlier, as it is worth having its own section to explain it properly. Evaluating a generative AI Model is not a straightforward task. Often, there isn’t a one to one relationship between a question and an answer. For example, ten different answers are equally good for a question, which leads to a very broad scope of mapping. For a language translation task, the mapping is much narrower. However, for a chatbot, the scope is increased dramatically, especially when you use a movie dialogue as a training set. An answer to ‘Where are you going?’ could be any of the following: Going to hell Why do you ask? I am not going to tell you. What? Can you say again? There are two popular evaluation metrics to choose from for seq2seq algorithm in Amazon SageMaker: perplexity and bleu. Perplexity evaluates the generated sentences by taking random samples word by word using the probability distribution model in our training set, which is very well explained in this article. Bleu evaluates the generated sentence against the target sentence by scoring the word n-gram match and penalising a generated sentence if it is shorter than the target sentence. This article explains how it works and advises against using it, with an excellent justification. On the contrary, I found that it works better than perplexity because the quality of the generated sentences strongly correlates to bleu’s score upon manual inspection. When the training is completed, you can create an endpoint for inference. From there, generating a text with inference can be done with a few lines of code. response = runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType='application/json', Body=json.dumps(payload))response = response["Body"].read().decode("utf-8")response = json.loads(response)for i, pred in enumerate(response['predictions']): print(f"Human: {sentences[i]}\nJarvis: {pred['target']}\n") The results will not win me a medal (roughly 60% of the responses were out of context and 20% were passable). However, what excites me is that the other 20% were surprisingly good. It answered with correct context and grammar. Consequently, it showed me that it could learn the English language to a certain extent and could even swear like us. It’s a good reminder too, of what your kids can learn from movies. One of my favourite examples is when the bot was asked, ‘who is your best friend?’ he answered, ‘my wife’. I have checked, and most of these sentences were not even in the training set, so the AI model indeed learned a little bit of creativity and did not just memorise the training sets. Here are some of the bad ones. From experimenting with several different hyper-parameters, I found that: Adding more encoder and decoder layers made it worse. Interestingly, the sentence structure that was generated was more complex. However, the relevancy of the answers to the questions was poor. Reducing the word embedding size also dropped the generation quality. Reducing the vocabulary size of up to 15k words increased the quality, whilst further reduction reduced the quality. Expanding on word contractions and separating punctuation definitely increased the quality of responses. Though it’s probably more of a pre-processing step rather than a hyper-parameter settings. It is worth to mention that adding Byte Pair Encoding (as suggested by SageMaker notebook) drops the quality of responses. The next modules I needed were a text to speech and an animated avatar. I used an awesome Amazon Polly for text to speech generation. Again, it is an online API. However, it has a super lighting respond time (less than 300ms most of the time) and high-quality speech that sounds natural. Given my previous work as a Special Effect and Motion Capture Software Engineer, I was very tempted to build the animated avatar myself. I did actually build a simple avatar system on a separate project: Building a Bot That Plays Videos for my Toddler. Thankfully, the better part of me realised how long this would take me if I were to pursue this journey rather than to use an awesome 3D avatar software, Loom.ai, which comes with audio lip-sync capability! All you need to do is send an audio clip to the Loom.ai app and it will animate a 3D avatar to lip-sync to the provided audio. How awesome is that? The app also comes with a fake video camera driver, which streams the rendered output. I just needed to select the fake video camera in the Zoom app settings, so that I could include the animation in the Zoom meeting. With all the modules completed, all I needed to do was build a controller system that would combine everything. The first test ran quite well, except that Jarvis stole all the conversation. He impolitely interjected and replied to every single sentence spoken by anyone in the video conference which annoyed everyone. Well, that’s one thing I forgot to train Jarvis in — manners and social skills! Rather than building another social skill module, which I had no clue how to start, an easy fix to this was to teach Jarvis to start and stop talking by a voice command. When he heard ‘Jarvis, stop talking’ he stopped responding until he heard ‘Jarvis, start talking’. With this new and important skill, everyone started to like Jarvis more. This generative model was fun to talk to for the first few exchanges as with some of his answers, he amazed us with his creativity and his rudeness. However, the novelty wore off quickly because the longer the conversation went on, the more we heard out of context responses, until eventually we came to the realisation that we were not engaged in a meaningful conversation at all. For this reason, I ended up using a pattern-based chatbot tech driven by the AIML language model, which surprisingly offered much better creativity than a normal retrieval-based model and could recall context from past information! This article explains clearly what it is, and perhaps it will be a story for me to tell another day. With the help of my super awesome Hackathon team members, we even extended Jarvis’ capability to be an on demand meeting assistant who can help taking down notes, action points assigned to relevant individuals, emailing them to meeting participants and scheduling a follow up meeting. Sometimes the quality of the generated text from the bot was good. However, from just two conversation exchanges (even with the good ones), you could clearly tell that something was off and unnatural. It did not have past context. Each response was generated from the context of the question asked. It did not consider prior conversations, which most humans can do very easily. Obviously, the technology is not there yet to build a model that can consider past conversation history. I have not heard of one yet at least. For more than half of the time, it gave an irrelevant response. Although a better model architecture may also be needed, however my biggest suspect is the training set. Movie dialogue has broad topics, which makes it very hard for the AI model to learn, especially when the source and target sentences sometimes do not make sense (e.g., no prior context, requiring visual reference or being incorrectly paired). A training set like a restaurant booking dialogue may work better as the scope is very limited in restaurant booking. However, the conversation exchanges will likely be less entertaining. Given the above, I believe a fully practical, generative chatbot is still years or decades away. I can now totally understand why it takes years for us to learn a language. Nevertheless, this was a very fun project and I learned a lot from it. The code for this project is available from github.
[ { "code": null, "e": 575, "s": 172, "text": "Carsales.com, the company I work for, is holding a hackathon event. This is an annual event where everyone (tech or non tech) comes together to form a team and build anything — anything at all. Well, preferably you would build something that has a business purpose, but it is really up to you. This idea for this chatbot actually came from Jason Blackman, our Chief Information Officer at carsales.com." }, { "code": null, "e": 856, "s": 575, "text": "Given that our next hackathon is an online event, thanks to COVID-19, wouldn’t it be cool if we could host a Zoom webinar, where any carsales.com employee could jump in to hang out and chat with an AI bot which we could call Jarvis, who would always be available to chat with you." }, { "code": null, "e": 1092, "s": 856, "text": "After tossing around ideas, I came up with a high-level scope. Jarvis would need to have a visual presence, just as would a human webinar participant. He needs to be able to listen to what you say and respond contextually with a voice." }, { "code": null, "e": 1897, "s": 1092, "text": "I wanted him to be as creative as possible in his replies and to be able to generate a reply on the fly. Most chatbot systems are retrieval based, meaning that they have hundreds or thousands of prepared sentence pairs (source and target), which form their knowledge bases. When the bot hears a sentence, it will then try to find the most similar source sentence from its knowledge base and simply return the paired target sentence. Retrieval based bots such as Amazon Alexa and Google Home are a lot easier to build and work very well to deliver specific tasks like booking a restaurant or turning the lights on or off, whereas the conversation scope is limited. However, for entertainment purposes like casual chatting, they lack creativity in their replies when compared to the generative counterpart." }, { "code": null, "e": 2140, "s": 1897, "text": "For that reason, I wanted a generative based system for Jarvis. I am fully aware that it is likely I will not achieve a good result. However, I really want to know how far the current generative chatbot technology has come and what it can do." }, { "code": null, "e": 2251, "s": 2140, "text": "Ok, so I knew what I wanted. Now it was time to really contemplate how on earth I was going to build this bot." }, { "code": null, "e": 3038, "s": 2251, "text": "We know that the first component needed is a mechanism to route audio and video. Our bot needed to be able to hear conversations on Zoom, so we needed a way to route the audio from Zoom into our bot. This audio would then need to be passed into a speech recognition module, which would give us the conversation as text. We would then need to pass this text into our generative AI model to get a reply, which would be turned into speech by using text-to-speech tech. While the audio reply is being played, we would need an animated avatar, which, apart from fidgeting, could also move his lips in sync with the audio playback. The avatar animation and audio playback needed to be sent back to Zoom for all meeting participants to hear and see. Wow! It was indeed a pretty complex system." }, { "code": null, "e": 3088, "s": 3038, "text": "To summarise, we needed the following components:" }, { "code": null, "e": 3108, "s": 3088, "text": "Audio/video routing" }, { "code": null, "e": 3127, "s": 3108, "text": "Speech recognition" }, { "code": null, "e": 3147, "s": 3127, "text": "Generative AI model" }, { "code": null, "e": 3162, "s": 3147, "text": "Text to Speech" }, { "code": null, "e": 3178, "s": 3162, "text": "Animated avatar" }, { "code": null, "e": 3189, "s": 3178, "text": "Controller" }, { "code": null, "e": 3508, "s": 3189, "text": "I love it when someone else has done the hard work for me. Loopback is an audio tool that allows you to redirect audio from any application into a virtual microphone. All I needed were two audio routings. The first one was to route the audio from the Zoom app into a virtual microphone, from which my bot would listen." }, { "code": null, "e": 3930, "s": 3508, "text": "The second routing was to route the chatbot audio output into yet another virtual microphone, where both the Zoom app and our avatar tool would listen to. It is obvious that Zoom would need to listen to this audio. However, why would our avatar tool need this audio? For lip-syncing, so that our avatar could move his lips according to the audio playback. You will see more details on this in later sections of this blog." }, { "code": null, "e": 4582, "s": 3930, "text": "This module is responsible for processing incoming audio from Zoom via a virtual microphone and turning it into a text. There were a couple of offline and online speech recognition frameworks to choose from. The one I ended up using was Google Speech API. It is an online API with an awesome python interface that delivers superb accuracy, and more importantly, allows you to stream and recognise audio in chunks, which minimises the processing time significantly. I would like to emphasise that latency (how long it takes for the bot to respond to a query) is very critical for a chat bot. A slow responding bot can look very robotic and unrealistic." }, { "code": null, "e": 4696, "s": 4582, "text": "Most of the time, the Google Speech API returns a response in less than a second after a sentence is fully heard." }, { "code": null, "e": 4944, "s": 4696, "text": "This is the part that I spent most of my time on. After spending a day or two catching up with the recent developments in generative chatbot techniques, I found out that Neural Machine Translation models seemed to have been quite popular recently." }, { "code": null, "e": 5299, "s": 4944, "text": "The concept was to feed an encoder-decoder LSTM model with word embedding from an input sentence, and to be able to generate a contextual output sentence. This technique is normally used for language translation. However, given that the job is simply mapping out one sentence to another, it can also be used to generate a reply to a sentence (in theory)." }, { "code": null, "e": 6206, "s": 5299, "text": "In layman’s terms, an input sentence is broken up into words. Each word is then mapped into an integer id, which is then passed into an embedding layer. During training, the embedding layer learns to turn this list of ids into a list of embedding vectors, which are ‘x’ dimension in size. This vector is constructed in such a way that words with similar meanings yield similar vectors, which will provide deeper information, rather than just a single integer value. These vectors are then passed into an LSTM encoder layer that turns them into a thought vector (some call them a latent vector), which contains information about the whole input sentence. Please note that there is a popular misconception that there are many LSTM layers or blocks, when in fact there is only one. The many blocks in the diagram above show the same LSTM block being called one-time step after another processing word by word." }, { "code": null, "e": 6585, "s": 6206, "text": "The decoder on the right-hand side of the model is responsible for turning this thought vector into an output sentence. A special beginning of sentence <BOS> word is passed as an initial input to the LSTM layer, together with the thought vector, to generate the first word, which is forwarded to the same LSTM layer as an input to generate the next word, and so on and so forth." }, { "code": null, "e": 7000, "s": 6585, "text": "Going slightly deeper into technical realms, the output of an LSTM decoder unit is actually a number that is passed into a softmax (classification) layer, which returns the probability of each possible word in our vocabulary. The word with the highest probability (in the case above it is ‘I’) is the one picked as an output word, and also passed on as an input to the LSTM decoder layer to generate the next word." }, { "code": null, "e": 7514, "s": 7000, "text": "There are a few examples online on how to build this model architecture. However, why build one if someone else has already done the hard work for you? Introducing: The Amazon SageMaker! Amazon SageMaker is a collection of tools and a pipeline to expedite building ML models, and comes with vast array of amazing built-in algorithms such as image classification, object detection, neural style transfer and seq2seq, which is a close variant of the Neural Machine Translation but with an extra attention mechanism." }, { "code": null, "e": 7819, "s": 7514, "text": "The Amazon SageMaker seq2seq model is highly customisable. You can choose how many LSTM units are used, the number of hidden cells, embedding vector dimensions, the number of LSTM layers, etc., which gives me more than enough flexibility to experiment with different parameters to achieve better results." }, { "code": null, "e": 8525, "s": 7819, "text": "The selection of the training set is crucial to the success of your chatbot responding with contextual and meaningful replies. The training set needs to be a collection of conversation exchanges between two parties. Specifically, we needed to construct a pair, a source sentence and a target sentence for each entry. For example, ‘Source: How are you?’ ‘Target: I am fine.’ ‘Source: Where do you live?’ ‘Target: I live in Australia’. This type of training set is very hard to get without a significant manual clean-up effort. The most popular dataset that people use is the Cornell Movie Dialogue Corpus Dataset, which is not great (you will see why a little later), but is the best you can get right now." }, { "code": null, "e": 8836, "s": 8525, "text": "This data set consists of 220k lines of conversations taken from a movie dialogue. Each line comprises dialogue from one or more persons. The three example lines below show you some good examples where the conversation starts with a question (in bold) from one person and is followed by an answer from another." }, { "code": null, "e": 8886, "s": 8836, "text": "You know French? Sure do ... my Mom’s from Canada" }, { "code": null, "e": 8988, "s": 8886, "text": "And where’re you going? If you must know, we were attempting to go to a small study group of friends." }, { "code": null, "e": 9048, "s": 8988, "text": "How many people go here? Couple thousand. Most of them evil" }, { "code": null, "e": 9279, "s": 9048, "text": "However, there are many more bad examples of lines where the follow up sentence does not make sense because you need the context of the prior conversation or a visual reference for it to make sense. For example, see the following:" }, { "code": null, "e": 9315, "s": 9279, "text": "What’s the worst? You get the girl." }, { "code": null, "e": 9344, "s": 9315, "text": "No kidding. He’s a criminal." }, { "code": null, "e": 9389, "s": 9344, "text": "It’s a lung cancer issue. Her favorite uncle" }, { "code": null, "e": 9688, "s": 9389, "text": "There is no easy way to remove the bad lines without putting in manual labour, which I was not really prepared to do. And even if I did, I would have ended up with much less dataset; not enough to train my AI model with. Hence, I decided to proceed regardless and see how far I could get with this." }, { "code": null, "e": 9852, "s": 9688, "text": "I generated multiple pairs of source and target sentences from each conversation line and from each two consecutive sentences, regardless of who said the sentence." }, { "code": null, "e": 9957, "s": 9852, "text": "‘What’s the worst? You are broke? What to do next?’ will be turned into two pairs of conversation lines." }, { "code": null, "e": 9990, "s": 9957, "text": "What’s the worst? You are broke?" }, { "code": null, "e": 10022, "s": 9990, "text": "You are broke? What to do next?" }, { "code": null, "e": 10313, "s": 10022, "text": "This way, I managed to enlarge my dataset. I was fully aware that I could potentially and mistakenly pair a source and target sentence spoken by the same person. However, half of the time, the target sentence still made sense if it was in a reply from others, as shown in the example below." }, { "code": null, "e": 10363, "s": 10313, "text": "What’s the worst? You are broke? What do do next?" }, { "code": null, "e": 10451, "s": 10363, "text": "Tokenising/splitting sentences can be done in two lines of code using the nltk library." }, { "code": null, "e": 10549, "s": 10451, "text": "tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')sentences = tokenizer.tokenize(text)" }, { "code": null, "e": 10864, "s": 10549, "text": "I also trimmed a sentence if it was longer than 20 words, as my model could only read an input of up to 20 words and an output of 20 words. Besides this, longer sentences mean a greater context and higher variation, which is a lot harder for an AI model to learn given the size of our training set is not that big." }, { "code": null, "e": 10939, "s": 10864, "text": "With the above methods, I managed to get 441k pairs of conversation lines." }, { "code": null, "e": 11029, "s": 10939, "text": "The next step was to pre-process this training set further, which involved several steps." }, { "code": null, "e": 11784, "s": 11029, "text": "The first step was to remove and replace unwanted strings from the pairs such as all the xml and html tags and multiple dots and dashes.The next step was to expand the contraction words, for example, ‘you’ll’ was expanded to ‘you will’, ‘I’m’ to ‘I am’, etc., which increased my AI model accuracy. The reason for this is that in later steps, sentences would be turned into lists of words by splitting against delimiter characters like spaces, new lines or tabs. All unique words would form our vocabulary. Contractions like ‘I’m’ would be considered as a new word in the vocabulary, which would increase our vocabulary size unnecessarily, and reduce the effectiveness of our training sets due to fragmentation; hence making it harder for our AI to learn." }, { "code": null, "e": 11909, "s": 11784, "text": "I used a very handy python framework called ‘contractions’, which expanded contractions in a sentence with one line of code." }, { "code": null, "e": 11939, "s": 11909, "text": "text = contractions.fix(text)" }, { "code": null, "e": 12325, "s": 11939, "text": "Punctuation was the next thing to tackle. I separated the punctuation from sentences (e.g., ‘How are you?’ was turned into ‘How are you ?’) This was done for similar reasons as for the contractions; to make sure that the punctuation itself would be considered as a word, and that it wouldn’t be merged together with the previous word as a new word, such as ‘you?’ in the example above." }, { "code": null, "e": 12440, "s": 12325, "text": "By going through all the steps above, I gained about 441k pairs of training sets and 56k words for the vocabulary." }, { "code": null, "e": 12989, "s": 12440, "text": "As a final step, I added a vocabulary pruning so that I could control what the maximum number of words was to support in the vocabulary. The pruning was easily done by removing less frequently used words. A smaller vocabulary size and a larger training set are more favourable. This make sense — imagine the difficulties of teaching your kids five new words by giving them 100 sample sentences, as opposed to 100 new words with the same 100 sample sentences. Using fewer words more frequently in more sentences will of course help you learn better." }, { "code": null, "e": 13179, "s": 12989, "text": "From my many experiments, I found that a vocabulary of 15k words gave me the best results, which yielded 346k training sets, equal to a ratio of 23 as opposed to the original 441k/56k =7.9." }, { "code": null, "e": 13333, "s": 13179, "text": "Kick starting the training was super easy thanks to Amazon SageMaker, which already provided an example Jupyter notebook on how to train a Seq2Seq model." }, { "code": null, "e": 13648, "s": 13333, "text": "I just needed to customise the S3 bucket, where my training file was located, and add my data pre-processing code. Next, I will show you how easy it is to train a seq2seq model in SageMaker, by showing you snippet of coding here and there. Check out my jupyter notebook if you want to see the complete source code." }, { "code": null, "e": 13795, "s": 13648, "text": "First, you need to let SageMaker know which built-in algorithm you want to use. Each algorithm is containerised and available from a specific URL." }, { "code": null, "e": 13904, "s": 13795, "text": "from sagemaker.amazon.amazon_estimator import get_image_uricontainer = get_image_uri(region_name, 'seq2seq')" }, { "code": null, "e": 14137, "s": 13904, "text": "Next, you need to construct the training job description which provides a few important information you need to set about the training job. First, you need to set the location of the training set and where you store the final model." }, { "code": null, "e": 14526, "s": 14137, "text": "\"InputDataConfig\": [ { \"ChannelName\": \"train\", \"DataSource\": { \"S3DataSource\": { \"S3DataType\": \"S3Prefix\", \"S3Uri\": \"s3://{}/{}/train/\".format(bucket, prefix), \"S3DataDistributionType\": \"FullyReplicated\" } }, },....\"OutputDataConfig\": { \"S3OutputPath\": \"s3://{}/{}/\".format(bucket, prefix)}," }, { "code": null, "e": 14744, "s": 14526, "text": "After this, you need to choose what machine or instance you want to run this training on. Seq2seq is quite a heavy model, so you need a GPU machine. My recommendation is ml.p3.8xlarge, which has four NVIDIA V100 GPUs." }, { "code": null, "e": 14848, "s": 14744, "text": "\"ResourceConfig\": { \"InstanceCount\": 1, \"InstanceType\": \"ml.p3.8xlarge\", \"VolumeSizeInGB\": 50}" }, { "code": null, "e": 15117, "s": 14848, "text": "Finally, you need to set the hyper-parameters. This is where I spent 30% of my time, a close second to experimenting with data preparation strategy. I built various models under different settings and compared their performances to come up with the best configuration." }, { "code": null, "e": 15320, "s": 15117, "text": "Remember, I chose to limit my sentences to 20 words. The first two lines below are the reason why. My LSTM model was only trained to recognise an input of up to 20 words and an output of up to 20 words." }, { "code": null, "e": 15749, "s": 15320, "text": "\"HyperParameters\": { \"max_seq_len_source\": \"20\", \"max_seq_len_target\": \"20\", \"optimized_metric\": \"bleu\", \"bleu_sample_size\": \"1000\", \"batch_size\": \"512\", \"checkpoint_frequency_num_batches\": \"1000\", \"rnn_num_hidden\": \"2048\", \"num_layers_encoder\": \"1\", \"num_layers_decoder\": \"1\", \"num_embed_source\": \"512\", \"num_embed_target\": \"512\", \"max_num_batches\": \"40100\", \"checkpoint_threshold\": \"3\"}," }, { "code": null, "e": 16151, "s": 15749, "text": "Normally, the larger your batch-size (if your GPU RAM can handle it), the better, as you can train more data in one go to speed up the training process. 512 seems to be the max size for p3.8xlarge. Some people may argue that different batch sizes produce slightly different accuracies, however I was not aiming to win a Nobel prize here, so small accuracy differences did not really matter much to me." }, { "code": null, "e": 16828, "s": 16151, "text": "I used one layer for each encoder and decoder, each having 2,048 hidden cells with the word embedding size of 512. A checkpoint and evaluation were then performed at each batch of 1,000, which was equal to 1,000 x 512 samples per batch (512k pair samples). So, the training would go to 1.5x the overall training sets (346k in total) until it performed an evaluation against this model. At each checkpoint, the best evaluated model was kept and then, finally, saved into our output S3 bucket. SageMaker also has the capability to early termination. For example, if the model does not improve after three consecutive checkpoints (‘checkpoint_threshold’), the training will stop." }, { "code": null, "e": 17082, "s": 16828, "text": "Also, ‘max_num_batches’ is a safety net that can stop the training regardless. In the case that your model keeps improving forever (which is a good thing), this will protect you so that the training cost won’t break your bank (which is not a good thing)" }, { "code": null, "e": 17295, "s": 17082, "text": "It only takes two lines of code to kick start the training. Then you just have to wait patiently for a few hours, depending on the instance type you use. It took me one and a half hours using p3.8xlarge instance." }, { "code": null, "e": 17425, "s": 17295, "text": "sagemaker_client = boto3.Session().client(service_name='sagemaker')sagemaker_client.create_training_job(**create_training_params)" }, { "code": null, "e": 17530, "s": 17425, "text": "As you can see below, the validation metrics found the best performing model at checkpoint number eight." }, { "code": null, "e": 18174, "s": 17530, "text": "I intentionally skipped the discussion of the ‘optimized_metric’ earlier, as it is worth having its own section to explain it properly. Evaluating a generative AI Model is not a straightforward task. Often, there isn’t a one to one relationship between a question and an answer. For example, ten different answers are equally good for a question, which leads to a very broad scope of mapping. For a language translation task, the mapping is much narrower. However, for a chatbot, the scope is increased dramatically, especially when you use a movie dialogue as a training set. An answer to ‘Where are you going?’ could be any of the following:" }, { "code": null, "e": 18188, "s": 18174, "text": "Going to hell" }, { "code": null, "e": 18204, "s": 18188, "text": "Why do you ask?" }, { "code": null, "e": 18232, "s": 18204, "text": "I am not going to tell you." }, { "code": null, "e": 18238, "s": 18232, "text": "What?" }, { "code": null, "e": 18257, "s": 18238, "text": "Can you say again?" }, { "code": null, "e": 18568, "s": 18257, "text": "There are two popular evaluation metrics to choose from for seq2seq algorithm in Amazon SageMaker: perplexity and bleu. Perplexity evaluates the generated sentences by taking random samples word by word using the probability distribution model in our training set, which is very well explained in this article." }, { "code": null, "e": 19013, "s": 18568, "text": "Bleu evaluates the generated sentence against the target sentence by scoring the word n-gram match and penalising a generated sentence if it is shorter than the target sentence. This article explains how it works and advises against using it, with an excellent justification. On the contrary, I found that it works better than perplexity because the quality of the generated sentences strongly correlates to bleu’s score upon manual inspection." }, { "code": null, "e": 19170, "s": 19013, "text": "When the training is completed, you can create an endpoint for inference. From there, generating a text with inference can be done with a few lines of code." }, { "code": null, "e": 19555, "s": 19170, "text": "response = runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType='application/json', Body=json.dumps(payload))response = response[\"Body\"].read().decode(\"utf-8\")response = json.loads(response)for i, pred in enumerate(response['predictions']): print(f\"Human: {sentences[i]}\\nJarvis: {pred['target']}\\n\")" }, { "code": null, "e": 19967, "s": 19555, "text": "The results will not win me a medal (roughly 60% of the responses were out of context and 20% were passable). However, what excites me is that the other 20% were surprisingly good. It answered with correct context and grammar. Consequently, it showed me that it could learn the English language to a certain extent and could even swear like us. It’s a good reminder too, of what your kids can learn from movies." }, { "code": null, "e": 20256, "s": 19967, "text": "One of my favourite examples is when the bot was asked, ‘who is your best friend?’ he answered, ‘my wife’. I have checked, and most of these sentences were not even in the training set, so the AI model indeed learned a little bit of creativity and did not just memorise the training sets." }, { "code": null, "e": 20287, "s": 20256, "text": "Here are some of the bad ones." }, { "code": null, "e": 20361, "s": 20287, "text": "From experimenting with several different hyper-parameters, I found that:" }, { "code": null, "e": 20555, "s": 20361, "text": "Adding more encoder and decoder layers made it worse. Interestingly, the sentence structure that was generated was more complex. However, the relevancy of the answers to the questions was poor." }, { "code": null, "e": 20625, "s": 20555, "text": "Reducing the word embedding size also dropped the generation quality." }, { "code": null, "e": 20742, "s": 20625, "text": "Reducing the vocabulary size of up to 15k words increased the quality, whilst further reduction reduced the quality." }, { "code": null, "e": 20847, "s": 20742, "text": "Expanding on word contractions and separating punctuation definitely increased the quality of responses." }, { "code": null, "e": 21061, "s": 20847, "text": "Though it’s probably more of a pre-processing step rather than a hyper-parameter settings. It is worth to mention that adding Byte Pair Encoding (as suggested by SageMaker notebook) drops the quality of responses." }, { "code": null, "e": 21349, "s": 21061, "text": "The next modules I needed were a text to speech and an animated avatar. I used an awesome Amazon Polly for text to speech generation. Again, it is an online API. However, it has a super lighting respond time (less than 300ms most of the time) and high-quality speech that sounds natural." }, { "code": null, "e": 22175, "s": 21349, "text": "Given my previous work as a Special Effect and Motion Capture Software Engineer, I was very tempted to build the animated avatar myself. I did actually build a simple avatar system on a separate project: Building a Bot That Plays Videos for my Toddler. Thankfully, the better part of me realised how long this would take me if I were to pursue this journey rather than to use an awesome 3D avatar software, Loom.ai, which comes with audio lip-sync capability! All you need to do is send an audio clip to the Loom.ai app and it will animate a 3D avatar to lip-sync to the provided audio. How awesome is that? The app also comes with a fake video camera driver, which streams the rendered output. I just needed to select the fake video camera in the Zoom app settings, so that I could include the animation in the Zoom meeting." }, { "code": null, "e": 22573, "s": 22175, "text": "With all the modules completed, all I needed to do was build a controller system that would combine everything. The first test ran quite well, except that Jarvis stole all the conversation. He impolitely interjected and replied to every single sentence spoken by anyone in the video conference which annoyed everyone. Well, that’s one thing I forgot to train Jarvis in — manners and social skills!" }, { "code": null, "e": 22915, "s": 22573, "text": "Rather than building another social skill module, which I had no clue how to start, an easy fix to this was to teach Jarvis to start and stop talking by a voice command. When he heard ‘Jarvis, stop talking’ he stopped responding until he heard ‘Jarvis, start talking’. With this new and important skill, everyone started to like Jarvis more." }, { "code": null, "e": 23630, "s": 22915, "text": "This generative model was fun to talk to for the first few exchanges as with some of his answers, he amazed us with his creativity and his rudeness. However, the novelty wore off quickly because the longer the conversation went on, the more we heard out of context responses, until eventually we came to the realisation that we were not engaged in a meaningful conversation at all. For this reason, I ended up using a pattern-based chatbot tech driven by the AIML language model, which surprisingly offered much better creativity than a normal retrieval-based model and could recall context from past information! This article explains clearly what it is, and perhaps it will be a story for me to tell another day." }, { "code": null, "e": 23915, "s": 23630, "text": "With the help of my super awesome Hackathon team members, we even extended Jarvis’ capability to be an on demand meeting assistant who can help taking down notes, action points assigned to relevant individuals, emailing them to meeting participants and scheduling a follow up meeting." }, { "code": null, "e": 24116, "s": 23915, "text": "Sometimes the quality of the generated text from the bot was good. However, from just two conversation exchanges (even with the good ones), you could clearly tell that something was off and unnatural." }, { "code": null, "e": 24436, "s": 24116, "text": "It did not have past context. Each response was generated from the context of the question asked. It did not consider prior conversations, which most humans can do very easily. Obviously, the technology is not there yet to build a model that can consider past conversation history. I have not heard of one yet at least." }, { "code": null, "e": 25036, "s": 24436, "text": "For more than half of the time, it gave an irrelevant response. Although a better model architecture may also be needed, however my biggest suspect is the training set. Movie dialogue has broad topics, which makes it very hard for the AI model to learn, especially when the source and target sentences sometimes do not make sense (e.g., no prior context, requiring visual reference or being incorrectly paired). A training set like a restaurant booking dialogue may work better as the scope is very limited in restaurant booking. However, the conversation exchanges will likely be less entertaining." }, { "code": null, "e": 25209, "s": 25036, "text": "Given the above, I believe a fully practical, generative chatbot is still years or decades away. I can now totally understand why it takes years for us to learn a language." }, { "code": null, "e": 25280, "s": 25209, "text": "Nevertheless, this was a very fun project and I learned a lot from it." } ]
append() and extend() in Python
The append() and extend() functions are used with the python list to increase its number of elements. But the two have different behaviors as shown below. Syntax: list_name.append(‘value’) It takes only one argument. This function appends the incoming element to the end of the list as a single new element. Even if the incoming element is itself a list, it will increase the count of the original list by only one. list = ['Mon', 'Tue', 'Wed' ] print("Existing list\n",list) # Append an element list.append('Thu') print("Appended one element: ",list) # Append a list list.append(['Fri','Sat']) print("Appended a list: ",list) Running the above code gives us the following result − Existing list ['Mon', 'Tue', 'Wed'] Appended one element: ['Mon', 'Tue', 'Wed', 'Thu'] Appended a list: ['Mon', 'Tue', 'Wed', 'Thu', ['Fri', 'Sat']] Extend adds each element to the list as an individual element. The new length of the list is incremented by the number of elements added. Syntax: list_name.extend(‘value’) It takes only one argument. list = ['Mon', 'Tue', 'Wed' ] print("Existing list\n",list) # Extend an element list.extend("Thu") print("Extended one element: ",list) # Extend a list list.extend(['Fri','Sat']) print("Extended a list: ",list) Running the above code gives us the following result − ['Mon', 'Tue', 'Wed'] Extended one element: ['Mon', 'Tue', 'Wed', 'T', 'h', 'u'] Extended a list: ['Mon', 'Tue', 'Wed', 'T', 'h', 'u', 'Fri', 'Sat']
[ { "code": null, "e": 1217, "s": 1062, "text": "The append() and extend() functions are used with the python list to increase its number of elements. But the two have different behaviors as shown below." }, { "code": null, "e": 1279, "s": 1217, "text": "Syntax: list_name.append(‘value’)\nIt takes only one argument." }, { "code": null, "e": 1478, "s": 1279, "text": "This function appends the incoming element to the end of the list as a single new element. Even if the incoming element is itself a list, it will increase the count of the original list by only one." }, { "code": null, "e": 1690, "s": 1478, "text": "list = ['Mon', 'Tue', 'Wed' ]\nprint(\"Existing list\\n\",list)\n# Append an element\nlist.append('Thu')\nprint(\"Appended one element: \",list)\n\n# Append a list\nlist.append(['Fri','Sat'])\nprint(\"Appended a list: \",list)" }, { "code": null, "e": 1745, "s": 1690, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1894, "s": 1745, "text": "Existing list\n['Mon', 'Tue', 'Wed']\nAppended one element: ['Mon', 'Tue', 'Wed', 'Thu']\nAppended a list: ['Mon', 'Tue', 'Wed', 'Thu', ['Fri', 'Sat']]" }, { "code": null, "e": 2032, "s": 1894, "text": "Extend adds each element to the list as an individual element. The new length of the list is incremented by the number of elements added." }, { "code": null, "e": 2094, "s": 2032, "text": "Syntax: list_name.extend(‘value’)\nIt takes only one argument." }, { "code": null, "e": 2306, "s": 2094, "text": "list = ['Mon', 'Tue', 'Wed' ]\nprint(\"Existing list\\n\",list)\n# Extend an element\nlist.extend(\"Thu\")\nprint(\"Extended one element: \",list)\n\n# Extend a list\nlist.extend(['Fri','Sat'])\nprint(\"Extended a list: \",list)" }, { "code": null, "e": 2361, "s": 2306, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2510, "s": 2361, "text": "['Mon', 'Tue', 'Wed']\nExtended one element: ['Mon', 'Tue', 'Wed', 'T', 'h', 'u']\nExtended a list: ['Mon', 'Tue', 'Wed', 'T', 'h', 'u', 'Fri', 'Sat']" } ]
CICS - MAP
BMS receives the data entered by the user and then formats it into a symbolic map area. The application program has access only to the data present in the symbolic map. The application program processes the data and the output is sent to the symbolic map. BMS will merge the output of the symbolic data with the physical map. Physical Map is a load module in the load library which contains information about how the map should be displayed. It contains the details about the attributes of all the fields in the map and their positions. It contains the details about the attributes of all the fields in the map and their positions. It contains the display format of the map for a given terminal. It contains the display format of the map for a given terminal. It is coded using BMS macros. It is assembled separately and link edited into the CICS library. It is coded using BMS macros. It is assembled separately and link edited into the CICS library. A Symbolic Map is a Copy book in the library. The Copy book is used by the CICS application program to send and receive data from the terminal. It contains all the variable data which is copied into program's WORKINGSTORAGE section. It contains all the variable data which is copied into program's WORKINGSTORAGE section. It has all the named fields. The application programmer uses these fields to read and write data into the map. It has all the named fields. The application programmer uses these fields to read and write data into the map. For an unprotected named field, in a map, if we have specified a length of 10, this means that the name field can take values whose length cannot exceed 10. But when you display this map using CICS and start entering values for this field on the screen, we can enter more than 10 Characters, i.e., till the end of the screen and we can enter even in the next line. To prevent this, we use Skipper field or stopper field. A Skipper field would generally be an Unnamed field of length 1, specified after a named field. If we place a skipper field after the named unprotected field, then while entering the value, once the specified length is reached, the cursor will automatically position to the next unprotected field. The following example shows how to add a skipper field − NUMBER DFHMDF POS = (01,01), X LENGTH = 5, X ATTRB = (UNPROT,IC) DFHMDF POS = (01,07), X LENGTH = 1, X ATTRB = (ASKIP) If we place a stopper field after the named unprotected field, then while entering the value, once the specified length is reached, the cursor will stop its positioning. The following example shows how to add a stopper field − NUMBER DFHMDF POS = (01,01), X LENGTH = 5, X ATTRB = (UNPROT,IC) DFHMDF POS = (01,07), X LENGTH = 1, X ATTRB = (PROT) The attribute byte of any field stores information about the physical properties of the field. The following diagram and the table explain the significance of each bit. Modified Data Tag (MDT) is the last bit in the attribute byte. MDT is a flag which holds a single bit. It specifies whether the value is to be transferred to the system or not. MDT is a flag which holds a single bit. It specifies whether the value is to be transferred to the system or not. Its default value is 1, when the field value is changed. Its default value is 1, when the field value is changed. If MDT is 0, then data cannot be transferred; and if MDT is 1, then data can be transferred. If MDT is 0, then data cannot be transferred; and if MDT is 1, then data can be transferred. The send map command writes formatted output to the terminal. It is used to send the map to the terminal from the application program. The following code segment shows how to send a map to the terminal − EXEC CICS SEND MAP('map-name') MAPSET('mapset-name') [FROM(data-area)] [LENGTH(data_value)] [DATAONLY] [MAPONLY] [CURSOR] [ERASE/ERASEAUP] [FREEKB] [FRSET] END-EXEC The following table lists the parameters used in a send map command along with their significance. Map-name It is the name of the map which we want to send. It is mandatory. Mapset-name It is the name of the map set that contains the mapname. The mapset name is needed unless it is the same as the map name. FROM It is used if we have decided to use a different DSECT name, we must use the option FROM (dsect-name) along with SEND MAP command. MAPONLY It means that no data from your program is to be merged into the map and only the information in the map is transmitted. DATAONLY It is the logical opposite of MAPONLY. We use it to modify the variable data in a display that has already been created. Only the data from your program is sent to the screen. The constants in the map are not sent. ERASE It causes the entire screen to be erased before what we are sending is shown. ERASEUP It causes only unprotected fields to be erased. FRSET Flag Reset turns off the modified data tag in the attribute byte for all the fields on the screen before what you are sending is placed there. CURSOR It can be used to position the cursor on the terminal screen. Cursor can be set by moving -1 to the L part of the field and then sending the map. ALARM It causes the audible alarm to be sounded. FREEKB. The keyboard is unlocked if we specify FREEKB in either the map or the SEND command. PRINT It allows the output of a SEND command to be printed on a printer. FORMFEED It causes the printer to restore the paper to the top of the next page before the output is printed. When we want to receive input from a terminal, we use the RECEIVE MAP command. The MAP and MAPSET parameters have exactly the same meaning as for the SEND MAP command. The following code segment shows how to receive a map − EXEC CICS RECEIVE MAP('map-name') MAPSET('mapset-name') [INTO(data-area)] [FROM(data-area)] [LENGTH(data_value)] END-EXEC The following steps are necessary to develop and execute a mapset − Step 1 − Open a TSO session. Step 1 − Open a TSO session. Step 2 − Create a new PDS. Step 2 − Create a new PDS. Step 3 − Code a mapset in a new member according to the requirement. Step 3 − Code a mapset in a new member according to the requirement. Step 4 − Assemble the mapset using the JCL provided by the CICS administrator. Step 4 − Assemble the mapset using the JCL provided by the CICS administrator. Step 5 − Open a CICS Session. Step 5 − Open a CICS Session. Step 6 − Install the program using the command − CEMT SET PROG(mapset-name) NEW Step 6 − Install the program using the command − CEMT SET PROG(mapset-name) NEW Step 7 − Type the following command to send the Map to the terminal − CECI SEND MAP(map-name) MAPSET(mapset-name) ERASE FREEKB Step 7 − Type the following command to send the Map to the terminal − CECI SEND MAP(map-name) MAPSET(mapset-name) ERASE FREEKB Print Add Notes Bookmark this page
[ { "code": null, "e": 2252, "s": 1926, "text": "BMS receives the data entered by the user and then formats it into a symbolic map area. The application program has access only to the data present in the symbolic map. The application program processes the data and the output is sent to the symbolic map. BMS will merge the output of the symbolic data with the physical map." }, { "code": null, "e": 2368, "s": 2252, "text": "Physical Map is a load module in the load library which contains information about how the map should be displayed." }, { "code": null, "e": 2463, "s": 2368, "text": "It contains the details about the attributes of all the fields in the map and their positions." }, { "code": null, "e": 2558, "s": 2463, "text": "It contains the details about the attributes of all the fields in the map and their positions." }, { "code": null, "e": 2622, "s": 2558, "text": "It contains the display format of the map for a given terminal." }, { "code": null, "e": 2686, "s": 2622, "text": "It contains the display format of the map for a given terminal." }, { "code": null, "e": 2782, "s": 2686, "text": "It is coded using BMS macros. It is assembled separately and link edited into the CICS library." }, { "code": null, "e": 2878, "s": 2782, "text": "It is coded using BMS macros. It is assembled separately and link edited into the CICS library." }, { "code": null, "e": 3022, "s": 2878, "text": "A Symbolic Map is a Copy book in the library. The Copy book is used by the CICS application program to send and receive data from the terminal." }, { "code": null, "e": 3111, "s": 3022, "text": "It contains all the variable data which is copied into program's WORKINGSTORAGE section." }, { "code": null, "e": 3200, "s": 3111, "text": "It contains all the variable data which is copied into program's WORKINGSTORAGE section." }, { "code": null, "e": 3311, "s": 3200, "text": "It has all the named fields. The application programmer uses these fields to read and write data into the map." }, { "code": null, "e": 3422, "s": 3311, "text": "It has all the named fields. The application programmer uses these fields to read and write data into the map." }, { "code": null, "e": 3939, "s": 3422, "text": "For an unprotected named field, in a map, if we have specified a length of 10, this means that the name field can take values whose length cannot exceed 10. But when you display this map using CICS and start entering values for this field on the screen, we can enter more than 10 Characters, i.e., till the end of the screen and we can enter even in the next line. To prevent this, we use Skipper field or stopper field. A Skipper field would generally be an Unnamed field of length 1, specified after a named field." }, { "code": null, "e": 4198, "s": 3939, "text": "If we place a skipper field after the named unprotected field, then while entering the value, once the specified length is reached, the cursor will automatically position to the next unprotected field. The following example shows how to add a skipper field −" }, { "code": null, "e": 4342, "s": 4198, "text": "NUMBER DFHMDF POS = (01,01), X\n LENGTH = 5, X\n ATTRB = (UNPROT,IC)\n DFHMDF POS = (01,07), X\n LENGTH = 1, X\n ATTRB = (ASKIP)" }, { "code": null, "e": 4569, "s": 4342, "text": "If we place a stopper field after the named unprotected field, then while entering the value, once the specified length is reached, the cursor will stop its positioning. The following example shows how to add a stopper field −" }, { "code": null, "e": 4708, "s": 4569, "text": "NUMBER DFHMDF POS = (01,01), X\n LENGTH = 5, X\n\tATTRB = (UNPROT,IC)\n\t DFHMDF POS = (01,07), X\n LENGTH = 1, X\n ATTRB = (PROT)" }, { "code": null, "e": 4877, "s": 4708, "text": "The attribute byte of any field stores information about the physical properties of the field. The following diagram and the table explain the significance of each bit." }, { "code": null, "e": 4940, "s": 4877, "text": "Modified Data Tag (MDT) is the last bit in the attribute byte." }, { "code": null, "e": 5054, "s": 4940, "text": "MDT is a flag which holds a single bit. It specifies whether the value is to be transferred to the system or not." }, { "code": null, "e": 5168, "s": 5054, "text": "MDT is a flag which holds a single bit. It specifies whether the value is to be transferred to the system or not." }, { "code": null, "e": 5225, "s": 5168, "text": "Its default value is 1, when the field value is changed." }, { "code": null, "e": 5282, "s": 5225, "text": "Its default value is 1, when the field value is changed." }, { "code": null, "e": 5375, "s": 5282, "text": "If MDT is 0, then data cannot be transferred; and if MDT is 1, then data can be transferred." }, { "code": null, "e": 5468, "s": 5375, "text": "If MDT is 0, then data cannot be transferred; and if MDT is 1, then data can be transferred." }, { "code": null, "e": 5672, "s": 5468, "text": "The send map command writes formatted output to the terminal. It is used to send the map to the terminal from the application program. The following code segment shows how to send a map to the terminal −" }, { "code": null, "e": 5872, "s": 5672, "text": "EXEC CICS SEND \n MAP('map-name')\n MAPSET('mapset-name')\n [FROM(data-area)]\n [LENGTH(data_value)]\n [DATAONLY]\n [MAPONLY]\n [CURSOR]\n [ERASE/ERASEAUP]\n [FREEKB] \n [FRSET]\nEND-EXEC " }, { "code": null, "e": 5971, "s": 5872, "text": "The following table lists the parameters used in a send map command along with their significance." }, { "code": null, "e": 5980, "s": 5971, "text": "Map-name" }, { "code": null, "e": 6046, "s": 5980, "text": "It is the name of the map which we want to send. It is mandatory." }, { "code": null, "e": 6058, "s": 6046, "text": "Mapset-name" }, { "code": null, "e": 6180, "s": 6058, "text": "It is the name of the map set that contains the mapname. The mapset name is needed unless it is the same as the map name." }, { "code": null, "e": 6185, "s": 6180, "text": "FROM" }, { "code": null, "e": 6316, "s": 6185, "text": "It is used if we have decided to use a different DSECT name, we must use the option FROM (dsect-name) along with SEND MAP command." }, { "code": null, "e": 6324, "s": 6316, "text": "MAPONLY" }, { "code": null, "e": 6445, "s": 6324, "text": "It means that no data from your program is to be merged into the map and only the information in the map is transmitted." }, { "code": null, "e": 6454, "s": 6445, "text": "DATAONLY" }, { "code": null, "e": 6669, "s": 6454, "text": "It is the logical opposite of MAPONLY. We use it to modify the variable data in a display that has already been created. Only the data from your program is sent to the screen. The constants in the map are not sent." }, { "code": null, "e": 6675, "s": 6669, "text": "ERASE" }, { "code": null, "e": 6753, "s": 6675, "text": "It causes the entire screen to be erased before what we are sending is shown." }, { "code": null, "e": 6761, "s": 6753, "text": "ERASEUP" }, { "code": null, "e": 6809, "s": 6761, "text": "It causes only unprotected fields to be erased." }, { "code": null, "e": 6815, "s": 6809, "text": "FRSET" }, { "code": null, "e": 6958, "s": 6815, "text": "Flag Reset turns off the modified data tag in the attribute byte for all the fields on the screen before what you are sending is placed there." }, { "code": null, "e": 6965, "s": 6958, "text": "CURSOR" }, { "code": null, "e": 7111, "s": 6965, "text": "It can be used to position the cursor on the terminal screen. Cursor can be set by moving -1 to the L part of the field and then sending the map." }, { "code": null, "e": 7117, "s": 7111, "text": "ALARM" }, { "code": null, "e": 7160, "s": 7117, "text": "It causes the audible alarm to be sounded." }, { "code": null, "e": 7168, "s": 7160, "text": "FREEKB." }, { "code": null, "e": 7253, "s": 7168, "text": "The keyboard is unlocked if we specify FREEKB in either the map or the SEND command." }, { "code": null, "e": 7259, "s": 7253, "text": "PRINT" }, { "code": null, "e": 7326, "s": 7259, "text": "It allows the output of a SEND command to be printed on a printer." }, { "code": null, "e": 7335, "s": 7326, "text": "FORMFEED" }, { "code": null, "e": 7436, "s": 7335, "text": "It causes the printer to restore the paper to the top of the next page before the output is printed." }, { "code": null, "e": 7660, "s": 7436, "text": "When we want to receive input from a terminal, we use the RECEIVE MAP command. The MAP and MAPSET parameters have exactly the same meaning as for the SEND MAP command. The following code segment shows how to receive a map −" }, { "code": null, "e": 7798, "s": 7660, "text": "EXEC CICS RECEIVE \n MAP('map-name')\n MAPSET('mapset-name')\n [INTO(data-area)]\n [FROM(data-area)]\n [LENGTH(data_value)]\nEND-EXEC" }, { "code": null, "e": 7866, "s": 7798, "text": "The following steps are necessary to develop and execute a mapset −" }, { "code": null, "e": 7895, "s": 7866, "text": "Step 1 − Open a TSO session." }, { "code": null, "e": 7924, "s": 7895, "text": "Step 1 − Open a TSO session." }, { "code": null, "e": 7951, "s": 7924, "text": "Step 2 − Create a new PDS." }, { "code": null, "e": 7978, "s": 7951, "text": "Step 2 − Create a new PDS." }, { "code": null, "e": 8047, "s": 7978, "text": "Step 3 − Code a mapset in a new member according to the requirement." }, { "code": null, "e": 8116, "s": 8047, "text": "Step 3 − Code a mapset in a new member according to the requirement." }, { "code": null, "e": 8195, "s": 8116, "text": "Step 4 − Assemble the mapset using the JCL provided by the CICS administrator." }, { "code": null, "e": 8274, "s": 8195, "text": "Step 4 − Assemble the mapset using the JCL provided by the CICS administrator." }, { "code": null, "e": 8304, "s": 8274, "text": "Step 5 − Open a CICS Session." }, { "code": null, "e": 8334, "s": 8304, "text": "Step 5 − Open a CICS Session." }, { "code": null, "e": 8414, "s": 8334, "text": "Step 6 − Install the program using the command −\nCEMT SET PROG(mapset-name) NEW" }, { "code": null, "e": 8463, "s": 8414, "text": "Step 6 − Install the program using the command −" }, { "code": null, "e": 8494, "s": 8463, "text": "CEMT SET PROG(mapset-name) NEW" }, { "code": null, "e": 8621, "s": 8494, "text": "Step 7 − Type the following command to send the Map to the terminal −\nCECI SEND MAP(map-name) MAPSET(mapset-name) ERASE FREEKB" }, { "code": null, "e": 8691, "s": 8621, "text": "Step 7 − Type the following command to send the Map to the terminal −" }, { "code": null, "e": 8748, "s": 8691, "text": "CECI SEND MAP(map-name) MAPSET(mapset-name) ERASE FREEKB" }, { "code": null, "e": 8755, "s": 8748, "text": " Print" }, { "code": null, "e": 8766, "s": 8755, "text": " Add Notes" } ]
JDBC Insert Example Program | JDBC executeUpdate() Example | OTP
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorials, we are going to understand JDBC insert program. In the previous tutorial we have implemented JDBC select Program example, it is recommended to have a look if you don’t know. To do the insert operation in JDBC, the api given us executeUpdate(String qry) and execute(String qry) methods. We can apply the both executeUpdate() aand execute() methods on statement object. executepdate() method returns the integer value. The value represents that the number of rows effected in the database. int rowsEffected = stmt.executepUpdate("insert command"); execute() method returns boolean value. As we already discussed in the JDBC select example, we can use the execute() method for both select and non-select operations. If the resultant object contains ResultSet then the execute() method returns the true, it returns false if it is an update count or no records found. boolean isResultSet = stmt.executep("insert command"); package com.onlinetutorialspoint.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class Jdbc_InsertionOperation_Example { public static void main(String[] args) throws Exception { Connection connection = null; Statement statement = null; Scanner scanner = null; try { int studentNo = 0; String studentName = null; String studentAddress = null; int studentAge = 0; scanner = new Scanner(System.in); if (scanner != null) { System.out.println("Enter Student No"); studentNo = scanner.nextInt(); System.out.println("Enter Student Name"); studentName = scanner.next(); System.out.println("Enter Student Address"); studentAddress = scanner.next(); System.out.println("Enter Student Age"); studentAge = scanner.nextInt(); } Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "systemuser23!"); if (connection != null) { statement = connection.createStatement(); String insertQuery = "insert into student values('" + studentNo + "','" + studentName +"','"+ studentAddress + "','"+studentAge+"')"; int result = statement.executeUpdate(insertQuery); if (result == 0) { System.out.println("Record Inserted Failed"); } else { System.out.println(result+ " Record(s) Inserted "); } } } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (SQLException sqe) { sqe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException sqe) { sqe.printStackTrace(); } try { if (connection != null) { connection.close(); } } catch (SQLException sqe) { sqe.printStackTrace(); } } } } Enter Student No 2003 Enter Student Name chandrashekhar Enter Student Address hyderabad Enter Student Age 30 1 Record(s) Inserted Happy Learning 🙂 Insert an Image using JDBC in Mysql DB JDBC Select Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Step by Step JDBC Program Example Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Scrollable ResultSet Example JDBC Updatable ResultSet Example Insert an Image using JDBC in Mysql DB JDBC Select Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Step by Step JDBC Program Example Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Scrollable ResultSet Example JDBC Updatable ResultSet Example Δ JDBC Driver Types Step by Step JDBC Program JDBC Select Program JDBC Insert Program JDBC Update Program JDBC Delete Program JDBC Connection – Properties File JDBC PreparedStatement Program JDBC – CallableStatement Example JDBC – Read an Image from DB JDBC – Insert an Image in DB JDBC – Updatable ResultSet JDBC – Scrollable ResultSet JDBC – ResultSetMetaData JDBC – DatabaseMetaData JDBC – Transaction Management JDBC – Batch Processing JDBC Interview Questions
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 591, "s": 398, "text": "In this tutorials, we are going to understand JDBC insert program. In the previous tutorial we have implemented JDBC select Program example, it is recommended to have a look if you don’t know." }, { "code": null, "e": 785, "s": 591, "text": "To do the insert operation in JDBC, the api given us executeUpdate(String qry) and execute(String qry) methods. We can apply the both executeUpdate() aand execute() methods on statement object." }, { "code": null, "e": 905, "s": 785, "text": "executepdate() method returns the integer value. The value represents that the number of rows effected in the database." }, { "code": null, "e": 963, "s": 905, "text": "int rowsEffected = stmt.executepUpdate(\"insert command\");" }, { "code": null, "e": 1280, "s": 963, "text": "execute() method returns boolean value. As we already discussed in the JDBC select example, we can use the execute() method for both select and non-select operations. If the resultant object contains ResultSet then the execute() method returns the true, it returns false if it is an update count or no records found." }, { "code": null, "e": 1335, "s": 1280, "text": "boolean isResultSet = stmt.executep(\"insert command\");" }, { "code": null, "e": 3926, "s": 1335, "text": "package com.onlinetutorialspoint.jdbc; \n \nimport java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.SQLException; \nimport java.sql.Statement; \nimport java.util.Scanner; \n \npublic class Jdbc_InsertionOperation_Example { \n \n public static void main(String[] args) throws Exception { \n \n Connection connection = null; \n Statement statement = null; \n Scanner scanner = null; \n \n try { \n int studentNo = 0; \n String studentName = null; \n String studentAddress = null; \n int studentAge = 0; \n scanner = new Scanner(System.in); \n if (scanner != null) { \n System.out.println(\"Enter Student No\"); \n studentNo = scanner.nextInt(); \n System.out.println(\"Enter Student Name\"); \n studentName = scanner.next(); \n System.out.println(\"Enter Student Address\"); \n studentAddress = scanner.next(); \n System.out.println(\"Enter Student Age\"); \n studentAge = scanner.nextInt(); \n } \n \n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\"); \n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\", \"systemuser23!\"); \n if (connection != null) { \n statement = connection.createStatement(); \n String insertQuery = \"insert into student values('\" + studentNo + \"','\" + studentName +\"','\"+ studentAddress + \"','\"+studentAge+\"')\"; \n int result = statement.executeUpdate(insertQuery); \n \n if (result == 0) { \n System.out.println(\"Record Inserted Failed\"); \n } else { \n System.out.println(result+ \" Record(s) Inserted \"); \n } \n } \n \n } catch (ClassNotFoundException cnfe) { \n \n cnfe.printStackTrace(); \n } catch (SQLException sqe) { \n sqe.printStackTrace(); \n \n } catch (Exception e) { \n e.printStackTrace(); \n } finally { \n try { \n if (statement != null) { \n statement.close(); \n } \n } catch (SQLException sqe) { \n sqe.printStackTrace(); \n \n } \n \n try { \n if (connection != null) { \n connection.close(); \n } \n } catch (SQLException sqe) { \n sqe.printStackTrace(); \n \n } \n \n } \n \n } \n} \n" }, { "code": null, "e": 4056, "s": 3926, "text": "Enter Student No\n2003\nEnter Student Name\nchandrashekhar\nEnter Student Address\nhyderabad\nEnter Student Age\n30\n1 Record(s) Inserted" }, { "code": null, "e": 4075, "s": 4058, "text": "Happy Learning 🙂" }, { "code": null, "e": 4580, "s": 4075, "text": "\nInsert an Image using JDBC in Mysql DB\nJDBC Select Program Example\nJDBC Update Program Example\nJDBC Delete Program Example\nJDBC PreparedStatement Example Program\nStep by Step JDBC Program Example\nRead an Image in JDBC Example\nCallableStatement in jdbc Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nTransaction Management in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\nJDBC Scrollable ResultSet Example\nJDBC Updatable ResultSet Example\n" }, { "code": null, "e": 4619, "s": 4580, "text": "Insert an Image using JDBC in Mysql DB" }, { "code": null, "e": 4647, "s": 4619, "text": "JDBC Select Program Example" }, { "code": null, "e": 4675, "s": 4647, "text": "JDBC Update Program Example" }, { "code": null, "e": 4703, "s": 4675, "text": "JDBC Delete Program Example" }, { "code": null, "e": 4742, "s": 4703, "text": "JDBC PreparedStatement Example Program" }, { "code": null, "e": 4776, "s": 4742, "text": "Step by Step JDBC Program Example" }, { "code": null, "e": 4806, "s": 4776, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 4840, "s": 4806, "text": "CallableStatement in jdbc Example" }, { "code": null, "e": 4874, "s": 4840, "text": "ResultSetMetaData in JDBC Example" }, { "code": null, "e": 4907, "s": 4874, "text": "DatabaseMetaData in JDBC Example" }, { "code": null, "e": 4946, "s": 4907, "text": "Transaction Management in JDBC Example" }, { "code": null, "e": 4979, "s": 4946, "text": "Batch Processing in JDBC Example" }, { "code": null, "e": 5016, "s": 4979, "text": "JDBC Connection with Properties file" }, { "code": null, "e": 5050, "s": 5016, "text": "JDBC Scrollable ResultSet Example" }, { "code": null, "e": 5083, "s": 5050, "text": "JDBC Updatable ResultSet Example" }, { "code": null, "e": 5089, "s": 5087, "text": "Δ" }, { "code": null, "e": 5108, "s": 5089, "text": " JDBC Driver Types" }, { "code": null, "e": 5135, "s": 5108, "text": " Step by Step JDBC Program" }, { "code": null, "e": 5156, "s": 5135, "text": " JDBC Select Program" }, { "code": null, "e": 5177, "s": 5156, "text": " JDBC Insert Program" }, { "code": null, "e": 5198, "s": 5177, "text": " JDBC Update Program" }, { "code": null, "e": 5219, "s": 5198, "text": " JDBC Delete Program" }, { "code": null, "e": 5254, "s": 5219, "text": " JDBC Connection – Properties File" }, { "code": null, "e": 5286, "s": 5254, "text": " JDBC PreparedStatement Program" }, { "code": null, "e": 5320, "s": 5286, "text": " JDBC – CallableStatement Example" }, { "code": null, "e": 5350, "s": 5320, "text": " JDBC – Read an Image from DB" }, { "code": null, "e": 5380, "s": 5350, "text": " JDBC – Insert an Image in DB" }, { "code": null, "e": 5408, "s": 5380, "text": " JDBC – Updatable ResultSet" }, { "code": null, "e": 5437, "s": 5408, "text": " JDBC – Scrollable ResultSet" }, { "code": null, "e": 5463, "s": 5437, "text": " JDBC – ResultSetMetaData" }, { "code": null, "e": 5488, "s": 5463, "text": " JDBC – DatabaseMetaData" }, { "code": null, "e": 5519, "s": 5488, "text": " JDBC – Transaction Management" }, { "code": null, "e": 5544, "s": 5519, "text": " JDBC – Batch Processing" } ]
How to tune a Decision Tree?. Hyperparameter tuning | by Mukesh Mithrakumar | Towards Data Science
How do the hyperparameters for a decision tree affect your model and how do you choose which ones to tune? Hyperparameter tuning is searching the hyperparameter space for a set of values that will optimize your model architecture. This is different from tuning your model parameters where you search your feature space that will best minimize a cost function. Hyperparameter tuning is also tricky in the sense that there is no direct way to calculate how a change in the hyperparameter value will reduce the loss of your model, so we usually resort to experimentation. This starts with us specifying a range of possible values for all the hyperparameters. Now, this is where most get stuck, what values am I going to try, and to answer that question, you first need to understand what these hyperparameters mean and how changing a hyperparameter will affect your model architecture, thereby try to understand how your model performance might change. The next step after you define the range of values is to use a hyperparameter tuning method, there’s a bunch, the most common and expensive being Grid Search where others like Random Search and Bayesian Optimization will provide a “smarter”, less expensive tuning. These methods are not really the focus of this article but if you want to learn more, check the reference section [1]. Decision Tree is one of the popular and most widely used Machine Learning Algorithms because of its robustness to noise, tolerance against missing information, handling of irrelevant, redundant predictive attribute values, low computational cost, interpretability, fast run time and robust predictors. I know, that’s a lot 😂. But a common question I get asked from students is how to tune a Decision Tree. What should be the range of values I should try for the maximum depth, what should be the minimum number of samples required at a leaf node? These are very good questions that don’t have a straightforward answer but what we can do is understand how changing one will affect your model. Like what does increasing the maximum depth really mean, what does changing the minimum sample leaves do to your model. So, in this article, I attempt to give you an introduction to these parameters and how they affect your model architecture and what it can mean to your model in general. Let’s look into Scikit-learn’s decision tree implementation and let me explain what each of these hyperparameters is and how it can affect your model. Btw note that I assume you have a basic understanding of decision trees. Since the decision tree is primarily a classification model, we will be looking into the decision tree classifier. criterion: string, optional (default=”gini”): The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain. If you ever wondered how decision tree nodes are split, it is by using impurity. Impurity is a measure of the homogeneity of the labels on a node. There are many ways to implement the impurity measure, two of which scikit-learn has implemented is the Information gain and Gini Impurity or Gini Index. Information gain uses the entropy measure as the impurity measure and splits a node such that it gives the most amount of information gain. Whereas Gini Impurity measures the divergences between the probability distributions of the target attribute’s values and splits a node such that it gives the least amount of impurity. According to the paper “Theoretical comparison between the Gini Index and Information Gain criteria” [3], the frequency of agreement/disagreement of the Gini Index and the Information Gain was only 2% of all cases, so for all intents and purposes you can pretty much use either, but the only difference is entropy might be a little slower to compute because it requires you to compute a logarithmic function: Many of the researchers point out that in most of the cases, the choice of splitting criteria will not make much difference in the tree performance. Each criterion is superior in some cases and inferior in others, as the “No Free Lunch” theorem suggests. splitter: string, optional (default=”best”) The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split. According to scikit-learn’s “best” and “random” implementation [4], both the “best” splitter and the “random” splitter uses Fisher-Yates-based algorithm to compute a permutation of the features array. You don’t really need to worry about the algorithm, the only difference is, in the “best” splitter it evaluate all splits using the criterion before splitting whereas the “random” splitter uses a random uniform function with min_feature_value, max_feature_value and random_state as inputs. We will look into what these are below but for now, let’s see how the splitter will affect the model. Let’s say you have hundreds of features, then “best” splitter would be ideal because it will calculate the best features to split based on the impurity measure and use that to split the nodes, whereas if you choose “random” you have a high chance of ending up with features that don’t really give you that much information, which would lead to a more deeper less precise tree. On the other hand, the “random” splitter has some advantages, specifically, since it selects a set of features randomly and splits, it doesn’t have the computational overhead of computing the optimal split. Next, it is also less prone to overfitting because you are not essentially calculating the best split before each split and the additional randomness will help you here, so if your model is overfitting, then you can change the splitter to “random” and retrain. So for a tree with few features without any overfitting, I would go with the “best” splitter to be safe so that you get the best possible model architecture. max_depth: int or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. The theoretical maximum depth a decision tree can achieve is one less than the number of training samples, but no algorithm will let you reach this point for obvious reasons, one big reason being overfitting. Note here that it is the number of training samples and not the number of features because the data can be split on the same feature multiple times. Let’s first talk about the default None case, if you don’t specify a depth for the tree, scikit-learn will expand the nodes until all leaves are pure, meaning the leaf will only have labels if you choose default for the min_samples_leaf, where the default value is one. Note that most of these hyperparameters are tied to one another and we will talk about the min_samples_leaf shortly. On the other hand, if you specify a min_samples_split, which we will look at next, the nodes will be expanded until all leaves contain less than the minimum number of samples. Scikit-learn will pick one over the other depending on which gives the maximum depth for your tree. There’s a lot of moving parts here, min_samples_split and min_samples_leaf so let’s just take the max_depth in isolation and see what happens to your model when you change it, so after we go through min_samples_split and min_samples_leaf we can get a better intuition of how all these come together. In general, the deeper you allow your tree to grow, the more complex your model will become because you will have more splits and it captures more information about the data and this is one of the root causes of overfitting in decision trees because your model will fit perfectly for the training data and will not be able to generalize well on test set. So, if your model is overfitting, reducing the number for max_depth is one way to combat overfitting. It is also bad to have a very low depth because your model will underfit sohow to find the best value, experiment because overfitting and underfitting are very subjective to a dataset, there is no one value fits all solution. So what I usually do is, let the model decide the max_depth first and then by comparing my train and test scores I look for overfitting or underfitting and depending on the degree I decrease or increase the max_depth. min_samples_split: int, float, optional (default=2) The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. min_samples_split and min_samples_leaf, if you read their definitions it sounds like one would imply the other, but what you need to note is a leaf is an external node and the min_samples_split talks about an internal node and by definition an internal node can have further split whereas a leaf node by definition is a node without any children. Say you specify a min_samples_split and the resulting split results in a leaf with 1 sample and you have specified min_samples_leaf as 2, then your min_samples_split will not be allowed. In other words, min_samples_leaf is always guaranteed no matter the min_samples_split value. According to the paper, An empirical study on hyperparameter tuning of decision trees [5] the ideal min_samples_split values tend to be between 1 to 40 for the CART algorithm which is the algorithm implemented in scikit-learn. min_samples_split is used to control over-fitting. Higher values prevent a model from learning relations which might be highly specific to the particular sample selected for a tree. Too high values can also lead to under-fitting hence depending on the level of underfitting or overfitting, you can tune the values for min_samples_split. min_samples_leaf: int, float, optional (default=1) The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. Similar to min_samples_split, min_samples_leaf is also used to control over-fitting by defining that each leaf has more than one element. Thus ensuring that the tree cannot overfit the training dataset by creating a bunch of small branches exclusively for one sample each. In reality, what this is actually doing is simply just telling the tree that each leaf doesn’t have to have an impurity of 0, we will look into impurity further in min_impurity_decrease. The paper, An empirical study on hyperparameter tuning of decision trees [5] also states that the ideal min_samples_leaf values tend to be between 1 to 20 for the CART algorithm. This paper also indicates that min_samples_split and min_samples_leaf are the most responsible for the performance of the final trees from their relative importance analysis [5]. According to scikit-learn, we can use min_samples_split or min_samples_leaf to ensure that multiple samples inform every decision in the tree, by controlling which splits will be considered. They also say a very small number will usually mean the tree will overfit, whereas a large number will prevent the tree from learning the data and this should make sense. I think one exception to this is when you have an imbalanced class problem because then the regions in which the minority class will be in majority will be very small so you should go with a lower value. min_weight_fraction_leaf: float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. min_weight_fraction_leaf is the fraction of the input samples required to be at a leaf node where weights are determined by sample_weight, this is a way to deal with class imbalance. Class balancing can be done by sampling an equal number of samples from each class, or preferably by normalizing the sum of the sample weights for each class to the same value. Also note that min_weight_fraction_leaf will then be less biased toward dominant classes than criteria that are not aware of the sample weights, like min_samples_leaf. If the samples are weighted, it will be easier to optimize the tree structure using weight-based pre-pruning criterion such as min_weight_fraction_leaf, which ensure that leaf nodes contain at least a fraction of the overall sum of the sample weights. max_features: int, float, string or None, optional (default=None) The number of features to consider when looking for the best split: If int, then consider max_features features at each split. If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split. If “auto”, then max_features=sqrt(n_features). If “sqrt”, then max_features=sqrt(n_features). If “log2”, then max_features=log2(n_features). If None, then max_features=n_features. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features. Every time there is a split, your algorithm looks at a number of features and takes the one with the optimal metric using gini impurity or entropy, and creates two branches according to that feature. It is computationally heavy to look at all the features every single time, so you can just check some of them using the various max_features options. Another use of max_features is to limit overfitting, by choosing a reduced number of features we can increase the stability of the tree and reduce variance and over-fitting. As for among the options which one to pick, it will depend on the number of features you have, the computational intensity you want to reduce or the amount of overfitting you have, so if you have a high computational cost or you have a lot of overfitting, you can try with “log2” and depending on what that produces, you can either bring it slightly up using sqrt or take it down further using a custom float value. random_state: int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Haha the notorious random_state, most novices ask me this, why 1, why 0 or why 42? 42 because that is the meaning of life, duh. random_state is not really a hyperparameter to tune, or should you 😋. Let me start with when and why you should set a random_state. The most straightforward answer is so you can get consistent results, well somewhat because remember splitter, it will introduce some randomness to your results so if you rerun your decision tree, your results will be different, but it should not be too different. That brings to my next point, I have seen new students play around with random_state values and their accuracy changes, it can happen because the decision tree algorithm is based on the greedy algorithm [6] where it is repeated a number of times using a random selection of features (splitter) and this random selection is affected by the pseudo-random number generator [7] which takes in the random_state value as a seed value, so by changing the random_state you might randomly pick good features, but what you need to realize is, random_state is not a hyperparameter, the changing of the accuracy of your model with the random_state just means there is something wrong with your model. It is a good hint that there are many local minima in your data and the decision tree is not dealing with it very well so I would rather have you set a random_state and tune your other parameters so that you don’t get stuck in local minima than play around with the random_state. min_impurity_decrease: float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child. N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed. min_impurity_decrease helps us control how deep our tree grows based on the impurity. But, what is this impurity and how does this affect our decision tree? Remember in the criterion section we quickly looked at Gini Index and Entropy, well, these are a measure of impurity. The impurity measure defines how well a number of classes are separated. In general, the impurity measure should be largest when data are split evenly for attribute values and should be zero when all data belong to the same class. A more detailed explanation will require us to go into information theory further which is not the scope of this article, so I will try to explain how changing the impurity values affect your model and how to know when to change these values. The best way to tune this is to plot the decision tree and look into the gini index. Interpreting a decision tree should be fairly easy if you have the domain knowledge on the dataset you are working with because a leaf node will have 0 gini index because it is pure, meaning all the samples belong to one class. Then you can look into the splits that lead to 0 gini index and see if it makes sense to classify your classes as such or whether you can reduce the depth thereby leading to a more generalizable tree, if so, you can increase the min_impurity_decrease to prevent further division because now, the node will not be further split if the impurity doesn’t decrease by the amount you specified. Note that this will affect your whole tree, so, you have to experiment with the numbers but the above explanation should give you a starting point. class_weight: dict, list of dicts, “balanced” or None, default=None Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. class_weight is used to provide a weight or bias for each output class. But what does this actually mean, see when the algorithm calculates the entropy or gini impurity to make the split at a node, the resulting child nodes are weighted by the class_weight giving the child samples weights based on the class proportion you specify. This can be highly useful when you have an imbalanced dataset. Usually, you can just start with the distribution of your classes as the class weights and then depending on where your decision tree lean, you can try to increase or decrease the other class weights so that the algorithm penalizes samples of one class relative to the other. The simplest way is to specify “balanced” and then go on from there with custom weights. Note that this isn’t like an undersampling or oversampling technique, the number of samples in a class doesn’t actually change, its the weight assigned to it that does, you can see this when you print the decision tree and the values in each node, and it will change to weight * (the number of samples from a class in the node) / (size of class) presort: bool, optional (default=False) Whether to presort the data to speed up the finding of best splits in fitting. For the default settings of a decision tree on large datasets, setting this to true may slow down the training process. When using either a smaller dataset or a restricted depth, this may speed up the training. This parameter is fairly straightforward, if you have a small dataset or if you will restrict the depth of the tree and after running your first iteration you have an unbalanced tree where most data points are sitting on only a small portion of leaf nodes, using presort will help you. The way presort works is it will initially sort all the variables before learning and at each node evaluation use sorted vectors, and after one choose the best split, you will split the data points and also the sorted indexes, in order to send to the child nodes the subset of data and subsets of sorted indexes. Thus you can apply this idea in recursion. Note however that this works if the number of data instances is greater than the number of input features. The Decision tree complexity has a crucial effect on its accuracy and it is explicitly controlled by the stopping criteria used and the pruning method employed. Usually, the tree complexity is measured by one of the following metrics: the total number of nodes, total number of leaves, tree depth and number of attributes used [8]. max_depth, min_samples_split, and min_samples_leaf are all stopping criteria whereas min_weight_fraction_leaf and min_impurity_decrease are pruning methods. Even though all of this pretty much implements either the stopping or pruning method, it varies on the level applied to the model. If you have a hard stopping criterion your model might end up under fitting so if you change it to a loose stopping criteria then your model may overfit, that is why we have the pruning methods. We should have a loose stopping criterion and then use pruning to remove branches that contribute to overfitting. But note that pruning is a tradeoff between accuracy and generalizability, so your train scores might lower but the difference between train and test scores will also get lower. I hope you have a better idea of these parameters and how they might interact with each other when you are tuning the hyperparameters. But if something is not clear, please let me know in the comments and I would be more than happy to explain further. Feel free to add me on LinkedIn or follow me on Facebook. [1] Hyperparameter tuning for machine learning models. [2] Scikit-learn DecisionTreeClassifier [3] Laura Elena Raileanu and Kilian Stoffel, “Theoretical comparison between the Gini Index and Information Gain criteria” Annals of Mathematics and Artificial Intelligence 41: 77–93, 2004. [4] Scikit-Learn Splitter Implementation [5] Rafael Gomes Mantovani, Tomáš Horváth, Ricardo Cerri, Sylvio Barbon Junior, Joaquin Vanschoren, André Carlos Ponce de Leon Ferreira de Carvalho, “An empirical study on hyperparameter tuning of decision trees” arXiv:1812.02207 [6] Greedy algorithm [7] Pseudorandom number generator [8] Lior Rokach, Oded Maimon, “Chapter 9: Decision Tree”
[ { "code": null, "e": 279, "s": 172, "text": "How do the hyperparameters for a decision tree affect your model and how do you choose which ones to tune?" }, { "code": null, "e": 403, "s": 279, "text": "Hyperparameter tuning is searching the hyperparameter space for a set of values that will optimize your model architecture." }, { "code": null, "e": 532, "s": 403, "text": "This is different from tuning your model parameters where you search your feature space that will best minimize a cost function." }, { "code": null, "e": 1122, "s": 532, "text": "Hyperparameter tuning is also tricky in the sense that there is no direct way to calculate how a change in the hyperparameter value will reduce the loss of your model, so we usually resort to experimentation. This starts with us specifying a range of possible values for all the hyperparameters. Now, this is where most get stuck, what values am I going to try, and to answer that question, you first need to understand what these hyperparameters mean and how changing a hyperparameter will affect your model architecture, thereby try to understand how your model performance might change." }, { "code": null, "e": 1506, "s": 1122, "text": "The next step after you define the range of values is to use a hyperparameter tuning method, there’s a bunch, the most common and expensive being Grid Search where others like Random Search and Bayesian Optimization will provide a “smarter”, less expensive tuning. These methods are not really the focus of this article but if you want to learn more, check the reference section [1]." }, { "code": null, "e": 2488, "s": 1506, "text": "Decision Tree is one of the popular and most widely used Machine Learning Algorithms because of its robustness to noise, tolerance against missing information, handling of irrelevant, redundant predictive attribute values, low computational cost, interpretability, fast run time and robust predictors. I know, that’s a lot 😂. But a common question I get asked from students is how to tune a Decision Tree. What should be the range of values I should try for the maximum depth, what should be the minimum number of samples required at a leaf node? These are very good questions that don’t have a straightforward answer but what we can do is understand how changing one will affect your model. Like what does increasing the maximum depth really mean, what does changing the minimum sample leaves do to your model. So, in this article, I attempt to give you an introduction to these parameters and how they affect your model architecture and what it can mean to your model in general." }, { "code": null, "e": 2712, "s": 2488, "text": "Let’s look into Scikit-learn’s decision tree implementation and let me explain what each of these hyperparameters is and how it can affect your model. Btw note that I assume you have a basic understanding of decision trees." }, { "code": null, "e": 2827, "s": 2712, "text": "Since the decision tree is primarily a classification model, we will be looking into the decision tree classifier." }, { "code": null, "e": 2873, "s": 2827, "text": "criterion: string, optional (default=”gini”):" }, { "code": null, "e": 3013, "s": 2873, "text": "The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain." }, { "code": null, "e": 3314, "s": 3013, "text": "If you ever wondered how decision tree nodes are split, it is by using impurity. Impurity is a measure of the homogeneity of the labels on a node. There are many ways to implement the impurity measure, two of which scikit-learn has implemented is the Information gain and Gini Impurity or Gini Index." }, { "code": null, "e": 3639, "s": 3314, "text": "Information gain uses the entropy measure as the impurity measure and splits a node such that it gives the most amount of information gain. Whereas Gini Impurity measures the divergences between the probability distributions of the target attribute’s values and splits a node such that it gives the least amount of impurity." }, { "code": null, "e": 4048, "s": 3639, "text": "According to the paper “Theoretical comparison between the Gini Index and Information Gain criteria” [3], the frequency of agreement/disagreement of the Gini Index and the Information Gain was only 2% of all cases, so for all intents and purposes you can pretty much use either, but the only difference is entropy might be a little slower to compute because it requires you to compute a logarithmic function:" }, { "code": null, "e": 4303, "s": 4048, "text": "Many of the researchers point out that in most of the cases, the choice of splitting criteria will not make much difference in the tree performance. Each criterion is superior in some cases and inferior in others, as the “No Free Lunch” theorem suggests." }, { "code": null, "e": 4347, "s": 4303, "text": "splitter: string, optional (default=”best”)" }, { "code": null, "e": 4502, "s": 4347, "text": "The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split." }, { "code": null, "e": 5095, "s": 4502, "text": "According to scikit-learn’s “best” and “random” implementation [4], both the “best” splitter and the “random” splitter uses Fisher-Yates-based algorithm to compute a permutation of the features array. You don’t really need to worry about the algorithm, the only difference is, in the “best” splitter it evaluate all splits using the criterion before splitting whereas the “random” splitter uses a random uniform function with min_feature_value, max_feature_value and random_state as inputs. We will look into what these are below but for now, let’s see how the splitter will affect the model." }, { "code": null, "e": 5472, "s": 5095, "text": "Let’s say you have hundreds of features, then “best” splitter would be ideal because it will calculate the best features to split based on the impurity measure and use that to split the nodes, whereas if you choose “random” you have a high chance of ending up with features that don’t really give you that much information, which would lead to a more deeper less precise tree." }, { "code": null, "e": 5940, "s": 5472, "text": "On the other hand, the “random” splitter has some advantages, specifically, since it selects a set of features randomly and splits, it doesn’t have the computational overhead of computing the optimal split. Next, it is also less prone to overfitting because you are not essentially calculating the best split before each split and the additional randomness will help you here, so if your model is overfitting, then you can change the splitter to “random” and retrain." }, { "code": null, "e": 6098, "s": 5940, "text": "So for a tree with few features without any overfitting, I would go with the “best” splitter to be safe so that you get the best possible model architecture." }, { "code": null, "e": 6146, "s": 6098, "text": "max_depth: int or None, optional (default=None)" }, { "code": null, "e": 6301, "s": 6146, "text": "The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples." }, { "code": null, "e": 6659, "s": 6301, "text": "The theoretical maximum depth a decision tree can achieve is one less than the number of training samples, but no algorithm will let you reach this point for obvious reasons, one big reason being overfitting. Note here that it is the number of training samples and not the number of features because the data can be split on the same feature multiple times." }, { "code": null, "e": 7622, "s": 6659, "text": "Let’s first talk about the default None case, if you don’t specify a depth for the tree, scikit-learn will expand the nodes until all leaves are pure, meaning the leaf will only have labels if you choose default for the min_samples_leaf, where the default value is one. Note that most of these hyperparameters are tied to one another and we will talk about the min_samples_leaf shortly. On the other hand, if you specify a min_samples_split, which we will look at next, the nodes will be expanded until all leaves contain less than the minimum number of samples. Scikit-learn will pick one over the other depending on which gives the maximum depth for your tree. There’s a lot of moving parts here, min_samples_split and min_samples_leaf so let’s just take the max_depth in isolation and see what happens to your model when you change it, so after we go through min_samples_split and min_samples_leaf we can get a better intuition of how all these come together." }, { "code": null, "e": 8079, "s": 7622, "text": "In general, the deeper you allow your tree to grow, the more complex your model will become because you will have more splits and it captures more information about the data and this is one of the root causes of overfitting in decision trees because your model will fit perfectly for the training data and will not be able to generalize well on test set. So, if your model is overfitting, reducing the number for max_depth is one way to combat overfitting." }, { "code": null, "e": 8523, "s": 8079, "text": "It is also bad to have a very low depth because your model will underfit sohow to find the best value, experiment because overfitting and underfitting are very subjective to a dataset, there is no one value fits all solution. So what I usually do is, let the model decide the max_depth first and then by comparing my train and test scores I look for overfitting or underfitting and depending on the degree I decrease or increase the max_depth." }, { "code": null, "e": 8575, "s": 8523, "text": "min_samples_split: int, float, optional (default=2)" }, { "code": null, "e": 8641, "s": 8575, "text": "The minimum number of samples required to split an internal node:" }, { "code": null, "e": 8704, "s": 8641, "text": "If int, then consider min_samples_split as the minimum number." }, { "code": null, "e": 8841, "s": 8704, "text": "If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split." }, { "code": null, "e": 9188, "s": 8841, "text": "min_samples_split and min_samples_leaf, if you read their definitions it sounds like one would imply the other, but what you need to note is a leaf is an external node and the min_samples_split talks about an internal node and by definition an internal node can have further split whereas a leaf node by definition is a node without any children." }, { "code": null, "e": 9468, "s": 9188, "text": "Say you specify a min_samples_split and the resulting split results in a leaf with 1 sample and you have specified min_samples_leaf as 2, then your min_samples_split will not be allowed. In other words, min_samples_leaf is always guaranteed no matter the min_samples_split value." }, { "code": null, "e": 10032, "s": 9468, "text": "According to the paper, An empirical study on hyperparameter tuning of decision trees [5] the ideal min_samples_split values tend to be between 1 to 40 for the CART algorithm which is the algorithm implemented in scikit-learn. min_samples_split is used to control over-fitting. Higher values prevent a model from learning relations which might be highly specific to the particular sample selected for a tree. Too high values can also lead to under-fitting hence depending on the level of underfitting or overfitting, you can tune the values for min_samples_split." }, { "code": null, "e": 10083, "s": 10032, "text": "min_samples_leaf: int, float, optional (default=1)" }, { "code": null, "e": 10366, "s": 10083, "text": "The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression." }, { "code": null, "e": 10428, "s": 10366, "text": "If int, then consider min_samples_leaf as the minimum number." }, { "code": null, "e": 10562, "s": 10428, "text": "If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node." }, { "code": null, "e": 11022, "s": 10562, "text": "Similar to min_samples_split, min_samples_leaf is also used to control over-fitting by defining that each leaf has more than one element. Thus ensuring that the tree cannot overfit the training dataset by creating a bunch of small branches exclusively for one sample each. In reality, what this is actually doing is simply just telling the tree that each leaf doesn’t have to have an impurity of 0, we will look into impurity further in min_impurity_decrease." }, { "code": null, "e": 11380, "s": 11022, "text": "The paper, An empirical study on hyperparameter tuning of decision trees [5] also states that the ideal min_samples_leaf values tend to be between 1 to 20 for the CART algorithm. This paper also indicates that min_samples_split and min_samples_leaf are the most responsible for the performance of the final trees from their relative importance analysis [5]." }, { "code": null, "e": 11946, "s": 11380, "text": "According to scikit-learn, we can use min_samples_split or min_samples_leaf to ensure that multiple samples inform every decision in the tree, by controlling which splits will be considered. They also say a very small number will usually mean the tree will overfit, whereas a large number will prevent the tree from learning the data and this should make sense. I think one exception to this is when you have an imbalanced class problem because then the regions in which the minority class will be in majority will be very small so you should go with a lower value." }, { "code": null, "e": 12001, "s": 11946, "text": "min_weight_fraction_leaf: float, optional (default=0.)" }, { "code": null, "e": 12179, "s": 12001, "text": "The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided." }, { "code": null, "e": 12707, "s": 12179, "text": "min_weight_fraction_leaf is the fraction of the input samples required to be at a leaf node where weights are determined by sample_weight, this is a way to deal with class imbalance. Class balancing can be done by sampling an equal number of samples from each class, or preferably by normalizing the sum of the sample weights for each class to the same value. Also note that min_weight_fraction_leaf will then be less biased toward dominant classes than criteria that are not aware of the sample weights, like min_samples_leaf." }, { "code": null, "e": 12959, "s": 12707, "text": "If the samples are weighted, it will be easier to optimize the tree structure using weight-based pre-pruning criterion such as min_weight_fraction_leaf, which ensure that leaf nodes contain at least a fraction of the overall sum of the sample weights." }, { "code": null, "e": 13025, "s": 12959, "text": "max_features: int, float, string or None, optional (default=None)" }, { "code": null, "e": 13093, "s": 13025, "text": "The number of features to consider when looking for the best split:" }, { "code": null, "e": 13152, "s": 13093, "text": "If int, then consider max_features features at each split." }, { "code": null, "e": 13268, "s": 13152, "text": "If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split." }, { "code": null, "e": 13315, "s": 13268, "text": "If “auto”, then max_features=sqrt(n_features)." }, { "code": null, "e": 13362, "s": 13315, "text": "If “sqrt”, then max_features=sqrt(n_features)." }, { "code": null, "e": 13409, "s": 13362, "text": "If “log2”, then max_features=log2(n_features)." }, { "code": null, "e": 13448, "s": 13409, "text": "If None, then max_features=n_features." }, { "code": null, "e": 13632, "s": 13448, "text": "Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features." }, { "code": null, "e": 14156, "s": 13632, "text": "Every time there is a split, your algorithm looks at a number of features and takes the one with the optimal metric using gini impurity or entropy, and creates two branches according to that feature. It is computationally heavy to look at all the features every single time, so you can just check some of them using the various max_features options. Another use of max_features is to limit overfitting, by choosing a reduced number of features we can increase the stability of the tree and reduce variance and over-fitting." }, { "code": null, "e": 14572, "s": 14156, "text": "As for among the options which one to pick, it will depend on the number of features you have, the computational intensity you want to reduce or the amount of overfitting you have, so if you have a high computational cost or you have a lot of overfitting, you can try with “log2” and depending on what that produces, you can either bring it slightly up using sqrt or take it down further using a custom float value." }, { "code": null, "e": 14645, "s": 14572, "text": "random_state: int, RandomState instance or None, optional (default=None)" }, { "code": null, "e": 14869, "s": 14645, "text": "If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random." }, { "code": null, "e": 14997, "s": 14869, "text": "Haha the notorious random_state, most novices ask me this, why 1, why 0 or why 42? 42 because that is the meaning of life, duh." }, { "code": null, "e": 15394, "s": 14997, "text": "random_state is not really a hyperparameter to tune, or should you 😋. Let me start with when and why you should set a random_state. The most straightforward answer is so you can get consistent results, well somewhat because remember splitter, it will introduce some randomness to your results so if you rerun your decision tree, your results will be different, but it should not be too different." }, { "code": null, "e": 16363, "s": 15394, "text": "That brings to my next point, I have seen new students play around with random_state values and their accuracy changes, it can happen because the decision tree algorithm is based on the greedy algorithm [6] where it is repeated a number of times using a random selection of features (splitter) and this random selection is affected by the pseudo-random number generator [7] which takes in the random_state value as a seed value, so by changing the random_state you might randomly pick good features, but what you need to realize is, random_state is not a hyperparameter, the changing of the accuracy of your model with the random_state just means there is something wrong with your model. It is a good hint that there are many local minima in your data and the decision tree is not dealing with it very well so I would rather have you set a random_state and tune your other parameters so that you don’t get stuck in local minima than play around with the random_state." }, { "code": null, "e": 16415, "s": 16363, "text": "min_impurity_decrease: float, optional (default=0.)" }, { "code": null, "e": 16522, "s": 16415, "text": "A node will be split if this split induces a decrease of the impurity greater than or equal to this value." }, { "code": null, "e": 16580, "s": 16522, "text": "The weighted impurity decrease equation is the following:" }, { "code": null, "e": 16682, "s": 16580, "text": "N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity)" }, { "code": null, "e": 16877, "s": 16682, "text": "where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child." }, { "code": null, "e": 16960, "s": 16877, "text": "N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed." }, { "code": null, "e": 17709, "s": 16960, "text": "min_impurity_decrease helps us control how deep our tree grows based on the impurity. But, what is this impurity and how does this affect our decision tree? Remember in the criterion section we quickly looked at Gini Index and Entropy, well, these are a measure of impurity. The impurity measure defines how well a number of classes are separated. In general, the impurity measure should be largest when data are split evenly for attribute values and should be zero when all data belong to the same class. A more detailed explanation will require us to go into information theory further which is not the scope of this article, so I will try to explain how changing the impurity values affect your model and how to know when to change these values." }, { "code": null, "e": 18559, "s": 17709, "text": "The best way to tune this is to plot the decision tree and look into the gini index. Interpreting a decision tree should be fairly easy if you have the domain knowledge on the dataset you are working with because a leaf node will have 0 gini index because it is pure, meaning all the samples belong to one class. Then you can look into the splits that lead to 0 gini index and see if it makes sense to classify your classes as such or whether you can reduce the depth thereby leading to a more generalizable tree, if so, you can increase the min_impurity_decrease to prevent further division because now, the node will not be further split if the impurity doesn’t decrease by the amount you specified. Note that this will affect your whole tree, so, you have to experiment with the numbers but the above explanation should give you a starting point." }, { "code": null, "e": 18627, "s": 18559, "text": "class_weight: dict, list of dicts, “balanced” or None, default=None" }, { "code": null, "e": 18851, "s": 18627, "text": "Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y." }, { "code": null, "e": 19184, "s": 18851, "text": "class_weight is used to provide a weight or bias for each output class. But what does this actually mean, see when the algorithm calculates the entropy or gini impurity to make the split at a node, the resulting child nodes are weighted by the class_weight giving the child samples weights based on the class proportion you specify." }, { "code": null, "e": 19612, "s": 19184, "text": "This can be highly useful when you have an imbalanced dataset. Usually, you can just start with the distribution of your classes as the class weights and then depending on where your decision tree lean, you can try to increase or decrease the other class weights so that the algorithm penalizes samples of one class relative to the other. The simplest way is to specify “balanced” and then go on from there with custom weights." }, { "code": null, "e": 19882, "s": 19612, "text": "Note that this isn’t like an undersampling or oversampling technique, the number of samples in a class doesn’t actually change, its the weight assigned to it that does, you can see this when you print the decision tree and the values in each node, and it will change to" }, { "code": null, "e": 19958, "s": 19882, "text": "weight * (the number of samples from a class in the node) / (size of class)" }, { "code": null, "e": 19998, "s": 19958, "text": "presort: bool, optional (default=False)" }, { "code": null, "e": 20288, "s": 19998, "text": "Whether to presort the data to speed up the finding of best splits in fitting. For the default settings of a decision tree on large datasets, setting this to true may slow down the training process. When using either a smaller dataset or a restricted depth, this may speed up the training." }, { "code": null, "e": 20574, "s": 20288, "text": "This parameter is fairly straightforward, if you have a small dataset or if you will restrict the depth of the tree and after running your first iteration you have an unbalanced tree where most data points are sitting on only a small portion of leaf nodes, using presort will help you." }, { "code": null, "e": 21037, "s": 20574, "text": "The way presort works is it will initially sort all the variables before learning and at each node evaluation use sorted vectors, and after one choose the best split, you will split the data points and also the sorted indexes, in order to send to the child nodes the subset of data and subsets of sorted indexes. Thus you can apply this idea in recursion. Note however that this works if the number of data instances is greater than the number of input features." }, { "code": null, "e": 21526, "s": 21037, "text": "The Decision tree complexity has a crucial effect on its accuracy and it is explicitly controlled by the stopping criteria used and the pruning method employed. Usually, the tree complexity is measured by one of the following metrics: the total number of nodes, total number of leaves, tree depth and number of attributes used [8]. max_depth, min_samples_split, and min_samples_leaf are all stopping criteria whereas min_weight_fraction_leaf and min_impurity_decrease are pruning methods." }, { "code": null, "e": 22144, "s": 21526, "text": "Even though all of this pretty much implements either the stopping or pruning method, it varies on the level applied to the model. If you have a hard stopping criterion your model might end up under fitting so if you change it to a loose stopping criteria then your model may overfit, that is why we have the pruning methods. We should have a loose stopping criterion and then use pruning to remove branches that contribute to overfitting. But note that pruning is a tradeoff between accuracy and generalizability, so your train scores might lower but the difference between train and test scores will also get lower." }, { "code": null, "e": 22396, "s": 22144, "text": "I hope you have a better idea of these parameters and how they might interact with each other when you are tuning the hyperparameters. But if something is not clear, please let me know in the comments and I would be more than happy to explain further." }, { "code": null, "e": 22454, "s": 22396, "text": "Feel free to add me on LinkedIn or follow me on Facebook." }, { "code": null, "e": 22509, "s": 22454, "text": "[1] Hyperparameter tuning for machine learning models." }, { "code": null, "e": 22549, "s": 22509, "text": "[2] Scikit-learn DecisionTreeClassifier" }, { "code": null, "e": 22739, "s": 22549, "text": "[3] Laura Elena Raileanu and Kilian Stoffel, “Theoretical comparison between the Gini Index and Information Gain criteria” Annals of Mathematics and Artificial Intelligence 41: 77–93, 2004." }, { "code": null, "e": 22780, "s": 22739, "text": "[4] Scikit-Learn Splitter Implementation" }, { "code": null, "e": 23014, "s": 22780, "text": "[5] Rafael Gomes Mantovani, Tomáš Horváth, Ricardo Cerri, Sylvio Barbon Junior, Joaquin Vanschoren, André Carlos Ponce de Leon Ferreira de Carvalho, “An empirical study on hyperparameter tuning of decision trees” arXiv:1812.02207" }, { "code": null, "e": 23035, "s": 23014, "text": "[6] Greedy algorithm" }, { "code": null, "e": 23069, "s": 23035, "text": "[7] Pseudorandom number generator" } ]
Iterate Your R Code Efficiently!. A step-by-step guide to perform clean... | by Manasi Mahadik | Towards Data Science
Inuits do not actually have a hundred names for snow. Turns out that’s part myth and part misunderstanding. Expanding a similar analogy to web speak, there are about a hundred ways to iterate code! To add to this, the syntax can be confusing and some of us also run the risk of just lazily resorting to copy-pasting the code 4 times. But it is important to recognise that this is a sub-optimal route and frankly impractical. As a general rule of thumb, if we need to run a block of code more than two times, it is a good idea to iterate! Here are two reasons why this will make your code richer- It draws attention to the part of code that is different, thus making it easier to spot the intent of the operation.Due to its concise nature, you’re likely to encounter fewer bugs. It draws attention to the part of code that is different, thus making it easier to spot the intent of the operation. Due to its concise nature, you’re likely to encounter fewer bugs. It might take some time to wrap your head around the idea of iterating, but trust me, it’s worth the investment. Now that you’re convinced to iterate — let’s jump right in! Let’s pick the inbuilt R dataset- air quality. A snippet of the same is presented below- Ozone Solar.R Wind Temp Month Day 41 190 7.4 67 5 1 36 118 8.0 72 5 2 12 149 12.6 74 5 3 18 313 11.5 62 5 4 23 299 8.6 65 5 7 19 99 13.8 59 5 8 Problem 1: You want to find the standard deviation for each variable in the dataset- You could copy-paste the same code for each column- sd(airquality$Ozone) 33.27597sd(airquality$Solar.R)91.1523sd(airquality$Wind)3.557713sd(airquality$Temp)9.529969sd(airquality$Month)1.473434sd(airquality$Day)8.707194 This is however impractical for large data sets and breaks the rule of thumb of not running the same operation more than twice. We have a solid case to iterate! We can write a for()loop- stddev = vector("double", ncol(airquality))for(i in seq_along(airquality)) { stddev[[i]] = sd(airquality[[i]]) }stddev33.275969 91.152302 3.557713 9.529969 1.473434 8.707194 The loop does away with any repetition and is indeed more efficient than the first approach. It is also imperative to pause and note that while seq_along()and length() are mostly used interchangeably to build a sequence in the for loop, there is one key difference. In case of a zero-length vector, seq_along() does the right thing, but length() takes the value of 0 and 1. Although you probably won’t create a zero-length vector deliberately, it’s easy to create them accidentally. If you use 1:length() instead of seq_along(), you’re likely to get a confusing error message Or you could just skip the loop and do the trick with just a line of code using sapply() from base R’s apply()family - sapply(airquality, sd) Ozone Solar.R Wind Temp Month Day 33.275969 91.152302 3.557713 9.529969 1.473434 8.707194 This is a great application of R’s functional programming capabilities and indeed does the job very neatly. Let’s now take another step on the ladder of complexity and look at another problem. Problem 2: You want to find the standard deviation and median of each column in your dataset. Since we have established that the first approach of copy-pasting is impractical, we weigh in on our iteration options. We start by writing a for()loop- stddev =vector("double", ncol(airquality)) median =vector("double", ncol(airquality))for(i in seq_along(airquality)) { stddev[[i]] = sd(airquality[[i]]) median[[i]] = median(airquality[[i]]) } stddev 33.275969 91.152302 3.557713 9.529969 1.473434 8.707194 median 31.0 207.0 9.7 79.0 7.0 16.0 Next, we take the functional programming route. Here, unlike the earlier example where we could directly use R’s inbuilt sd() function to calculate the standard deviation and pass it through sapply() , we need to create a custom function, as we need to calculate both the standard deviation and the median. f <- function(x){ list(sd(x),median(x)) }sapply(airquality, f)Ozone Solar.R Wind Temp Month Day 33.27597 91.1523 3.557713 9.529969 1.473434 8.70719431 207 9.7 79 7 16 This is a very solid idea! The ability to pass a user built function to another function is thrilling and clearly showcases R’s functional programming capabilities to solve a wide variety of tasks. In fact, seasoned R users rarely ever use loops and resort to functional programming techniques to solve all iterative tasks. As used above, apply family of functions in base R (apply(), lapply(), tapply(), etc) are a great way to go about this, but even in the functional programming universe there is one package which has emerged as a favorite — Purrr. The purrr family of functions has more consistent syntax and has in built functionalities to carry out a wide variety of common iterative tasks. The Map() functions form the cornerstone of the purrr’s iterative capabilities. Here are some of the forms it takes- map() makes a list. map_lgl() makes a logical vector. map_int() makes an integer vector. map_dbl() makes a double vector. map_chr() makes a character vector. Let’s use this idea to solve our earlier problem of calculating the median and standard deviation of each column- map_df(airquality, ~list(med = median(.x), sd = sd(.x))) Next, in order to another leap on the complexity ladder let’s pick the gapminder dataset from the gapminder library. A snippet of the same is presented below.(P.S- If you haven’t heard about the gapminder foundation, do check its website out here . The foundation does some groundbreaking work on putting basic global facts into context) country continent year lifeExp pop gdpPercap Afghanistan Asia 1952 28.8 8425333 779. Afghanistan Asia 1957 30.3 9240934 821. Afghanistan Asia 1962 32.0 10267083 853. Afghanistan Asia 1967 34.0 11537966 836. Afghanistan Asia 1972 36.1 13079460 740. Afghanistan Asia 1977 38.4 14880372 786. Problem 3: I want to know which country has the highest GDP Per Capita in each continent and in each year. Using the for() loop approach- list = c(“continent”, “year”)DF= data.frame()for( i in list){ df = gapminder %>% group_by_at(i) %>% top_n(1, gdpPercap) %>% mutate(Remark = paste0(“Country Max GDP Per capita in the “,i)) %>% data.frame() DF = rbind(df,DF)}DF Using the Apply()approach- do.call(rbind, lapply(list, function(x){ gapminder %>% group_by_at(x) %>% top_n(1, gdpPercap)%>% mutate(Remark = paste0("Country with the max GDP Per capita in the ",x)) %>% data.frame})) Using the Purrr::Map() approach- gapminder$year = as.character(gapminder$year)map_dfr(list, ~gapminder %>% group_by(!!sym(.x)) %>% top_n(1, gdpPercap)%>% mutate(Remark = paste0(“Country with the max GDP Per capita in the “,.x)) %>% data.frame() All of the above three approaches lead to the same output (For the sake of brevity, I am not including the output here. You can have a look at it on my Github here). Again, while you can take your pick on which iterative route you want to take, the functional programming way is a clear winner on cogency. Purrr also has some inbuilt functions to deal with everyday iterative tasks! Below I have listed down a few popular ones. Task: Run a piecewise regression for each segment of the data. (Here, continent): Purrr solution: gapminder %>% split(.$Continent) %>% map(~lm(gdpPercap ~ lifeExp, data = .)) Task: Keep variables basis an arbitrary condition. (Here, if the variable is a factor): Purrr solution: gapminder %>% keep(is.factor) %>% str() Task: Check if any variable meets the arbitrary condition(Here, if any variable is a character): Purrr solution: gapminder%>% some(is_character) Task: Check if every variable meets the arbitrary condition(Here, if every variable is an integer): Purrr solution: gapminder %>% every(is.integer)) Once you get accustomed to the syntax of purrr, you will need less time to actually write iterative code in R. However, one must never ever feel bad about writing loops in R. In fact, they are one of the fundamental blocks of programming and are profusely used throughout other languages. Some people even call loops slow. They’re wrong! (Well at least they’re rather out of date, as for loops haven’t been slow for many years). The chief benefit of using functions like map() and apply() is not speed, but clarity: they make your code easier to write and read. The important thing is that you solve the problem that you’re working on, not write the most concise and elegant code (although that’s definitely something you want to strive towards!)- Hadley Wickham Thanks for reading! You can view the code on my Github here or reach out to me here.
[ { "code": null, "e": 767, "s": 171, "text": "Inuits do not actually have a hundred names for snow. Turns out that’s part myth and part misunderstanding. Expanding a similar analogy to web speak, there are about a hundred ways to iterate code! To add to this, the syntax can be confusing and some of us also run the risk of just lazily resorting to copy-pasting the code 4 times. But it is important to recognise that this is a sub-optimal route and frankly impractical. As a general rule of thumb, if we need to run a block of code more than two times, it is a good idea to iterate! Here are two reasons why this will make your code richer-" }, { "code": null, "e": 949, "s": 767, "text": "It draws attention to the part of code that is different, thus making it easier to spot the intent of the operation.Due to its concise nature, you’re likely to encounter fewer bugs." }, { "code": null, "e": 1066, "s": 949, "text": "It draws attention to the part of code that is different, thus making it easier to spot the intent of the operation." }, { "code": null, "e": 1132, "s": 1066, "text": "Due to its concise nature, you’re likely to encounter fewer bugs." }, { "code": null, "e": 1245, "s": 1132, "text": "It might take some time to wrap your head around the idea of iterating, but trust me, it’s worth the investment." }, { "code": null, "e": 1305, "s": 1245, "text": "Now that you’re convinced to iterate — let’s jump right in!" }, { "code": null, "e": 1394, "s": 1305, "text": "Let’s pick the inbuilt R dataset- air quality. A snippet of the same is presented below-" }, { "code": null, "e": 1648, "s": 1394, "text": " Ozone Solar.R Wind Temp Month Day 41 190 7.4 67 5 1 36 118 8.0 72 5 2 12 149 12.6 74 5 3 18 313 11.5 62 5 4 23 299 8.6 65 5 7 19 99 13.8 59 5 8" }, { "code": null, "e": 1733, "s": 1648, "text": "Problem 1: You want to find the standard deviation for each variable in the dataset-" }, { "code": null, "e": 1785, "s": 1733, "text": "You could copy-paste the same code for each column-" }, { "code": null, "e": 1952, "s": 1785, "text": "sd(airquality$Ozone) 33.27597sd(airquality$Solar.R)91.1523sd(airquality$Wind)3.557713sd(airquality$Temp)9.529969sd(airquality$Month)1.473434sd(airquality$Day)8.707194" }, { "code": null, "e": 2113, "s": 1952, "text": "This is however impractical for large data sets and breaks the rule of thumb of not running the same operation more than twice. We have a solid case to iterate!" }, { "code": null, "e": 2139, "s": 2113, "text": "We can write a for()loop-" }, { "code": null, "e": 2339, "s": 2139, "text": "stddev = vector(\"double\", ncol(airquality))for(i in seq_along(airquality)) { stddev[[i]] = sd(airquality[[i]]) }stddev33.275969 91.152302 3.557713 9.529969 1.473434 8.707194" }, { "code": null, "e": 2432, "s": 2339, "text": "The loop does away with any repetition and is indeed more efficient than the first approach." }, { "code": null, "e": 2915, "s": 2432, "text": "It is also imperative to pause and note that while seq_along()and length() are mostly used interchangeably to build a sequence in the for loop, there is one key difference. In case of a zero-length vector, seq_along() does the right thing, but length() takes the value of 0 and 1. Although you probably won’t create a zero-length vector deliberately, it’s easy to create them accidentally. If you use 1:length() instead of seq_along(), you’re likely to get a confusing error message" }, { "code": null, "e": 3034, "s": 2915, "text": "Or you could just skip the loop and do the trick with just a line of code using sapply() from base R’s apply()family -" }, { "code": null, "e": 3174, "s": 3034, "text": "sapply(airquality, sd) Ozone Solar.R Wind Temp Month Day 33.275969 91.152302 3.557713 9.529969 1.473434 8.707194" }, { "code": null, "e": 3282, "s": 3174, "text": "This is a great application of R’s functional programming capabilities and indeed does the job very neatly." }, { "code": null, "e": 3367, "s": 3282, "text": "Let’s now take another step on the ladder of complexity and look at another problem." }, { "code": null, "e": 3461, "s": 3367, "text": "Problem 2: You want to find the standard deviation and median of each column in your dataset." }, { "code": null, "e": 3581, "s": 3461, "text": "Since we have established that the first approach of copy-pasting is impractical, we weigh in on our iteration options." }, { "code": null, "e": 3614, "s": 3581, "text": "We start by writing a for()loop-" }, { "code": null, "e": 3921, "s": 3614, "text": "stddev =vector(\"double\", ncol(airquality)) median =vector(\"double\", ncol(airquality))for(i in seq_along(airquality)) { stddev[[i]] = sd(airquality[[i]]) median[[i]] = median(airquality[[i]]) } stddev 33.275969 91.152302 3.557713 9.529969 1.473434 8.707194 median 31.0 207.0 9.7 79.0 7.0 16.0" }, { "code": null, "e": 4228, "s": 3921, "text": "Next, we take the functional programming route. Here, unlike the earlier example where we could directly use R’s inbuilt sd() function to calculate the standard deviation and pass it through sapply() , we need to create a custom function, as we need to calculate both the standard deviation and the median." }, { "code": null, "e": 4444, "s": 4228, "text": "f <- function(x){ list(sd(x),median(x)) }sapply(airquality, f)Ozone Solar.R Wind Temp Month Day 33.27597 91.1523 3.557713 9.529969 1.473434 8.70719431 207 9.7 79 7 16" }, { "code": null, "e": 5143, "s": 4444, "text": "This is a very solid idea! The ability to pass a user built function to another function is thrilling and clearly showcases R’s functional programming capabilities to solve a wide variety of tasks. In fact, seasoned R users rarely ever use loops and resort to functional programming techniques to solve all iterative tasks. As used above, apply family of functions in base R (apply(), lapply(), tapply(), etc) are a great way to go about this, but even in the functional programming universe there is one package which has emerged as a favorite — Purrr. The purrr family of functions has more consistent syntax and has in built functionalities to carry out a wide variety of common iterative tasks." }, { "code": null, "e": 5260, "s": 5143, "text": "The Map() functions form the cornerstone of the purrr’s iterative capabilities. Here are some of the forms it takes-" }, { "code": null, "e": 5280, "s": 5260, "text": "map() makes a list." }, { "code": null, "e": 5314, "s": 5280, "text": "map_lgl() makes a logical vector." }, { "code": null, "e": 5349, "s": 5314, "text": "map_int() makes an integer vector." }, { "code": null, "e": 5382, "s": 5349, "text": "map_dbl() makes a double vector." }, { "code": null, "e": 5418, "s": 5382, "text": "map_chr() makes a character vector." }, { "code": null, "e": 5532, "s": 5418, "text": "Let’s use this idea to solve our earlier problem of calculating the median and standard deviation of each column-" }, { "code": null, "e": 5589, "s": 5532, "text": "map_df(airquality, ~list(med = median(.x), sd = sd(.x)))" }, { "code": null, "e": 5927, "s": 5589, "text": "Next, in order to another leap on the complexity ladder let’s pick the gapminder dataset from the gapminder library. A snippet of the same is presented below.(P.S- If you haven’t heard about the gapminder foundation, do check its website out here . The foundation does some groundbreaking work on putting basic global facts into context)" }, { "code": null, "e": 6272, "s": 5927, "text": " country continent year lifeExp pop gdpPercap Afghanistan Asia 1952 28.8 8425333 779. Afghanistan Asia 1957 30.3 9240934 821. Afghanistan Asia 1962 32.0 10267083 853. Afghanistan Asia 1967 34.0 11537966 836. Afghanistan Asia 1972 36.1 13079460 740. Afghanistan Asia 1977 38.4 14880372 786." }, { "code": null, "e": 6379, "s": 6272, "text": "Problem 3: I want to know which country has the highest GDP Per Capita in each continent and in each year." }, { "code": null, "e": 6410, "s": 6379, "text": "Using the for() loop approach-" }, { "code": null, "e": 6639, "s": 6410, "text": "list = c(“continent”, “year”)DF= data.frame()for( i in list){ df = gapminder %>% group_by_at(i) %>% top_n(1, gdpPercap) %>% mutate(Remark = paste0(“Country Max GDP Per capita in the “,i)) %>% data.frame() DF = rbind(df,DF)}DF" }, { "code": null, "e": 6666, "s": 6639, "text": "Using the Apply()approach-" }, { "code": null, "e": 6866, "s": 6666, "text": "do.call(rbind, lapply(list, function(x){ gapminder %>% group_by_at(x) %>% top_n(1, gdpPercap)%>% mutate(Remark = paste0(\"Country with the max GDP Per capita in the \",x)) %>% data.frame}))" }, { "code": null, "e": 6899, "s": 6866, "text": "Using the Purrr::Map() approach-" }, { "code": null, "e": 7112, "s": 6899, "text": "gapminder$year = as.character(gapminder$year)map_dfr(list, ~gapminder %>% group_by(!!sym(.x)) %>% top_n(1, gdpPercap)%>% mutate(Remark = paste0(“Country with the max GDP Per capita in the “,.x)) %>% data.frame()" }, { "code": null, "e": 7418, "s": 7112, "text": "All of the above three approaches lead to the same output (For the sake of brevity, I am not including the output here. You can have a look at it on my Github here). Again, while you can take your pick on which iterative route you want to take, the functional programming way is a clear winner on cogency." }, { "code": null, "e": 7540, "s": 7418, "text": "Purrr also has some inbuilt functions to deal with everyday iterative tasks! Below I have listed down a few popular ones." }, { "code": null, "e": 7622, "s": 7540, "text": "Task: Run a piecewise regression for each segment of the data. (Here, continent):" }, { "code": null, "e": 7638, "s": 7622, "text": "Purrr solution:" }, { "code": null, "e": 7717, "s": 7638, "text": "gapminder %>% split(.$Continent) %>% map(~lm(gdpPercap ~ lifeExp, data = .))" }, { "code": null, "e": 7805, "s": 7717, "text": "Task: Keep variables basis an arbitrary condition. (Here, if the variable is a factor):" }, { "code": null, "e": 7821, "s": 7805, "text": "Purrr solution:" }, { "code": null, "e": 7865, "s": 7821, "text": "gapminder %>% keep(is.factor) %>% str()" }, { "code": null, "e": 7962, "s": 7865, "text": "Task: Check if any variable meets the arbitrary condition(Here, if any variable is a character):" }, { "code": null, "e": 7978, "s": 7962, "text": "Purrr solution:" }, { "code": null, "e": 8012, "s": 7978, "text": "gapminder%>% some(is_character)" }, { "code": null, "e": 8112, "s": 8012, "text": "Task: Check if every variable meets the arbitrary condition(Here, if every variable is an integer):" }, { "code": null, "e": 8128, "s": 8112, "text": "Purrr solution:" }, { "code": null, "e": 8163, "s": 8128, "text": "gapminder %>% every(is.integer))" }, { "code": null, "e": 8725, "s": 8163, "text": "Once you get accustomed to the syntax of purrr, you will need less time to actually write iterative code in R. However, one must never ever feel bad about writing loops in R. In fact, they are one of the fundamental blocks of programming and are profusely used throughout other languages. Some people even call loops slow. They’re wrong! (Well at least they’re rather out of date, as for loops haven’t been slow for many years). The chief benefit of using functions like map() and apply() is not speed, but clarity: they make your code easier to write and read." }, { "code": null, "e": 8926, "s": 8725, "text": "The important thing is that you solve the problem that you’re working on, not write the most concise and elegant code (although that’s definitely something you want to strive towards!)- Hadley Wickham" } ]
Frequencies of even and odd numbers in a matrix - GeeksforGeeks
29 Apr, 2021 Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in matrix Examples: Input : m = 3, n = 3 { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } Output : Frequency of odd number = 5 Frequency of even number = 4 Input : m = 3, n = 3 { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } Output : Frequency of odd number = 4 Frequency of even number = 5 CPP Java Python3 C# PHP Javascript // C++ Program to Find the frequency// of even and odd numbers in a matrix#include<bits/stdc++.h>using namespace std; #define MAX 100 // function for calculating frequencyvoid freq(int ar[][MAX], int m, int n){ int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers printf(" Frequency of odd number = %d \n", odd); printf(" Frequency of even number = %d \n", even);} // Driver codeint main(){ int m = 3, n = 3; int array[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; freq(array, m, n); return 0;} // Java Program to Find the frequency// of even and odd numbers in a matrix class GFG {static final int MAX = 100; // function for calculating frequencystatic void freq(int ar[][], int m, int n) { int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers System.out.print(" Frequency of odd number =" + odd + " \n"); System.out.print(" Frequency of even number = " + even + " \n");} // Driver codepublic static void main(String[] args) { int m = 3, n = 3; int array[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; freq(array, m, n);}}// This code is contributed by Anant Agarwal. # Python Program to Find the frequency# of even and odd numbers in a matrix MAX=100 # Function for calculating frequencydef freq(ar, m, n): even = 0 odd = 0 for i in range(m): for j in range(n): # modulo by 2 to check # even and odd if ((ar[i][j] % 2) == 0): even += 1 else: odd += 1 # print Frequency of numbers print(" Frequency of odd number =", odd) print(" Frequency of even number =", even) # Driver codem = 3n = 3 array = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] freq(array, m, n) # This code is contributed# by Anant Agarwal. // C# Program to Find the frequency// of even and odd numbers in a matrixusing System; class GFG{ //static int MAX = 100; // function for calculating frequency static void freq(int [,]ar, int m, int n) { int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i, j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers Console.WriteLine(" Frequency of odd number =" + odd ); Console.WriteLine(" Frequency of even number = " + even ); } // Driver code public static void Main() { int m = 3, n = 3; int [,]array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; freq(array, m, n); }}// This code is contributed by vt_m. <?php// PHP Program to Find the frequency// of even and odd numbers in a matrix$MAX = 100; // function for calculating frequencyfunction freq($ar, $m, $n){ $even = 0; $odd = 0; for($i = 0; $i < $m; ++$i) { for ( $j = 0; $j < $n; ++$j) { // modulo by 2 to check // even and odd if (($ar[$i][$j] % 2) == 0) ++$even; else ++$odd; } } // print Frequency of numbers echo " Frequency of odd number = " , $odd,"\n"; echo " Frequency of even number = " , $even;} // Driver code $m = 3; $n = 3; $array = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); freq($array, $m, $n); // This code is contributed by anuj_67.?> <script>// Java Script Program to Find the frequency// of even and odd numbers in a matrix let MAX = 100; // function for calculating frequencyfunction freq(ar,m,n) { let even = 0, odd = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers document.write(" Frequency of odd number =" + odd + " <br>"); document.write(" Frequency of even number = " + even + "<br>");} // Driver code let m = 3, n = 3; let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; freq(array, m, n); // This code is contributed by sravan kumar G</script> Output: Frequency of odd number = 5 Frequency of even number = 4 vt_m sravankumar8128 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation) Unique paths in a Grid with Obstacles Mathematics | L U Decomposition of a System of Linear Equations C program to implement Adjacency Matrix of a given Graph Java Program to Multiply two Matrices of any size Python Dictionary Inheritance in C++ Arrays in C/C++ Overriding in Java Copy Constructor in C++
[ { "code": null, "e": 24530, "s": 24502, "text": "\n29 Apr, 2021" }, { "code": null, "e": 24643, "s": 24530, "text": "Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in matrix Examples: " }, { "code": null, "e": 24983, "s": 24643, "text": "Input : m = 3, n = 3\n { 1, 2, 3 }, \n { 4, 5, 6 }, \n { 7, 8, 9 }\nOutput : Frequency of odd number = 5 \n Frequency of even number = 4\n\n\nInput : m = 3, n = 3\n { 10, 11, 12 },\n { 13, 14, 15 },\n { 16, 17, 18 }\nOutput : Frequency of odd number = 4 \n Frequency of even number = 5" }, { "code": null, "e": 24991, "s": 24987, "text": "CPP" }, { "code": null, "e": 24996, "s": 24991, "text": "Java" }, { "code": null, "e": 25004, "s": 24996, "text": "Python3" }, { "code": null, "e": 25007, "s": 25004, "text": "C#" }, { "code": null, "e": 25011, "s": 25007, "text": "PHP" }, { "code": null, "e": 25022, "s": 25011, "text": "Javascript" }, { "code": "// C++ Program to Find the frequency// of even and odd numbers in a matrix#include<bits/stdc++.h>using namespace std; #define MAX 100 // function for calculating frequencyvoid freq(int ar[][MAX], int m, int n){ int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers printf(\" Frequency of odd number = %d \\n\", odd); printf(\" Frequency of even number = %d \\n\", even);} // Driver codeint main(){ int m = 3, n = 3; int array[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; freq(array, m, n); return 0;} ", "e": 25872, "s": 25022, "text": null }, { "code": "// Java Program to Find the frequency// of even and odd numbers in a matrix class GFG {static final int MAX = 100; // function for calculating frequencystatic void freq(int ar[][], int m, int n) { int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers System.out.print(\" Frequency of odd number =\" + odd + \" \\n\"); System.out.print(\" Frequency of even number = \" + even + \" \\n\");} // Driver codepublic static void main(String[] args) { int m = 3, n = 3; int array[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; freq(array, m, n);}}// This code is contributed by Anant Agarwal.", "e": 26758, "s": 25872, "text": null }, { "code": "# Python Program to Find the frequency# of even and odd numbers in a matrix MAX=100 # Function for calculating frequencydef freq(ar, m, n): even = 0 odd = 0 for i in range(m): for j in range(n): # modulo by 2 to check # even and odd if ((ar[i][j] % 2) == 0): even += 1 else: odd += 1 # print Frequency of numbers print(\" Frequency of odd number =\", odd) print(\" Frequency of even number =\", even) # Driver codem = 3n = 3 array = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] freq(array, m, n) # This code is contributed# by Anant Agarwal.", "e": 27439, "s": 26758, "text": null }, { "code": "// C# Program to Find the frequency// of even and odd numbers in a matrixusing System; class GFG{ //static int MAX = 100; // function for calculating frequency static void freq(int [,]ar, int m, int n) { int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i, j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers Console.WriteLine(\" Frequency of odd number =\" + odd ); Console.WriteLine(\" Frequency of even number = \" + even ); } // Driver code public static void Main() { int m = 3, n = 3; int [,]array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; freq(array, m, n); }}// This code is contributed by vt_m.", "e": 28431, "s": 27439, "text": null }, { "code": "<?php// PHP Program to Find the frequency// of even and odd numbers in a matrix$MAX = 100; // function for calculating frequencyfunction freq($ar, $m, $n){ $even = 0; $odd = 0; for($i = 0; $i < $m; ++$i) { for ( $j = 0; $j < $n; ++$j) { // modulo by 2 to check // even and odd if (($ar[$i][$j] % 2) == 0) ++$even; else ++$odd; } } // print Frequency of numbers echo \" Frequency of odd number = \" , $odd,\"\\n\"; echo \" Frequency of even number = \" , $even;} // Driver code $m = 3; $n = 3; $array = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); freq($array, $m, $n); // This code is contributed by anuj_67.?>", "e": 29276, "s": 28431, "text": null }, { "code": "<script>// Java Script Program to Find the frequency// of even and odd numbers in a matrix let MAX = 100; // function for calculating frequencyfunction freq(ar,m,n) { let even = 0, odd = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers document.write(\" Frequency of odd number =\" + odd + \" <br>\"); document.write(\" Frequency of even number = \" + even + \"<br>\");} // Driver code let m = 3, n = 3; let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; freq(array, m, n); // This code is contributed by sravan kumar G</script>", "e": 30080, "s": 29276, "text": null }, { "code": null, "e": 30090, "s": 30080, "text": "Output: " }, { "code": null, "e": 30151, "s": 30090, "text": " Frequency of odd number = 5 \n Frequency of even number = 4" }, { "code": null, "e": 30158, "s": 30153, "text": "vt_m" }, { "code": null, "e": 30174, "s": 30158, "text": "sravankumar8128" }, { "code": null, "e": 30181, "s": 30174, "text": "Matrix" }, { "code": null, "e": 30200, "s": 30181, "text": "School Programming" }, { "code": null, "e": 30207, "s": 30200, "text": "Matrix" }, { "code": null, "e": 30305, "s": 30207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30314, "s": 30305, "text": "Comments" }, { "code": null, "e": 30327, "s": 30314, "text": "Old Comments" }, { "code": null, "e": 30404, "s": 30327, "text": "Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)" }, { "code": null, "e": 30442, "s": 30404, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 30506, "s": 30442, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 30563, "s": 30506, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 30613, "s": 30563, "text": "Java Program to Multiply two Matrices of any size" }, { "code": null, "e": 30631, "s": 30613, "text": "Python Dictionary" }, { "code": null, "e": 30650, "s": 30631, "text": "Inheritance in C++" }, { "code": null, "e": 30666, "s": 30650, "text": "Arrays in C/C++" }, { "code": null, "e": 30685, "s": 30666, "text": "Overriding in Java" } ]
What is the basic minimal structure of HTML document?
HTML document is a web page, which helps you in showing content on the website. It consists of tags, which has an opening as well as closing tags. However, some tags do not come in pairs i.e. they do not have a closing tag. The basic minimal structure also has some tags, which you need to add. doctypeThis is a doctype declaration, which begins the HTML program and gets added as <!DOCTYPE html>. It is added to tell and instruct the browser about the document.<htmlThe first thing after the doctype declaration is the <html> tag. All the other HTML tags comes inside the <html>...</html> tag tells. Every tag inside this tag follows HTML rules. <head>The <head> tag helps you in adding the title for the HTML document using the <title>...<title> tag.<body>The <body> tag allows you need to content to the HTML Document. You can use the <p>...</p> tag to add content to the document, which is visible on the web page. Live Demo <!DOCTYPE html> <html> <head> <title>HTML Document</title> </head> <body> <p>This is demo text.</p> </body> </html>
[ { "code": null, "e": 1357, "s": 1062, "text": "HTML document is a web page, which helps you in showing content on the website. It consists of tags, which has an opening as well as closing tags. However, some tags do not come in pairs i.e. they do not have a closing tag. The basic minimal structure also has some tags, which you need to add." }, { "code": null, "e": 1709, "s": 1357, "text": "doctypeThis is a doctype declaration, which begins the HTML program and gets added as <!DOCTYPE html>. It is added to tell and instruct the browser about the document.<htmlThe first thing after the doctype declaration is the <html> tag. All the other HTML tags comes inside the <html>...</html> tag tells. Every tag inside this tag follows HTML rules." }, { "code": null, "e": 1981, "s": 1709, "text": "<head>The <head> tag helps you in adding the title for the HTML document using the <title>...<title> tag.<body>The <body> tag allows you need to content to the HTML Document. You can use the <p>...</p> tag to add content to the document, which is visible on the web page." }, { "code": null, "e": 1991, "s": 1981, "text": "Live Demo" }, { "code": null, "e": 2131, "s": 1991, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Document</title>\n </head>\n <body>\n <p>This is demo text.</p>\n </body>\n</html>" } ]
An Introduction to Classification Using Mislabeled Data | by Shihab Shahriar Khan | Towards Data Science
The performance of any classifier, or for that matter any machine learning task, depends crucially on the quality of the available data. Data quality in turn depends on several factors- for example accuracy of measurements (i.e. noise), presence of important information, absence of redundant information, how much collected samples actually represent the population, etc. In this article we will focus on noise, in particular label noise- the scenario when a sample can have exactly one label (or class), and a subset of samples in the dataset are mislabeled. We will look at what happens to classification performance when there’s label noise, how exactly it hampers the learning process of classifiers, and what we can do about it. We’ll restrict ourselves to “matrix-form” datasets in this post. While many of the points raised here will no doubt apply to deep learning, there are enough practical differences for it to require a separate post. Python code for all the experiments and figures can be found in this link. There are two important reasons: 1. Label noise can significantly harm performance: Noise in a dataset can mainly be of two types: feature noise and label noise; and several research papers have pointed out that label noise usually is a lot more harmful than feature noise. Figure 1 illustrates the impact of (artificially introduced) 30% label noise on the classification boundary of LinearSVC on a simple, linearly separable, binary classification dataset. We’ll talk about the impact more deeply later on, so let’s move on to the second point. 2. Label noise is very widespread: Label noise can creep into your dataset in many ways. One possible source is automatic labeling. This approach often uses meta-information (i.e. info not directly present in feature vectors) to generate labels- for example using hashtags to label images or using commit logs to detect defective modules in a software repository etc. This saves both time and money compared to labeling by domain experts, especially while dealing with large datasets, at the expense of quality. In software engineering domain, it was discovered that one of the leading auto-labeling algorithms to detect bug introducing commits (SZZ) has quite high noise rate [2], putting a big question mark on years of research that relied on SZZ to produce defect classification datasets. In fact, this trade-off between quality and cost springs up quite often. For an example particularly relevant to the moment- say we want to create a COVID-19 prediction dataset using demographic features. For collecting the labels, i.e. whether someone actually have COVID-19, so far we basically have two options- we can either use slow, expensive and accurate RT-PCR test, or we can use fast, cheap but error-prone rapid testing kits. But human labelers, or even experts are not infallible. In the medical domain, radiologists with 10 years of experience make mistakes 16.1% of the times while classifying MRIs [1]. Amazon Mechanical Turk has emerged as a quite popular data-labeling medium, but its widely known to contain illegal bots (and sometimes lazy humans) randomly labeling stuff. In fact, it’s hard to imagine a sufficiently large dataset that doesn’t contain at least some level of label noise. It perhaps wouldn’t be an overstatement to say that at least a basic awareness of label noise is pretty important for any data scientist working with real-world datasets. Noise in dataset label will hurt the performance of any classifier, which is expected- the interesting question is by how much. Turns out the answer depends quite heavily on the classifier being used to mine the dataset. To show this, we’re going to carry out a little experiment. We’ll use seven datasets to mitigate any dataset-specific bias- Iris, Breast Cancer, Vowel, Segment, Digits, Wine and Spambase. 5-fold cross-validation is repeated 3 times to compute the accuracy of a single classifier-dataset pair. At each iteration of cross-validation, we corrupt (i.e randomly flip) 20% labels of training data. Note that only the training dataset is corrupted with noise, original i.e. clean labels are used for evaluation. As Figure 2 shows, performance of all classifiers get worse, which is expected. But there is a pretty huge variation among classifiers. Decision Tree (DT) appears to be extremely vulnerable to noise. All 4 ensembles examined here: Random Forest (RF), Extra Tree (Extra), XGBoost (XGB) and LightGBM (LGB), have broadly similar performance on original data. But XGBoost’s performance takes a comparatively bigger hit due to noise, RF on the other hand seems comparatively robust. Well, an obvious answer is that low-quality data results in low-quality models. But defining quality isn’t straight as forward as it seems. We might be tempted to say dataset with higher noise level is of lower quality, and intuitively that makes sense. But remember figure 1? here is the same one, but now with 4000 samples instead of 400. In both cases the datasets contain 30% label noise, so should be of similar quality. Yet in this case, the decision boundary learned with noisy data is indistinguishable from the one learned with clean data. This isn’t to say that the intuition is wrong (it isn’t), but to emphasize that when it comes to explaining the performance loss, there’s more to the story (e.g. dataset size) than simple noise level. Besides, the data-centric perspective alone doesn’t explain the huge disparity among different classifiers’ response to noise. So next we’re going to analyze it from the perspective of classifiers. In the figure below, we take the most brittle among all classifiers- Decision Tree, train it with both clean and noisy labels of Iris dataset, and plot the structure of resulting trees below. We’re only applying 20% noise here. But even this small noise is enough to turn a relatively small decision tree (left) into a gigantic mess (right). This is admittedly a contrived and extreme example, but it does reveal an important insight that more or less applies to all classifiers: label noise increases the model complexity, making the classifiers overfit to noise. Another good algorithm to demonstrate the impact of noise is Adaboost, the predecessor of current state-of-the-arts like XGBoost and LightGBM. It was among state-of-the-arts in early 2000s, but it is also very vulnerable to label noise. Adaboost begins by assigning each instance equal weight. At each iteration, it increases the weight of the instances it misclassified, and reduces the weight of others. In this way, it gradually concentrates more on the harder instances. But as you might have imagined, mislabeled instances are usually harder to classify than clean ones. So Adaboost ends up assigning higher weights to mislabeled samples i.e. it tries hard to correctly classify instances it should ideally ignore. The animation in figure 5 captures the distribution of weights assigned to noisy and clean samples by Adaboost on Breast Cancer dataset with 20% noise. After only 20 iterations, noisy instances collectively have twice more weight than clean ones, despite being outnumbered 4 to 1. To make this discussion complete, let’s take a look at some classifiers of the opposite spectrum: ones that are more robust to noise than others. If you have looked at figure 2 attentively, you’ve probably discovered a quite remarkable fact: that two of the most robust classifiers there (Random Forest and Extra Tree) are nothing but a simple collection of the most brittle algorithm: Decision Tree. To explain this, let’s start with something that these forests doesn’t do- they don’t put extra emphasis on noisy instances like Adaboost (or SVM), all instances are treated equally during bootstrap aggregating (or Bagging) [3], a vital component of random forest. The explanation of how a bunch of poor decision trees (DT) can band together to form such powerful random forest lies in a concept called bias–variance decomposition of classification error. Imagine lots of DTs each with exactly 60% accuracy on a binary classification dataset. Assuming there is no correlation between their predictions, given a new instance, we can expect (approximately) 60% of DTs to make the right prediction on it. So if we aggregate their result by majority voting, for any new instance majority (i.e. 60%) will make the right prediction, giving us a perfect 100% accuracy! Of course, that assumption of zero correlation is impossible to achieve in practice, so we can’t go quite as far as 100, but hopefully, you get the point. Before we start talking about mitigating the impact of noise, please remember the famous No Free Lunch theorem. None of the methods discussed below are panacea- they sometimes work and sometimes don’t. And sometimes when they do work, the improvement might be insignificant compared to added computational cost. So always remember to compare your ML pipeline against a simple baseline without any of these noise handling mechanisms. That being said, broadly speaking, we can attack the label noise problem from two angles: by using noise robust algorithms, or by cleaning our data. In the first approach, we can simply pick algorithms that are inherently more robust, for example, bagging-based ensembles over boosting. There have also been many algorithms and loss functions designed specifically to be noise-robust, for example unhinged SVM [4][5]. Or, using the fact that label noise leads to overfitting, we can usually make brittle algorithms more robust just by introducing stronger regularization, as figure 6 shows. For cleaning data, we can use the previously stated observation that mislabeled instances are harder to correctly classify. In fact, a good number of ML papers rely on this observation to design new data cleaning procedures [6]. The basic steps are: train a bunch of classifiers using a subset of training data, predict the labels of the rest of the data using them, and then the percentage of classifiers that failed to correctly predict a sample’s given label is the probability that the sample is mislabeled. Although a link to full code has already been shared, a sample implementation using an ensemble of decision trees is so simple that I can’t resist showing it here: def detect_noisy_samples(X,y,thres=.5): #Returns noisy indexes rf = RandomForestClassifier(oob_score=True).fit(X,y) noise_prob = 1 - rf.oob_decision_function_[range(len(y)),y] return noise_prob>thres On Spambase dataset with 25% label noise, this method detects 85% of mislabeled instances, while only 13% of clean instances get detected as noisy. For Breast Cancer, these numbers are 90% and 10% respectively. But this method of training multiple classifiers only to preprocess dataset might be impractical for big datasets. Another closely related but far more efficient heuristic is: 1) find the K nearest neighbors of a sample, 2) compute the percentage of those neighbors with similar label, 3) Use that as a proxy for label reliability. As expected, it’s performance can be somewhat less impressive- it detects 2/3rd of noisy instances in Spambase while 10% of clean instances gets labeled noisy. But once again, a basic implementation is incredibly simple. def detect_noisy_samples(X,y,thres=.5): #Returns noisy indexes knn = KNeighborsClassifier().fit(X,y) noise_prob = 1 - knn.predict_proba(X)[range(len(X)),y] return np.argwhere(noise_prob>thres).reshape(-1) It is worth emphasizing that cleaning data doesn’t have to mean simply throwing away suspected mislabeled samples. Both of the heuristics described above returns continuous probability of (a sample) being mislabeled. We can use the inverse of that probability as a sort of reliability or confidence score, and use cost-sensitive learning to utilize this information. In this way, we get to retain all data points, which is especially important when the noise level is high or dataset size is small. Plus, this is more general than filtering- filtering is a special instance of cost-sensitive approach where the cost can be only 0 and 1. Thanks for staying this far! I hope this article has been useful. But please remember that this is simply an introduction, and therefore leaves out a lot of interesting and important questions. For example, we haven’t really talked about “Noise Model” here. We only focused on the overall percentage of mislabeled samples, assuming the wrong label for a mislabeled instance can come from any of the other labels with equal probability. This is not unrealistic, this so-called uniform noise model can arise e.g. when an amazon bot randomly assigns labels. But we know from common sense that a serious human annotator is much more likely to confuse between say 9 and 7 than 9 and 8, or between positive and neutral sentiment than positive and negative sentiment- and the uniform noise model doesn’t quite capture this uneven interaction between labels. Another interesting question is regarding how we should act when we haven’t yet collected labels: Do we collect a big amount of low-quality data? or do we collect a small quantity of high-quality data? Anyway, I hope this introduction serves as a good starting point. I’m planning to address these left-out issues and several others in a series of articles in near future, so stay tuned. [1] https://escholarship.org/uc/item/9zt9g3wt [2] https://ieeexplore.ieee.org/document/8765743 [3] G., Yves. “Bagging equalizes influence.” Machine Learning, (2004)
[ { "code": null, "e": 907, "s": 172, "text": "The performance of any classifier, or for that matter any machine learning task, depends crucially on the quality of the available data. Data quality in turn depends on several factors- for example accuracy of measurements (i.e. noise), presence of important information, absence of redundant information, how much collected samples actually represent the population, etc. In this article we will focus on noise, in particular label noise- the scenario when a sample can have exactly one label (or class), and a subset of samples in the dataset are mislabeled. We will look at what happens to classification performance when there’s label noise, how exactly it hampers the learning process of classifiers, and what we can do about it." }, { "code": null, "e": 1196, "s": 907, "text": "We’ll restrict ourselves to “matrix-form” datasets in this post. While many of the points raised here will no doubt apply to deep learning, there are enough practical differences for it to require a separate post. Python code for all the experiments and figures can be found in this link." }, { "code": null, "e": 1229, "s": 1196, "text": "There are two important reasons:" }, { "code": null, "e": 1743, "s": 1229, "text": "1. Label noise can significantly harm performance: Noise in a dataset can mainly be of two types: feature noise and label noise; and several research papers have pointed out that label noise usually is a lot more harmful than feature noise. Figure 1 illustrates the impact of (artificially introduced) 30% label noise on the classification boundary of LinearSVC on a simple, linearly separable, binary classification dataset. We’ll talk about the impact more deeply later on, so let’s move on to the second point." }, { "code": null, "e": 2536, "s": 1743, "text": "2. Label noise is very widespread: Label noise can creep into your dataset in many ways. One possible source is automatic labeling. This approach often uses meta-information (i.e. info not directly present in feature vectors) to generate labels- for example using hashtags to label images or using commit logs to detect defective modules in a software repository etc. This saves both time and money compared to labeling by domain experts, especially while dealing with large datasets, at the expense of quality. In software engineering domain, it was discovered that one of the leading auto-labeling algorithms to detect bug introducing commits (SZZ) has quite high noise rate [2], putting a big question mark on years of research that relied on SZZ to produce defect classification datasets." }, { "code": null, "e": 2973, "s": 2536, "text": "In fact, this trade-off between quality and cost springs up quite often. For an example particularly relevant to the moment- say we want to create a COVID-19 prediction dataset using demographic features. For collecting the labels, i.e. whether someone actually have COVID-19, so far we basically have two options- we can either use slow, expensive and accurate RT-PCR test, or we can use fast, cheap but error-prone rapid testing kits." }, { "code": null, "e": 3615, "s": 2973, "text": "But human labelers, or even experts are not infallible. In the medical domain, radiologists with 10 years of experience make mistakes 16.1% of the times while classifying MRIs [1]. Amazon Mechanical Turk has emerged as a quite popular data-labeling medium, but its widely known to contain illegal bots (and sometimes lazy humans) randomly labeling stuff. In fact, it’s hard to imagine a sufficiently large dataset that doesn’t contain at least some level of label noise. It perhaps wouldn’t be an overstatement to say that at least a basic awareness of label noise is pretty important for any data scientist working with real-world datasets." }, { "code": null, "e": 4341, "s": 3615, "text": "Noise in dataset label will hurt the performance of any classifier, which is expected- the interesting question is by how much. Turns out the answer depends quite heavily on the classifier being used to mine the dataset. To show this, we’re going to carry out a little experiment. We’ll use seven datasets to mitigate any dataset-specific bias- Iris, Breast Cancer, Vowel, Segment, Digits, Wine and Spambase. 5-fold cross-validation is repeated 3 times to compute the accuracy of a single classifier-dataset pair. At each iteration of cross-validation, we corrupt (i.e randomly flip) 20% labels of training data. Note that only the training dataset is corrupted with noise, original i.e. clean labels are used for evaluation." }, { "code": null, "e": 4819, "s": 4341, "text": "As Figure 2 shows, performance of all classifiers get worse, which is expected. But there is a pretty huge variation among classifiers. Decision Tree (DT) appears to be extremely vulnerable to noise. All 4 ensembles examined here: Random Forest (RF), Extra Tree (Extra), XGBoost (XGB) and LightGBM (LGB), have broadly similar performance on original data. But XGBoost’s performance takes a comparatively bigger hit due to noise, RF on the other hand seems comparatively robust." }, { "code": null, "e": 5569, "s": 4819, "text": "Well, an obvious answer is that low-quality data results in low-quality models. But defining quality isn’t straight as forward as it seems. We might be tempted to say dataset with higher noise level is of lower quality, and intuitively that makes sense. But remember figure 1? here is the same one, but now with 4000 samples instead of 400. In both cases the datasets contain 30% label noise, so should be of similar quality. Yet in this case, the decision boundary learned with noisy data is indistinguishable from the one learned with clean data. This isn’t to say that the intuition is wrong (it isn’t), but to emphasize that when it comes to explaining the performance loss, there’s more to the story (e.g. dataset size) than simple noise level." }, { "code": null, "e": 5959, "s": 5569, "text": "Besides, the data-centric perspective alone doesn’t explain the huge disparity among different classifiers’ response to noise. So next we’re going to analyze it from the perspective of classifiers. In the figure below, we take the most brittle among all classifiers- Decision Tree, train it with both clean and noisy labels of Iris dataset, and plot the structure of resulting trees below." }, { "code": null, "e": 6332, "s": 5959, "text": "We’re only applying 20% noise here. But even this small noise is enough to turn a relatively small decision tree (left) into a gigantic mess (right). This is admittedly a contrived and extreme example, but it does reveal an important insight that more or less applies to all classifiers: label noise increases the model complexity, making the classifiers overfit to noise." }, { "code": null, "e": 7333, "s": 6332, "text": "Another good algorithm to demonstrate the impact of noise is Adaboost, the predecessor of current state-of-the-arts like XGBoost and LightGBM. It was among state-of-the-arts in early 2000s, but it is also very vulnerable to label noise. Adaboost begins by assigning each instance equal weight. At each iteration, it increases the weight of the instances it misclassified, and reduces the weight of others. In this way, it gradually concentrates more on the harder instances. But as you might have imagined, mislabeled instances are usually harder to classify than clean ones. So Adaboost ends up assigning higher weights to mislabeled samples i.e. it tries hard to correctly classify instances it should ideally ignore. The animation in figure 5 captures the distribution of weights assigned to noisy and clean samples by Adaboost on Breast Cancer dataset with 20% noise. After only 20 iterations, noisy instances collectively have twice more weight than clean ones, despite being outnumbered 4 to 1." }, { "code": null, "e": 7999, "s": 7333, "text": "To make this discussion complete, let’s take a look at some classifiers of the opposite spectrum: ones that are more robust to noise than others. If you have looked at figure 2 attentively, you’ve probably discovered a quite remarkable fact: that two of the most robust classifiers there (Random Forest and Extra Tree) are nothing but a simple collection of the most brittle algorithm: Decision Tree. To explain this, let’s start with something that these forests doesn’t do- they don’t put extra emphasis on noisy instances like Adaboost (or SVM), all instances are treated equally during bootstrap aggregating (or Bagging) [3], a vital component of random forest." }, { "code": null, "e": 8751, "s": 7999, "text": "The explanation of how a bunch of poor decision trees (DT) can band together to form such powerful random forest lies in a concept called bias–variance decomposition of classification error. Imagine lots of DTs each with exactly 60% accuracy on a binary classification dataset. Assuming there is no correlation between their predictions, given a new instance, we can expect (approximately) 60% of DTs to make the right prediction on it. So if we aggregate their result by majority voting, for any new instance majority (i.e. 60%) will make the right prediction, giving us a perfect 100% accuracy! Of course, that assumption of zero correlation is impossible to achieve in practice, so we can’t go quite as far as 100, but hopefully, you get the point." }, { "code": null, "e": 9184, "s": 8751, "text": "Before we start talking about mitigating the impact of noise, please remember the famous No Free Lunch theorem. None of the methods discussed below are panacea- they sometimes work and sometimes don’t. And sometimes when they do work, the improvement might be insignificant compared to added computational cost. So always remember to compare your ML pipeline against a simple baseline without any of these noise handling mechanisms." }, { "code": null, "e": 9775, "s": 9184, "text": "That being said, broadly speaking, we can attack the label noise problem from two angles: by using noise robust algorithms, or by cleaning our data. In the first approach, we can simply pick algorithms that are inherently more robust, for example, bagging-based ensembles over boosting. There have also been many algorithms and loss functions designed specifically to be noise-robust, for example unhinged SVM [4][5]. Or, using the fact that label noise leads to overfitting, we can usually make brittle algorithms more robust just by introducing stronger regularization, as figure 6 shows." }, { "code": null, "e": 10451, "s": 9775, "text": "For cleaning data, we can use the previously stated observation that mislabeled instances are harder to correctly classify. In fact, a good number of ML papers rely on this observation to design new data cleaning procedures [6]. The basic steps are: train a bunch of classifiers using a subset of training data, predict the labels of the rest of the data using them, and then the percentage of classifiers that failed to correctly predict a sample’s given label is the probability that the sample is mislabeled. Although a link to full code has already been shared, a sample implementation using an ensemble of decision trees is so simple that I can’t resist showing it here:" }, { "code": null, "e": 10660, "s": 10451, "text": "def detect_noisy_samples(X,y,thres=.5): #Returns noisy indexes rf = RandomForestClassifier(oob_score=True).fit(X,y) noise_prob = 1 - rf.oob_decision_function_[range(len(y)),y] return noise_prob>thres" }, { "code": null, "e": 10871, "s": 10660, "text": "On Spambase dataset with 25% label noise, this method detects 85% of mislabeled instances, while only 13% of clean instances get detected as noisy. For Breast Cancer, these numbers are 90% and 10% respectively." }, { "code": null, "e": 11424, "s": 10871, "text": "But this method of training multiple classifiers only to preprocess dataset might be impractical for big datasets. Another closely related but far more efficient heuristic is: 1) find the K nearest neighbors of a sample, 2) compute the percentage of those neighbors with similar label, 3) Use that as a proxy for label reliability. As expected, it’s performance can be somewhat less impressive- it detects 2/3rd of noisy instances in Spambase while 10% of clean instances gets labeled noisy. But once again, a basic implementation is incredibly simple." }, { "code": null, "e": 11638, "s": 11424, "text": "def detect_noisy_samples(X,y,thres=.5): #Returns noisy indexes knn = KNeighborsClassifier().fit(X,y) noise_prob = 1 - knn.predict_proba(X)[range(len(X)),y] return np.argwhere(noise_prob>thres).reshape(-1)" }, { "code": null, "e": 12275, "s": 11638, "text": "It is worth emphasizing that cleaning data doesn’t have to mean simply throwing away suspected mislabeled samples. Both of the heuristics described above returns continuous probability of (a sample) being mislabeled. We can use the inverse of that probability as a sort of reliability or confidence score, and use cost-sensitive learning to utilize this information. In this way, we get to retain all data points, which is especially important when the noise level is high or dataset size is small. Plus, this is more general than filtering- filtering is a special instance of cost-sensitive approach where the cost can be only 0 and 1." }, { "code": null, "e": 12469, "s": 12275, "text": "Thanks for staying this far! I hope this article has been useful. But please remember that this is simply an introduction, and therefore leaves out a lot of interesting and important questions." }, { "code": null, "e": 13126, "s": 12469, "text": "For example, we haven’t really talked about “Noise Model” here. We only focused on the overall percentage of mislabeled samples, assuming the wrong label for a mislabeled instance can come from any of the other labels with equal probability. This is not unrealistic, this so-called uniform noise model can arise e.g. when an amazon bot randomly assigns labels. But we know from common sense that a serious human annotator is much more likely to confuse between say 9 and 7 than 9 and 8, or between positive and neutral sentiment than positive and negative sentiment- and the uniform noise model doesn’t quite capture this uneven interaction between labels." }, { "code": null, "e": 13328, "s": 13126, "text": "Another interesting question is regarding how we should act when we haven’t yet collected labels: Do we collect a big amount of low-quality data? or do we collect a small quantity of high-quality data?" }, { "code": null, "e": 13514, "s": 13328, "text": "Anyway, I hope this introduction serves as a good starting point. I’m planning to address these left-out issues and several others in a series of articles in near future, so stay tuned." }, { "code": null, "e": 13560, "s": 13514, "text": "[1] https://escholarship.org/uc/item/9zt9g3wt" }, { "code": null, "e": 13609, "s": 13560, "text": "[2] https://ieeexplore.ieee.org/document/8765743" } ]
How to Swap a Values in MySQL? - GeeksforGeeks
19 Nov, 2021 The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. Suppose we want to need to write a SQL query to swap all ‘a’ and ‘m’ values (i.e., change all ‘f’ values to ‘m’ and vice versa) with a single update statement and no intermediate temporary tables, then following are the steps: Step 1: Creating the Database Use the below SQL statement to create a database called geeks: Query: create database geeksforgeeks; Step 2: Using the Database Use the below SQL statement to switch the database context to geeks: Query: use geeksforgeeks; Step 3: Table Definition We have the following Salary table in our geeksforgeeks database. Query: create table Salary(id int , name varchar(20) , sex varchar(1) , salary int); the table Salary contains information about an employee. Step 4: Inserting Values in the table Query: insert into Salary values(1 , "A" , "m" , 2500); insert into Salary values(2 , "B" , "f" , 1500); insert into Salary values(3 , "C" , "m" , 5500); insert into Salary values(4 , "D" , "f" , 500); Step 5: Suppose we want to update a particular value in the table then the query will be as follows MySQL Query: update Salary set sex = if(sex='m' , 'f','m'); here in the above query, we are using the IF() function to swap f and m, return f if sex is m, return m otherwise. Output: mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 Nov, 2021" }, { "code": null, "e": 25966, "s": 25537, "text": "The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. Suppose we want to need to write a SQL query to swap all ‘a’ and ‘m’ values (i.e., change all ‘f’ values to ‘m’ and vice versa) with a single update statement and no intermediate temporary tables, then following are the steps:" }, { "code": null, "e": 25996, "s": 25966, "text": "Step 1: Creating the Database" }, { "code": null, "e": 26059, "s": 25996, "text": "Use the below SQL statement to create a database called geeks:" }, { "code": null, "e": 26066, "s": 26059, "text": "Query:" }, { "code": null, "e": 26097, "s": 26066, "text": "create database geeksforgeeks;" }, { "code": null, "e": 26124, "s": 26097, "text": "Step 2: Using the Database" }, { "code": null, "e": 26193, "s": 26124, "text": "Use the below SQL statement to switch the database context to geeks:" }, { "code": null, "e": 26200, "s": 26193, "text": "Query:" }, { "code": null, "e": 26219, "s": 26200, "text": "use geeksforgeeks;" }, { "code": null, "e": 26244, "s": 26219, "text": "Step 3: Table Definition" }, { "code": null, "e": 26310, "s": 26244, "text": "We have the following Salary table in our geeksforgeeks database." }, { "code": null, "e": 26317, "s": 26310, "text": "Query:" }, { "code": null, "e": 26397, "s": 26317, "text": "create table Salary(id int , name varchar(20) , sex varchar(1) ,\n salary int);" }, { "code": null, "e": 26454, "s": 26397, "text": "the table Salary contains information about an employee." }, { "code": null, "e": 26492, "s": 26454, "text": "Step 4: Inserting Values in the table" }, { "code": null, "e": 26499, "s": 26492, "text": "Query:" }, { "code": null, "e": 26695, "s": 26499, "text": "insert into Salary values(1 , \"A\" , \"m\" , 2500);\ninsert into Salary values(2 , \"B\" , \"f\" , 1500);\ninsert into Salary values(3 , \"C\" , \"m\" , 5500);\ninsert into Salary values(4 , \"D\" , \"f\" , 500);" }, { "code": null, "e": 26795, "s": 26695, "text": "Step 5: Suppose we want to update a particular value in the table then the query will be as follows" }, { "code": null, "e": 26808, "s": 26795, "text": "MySQL Query:" }, { "code": null, "e": 26855, "s": 26808, "text": "update Salary set sex = if(sex='m' , 'f','m');" }, { "code": null, "e": 26970, "s": 26855, "text": "here in the above query, we are using the IF() function to swap f and m, return f if sex is m, return m otherwise." }, { "code": null, "e": 26978, "s": 26970, "text": "Output:" }, { "code": null, "e": 26984, "s": 26978, "text": "mysql" }, { "code": null, "e": 26988, "s": 26984, "text": "SQL" }, { "code": null, "e": 26992, "s": 26988, "text": "SQL" }, { "code": null, "e": 27090, "s": 26992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27156, "s": 27090, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27171, "s": 27156, "text": "SQL | Subquery" }, { "code": null, "e": 27228, "s": 27171, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27260, "s": 27228, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27338, "s": 27260, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27374, "s": 27338, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27391, "s": 27374, "text": "SQL using Python" }, { "code": null, "e": 27457, "s": 27391, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27519, "s": 27457, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Reduce size of legend area using ggplot in R - GeeksforGeeks
30 May, 2021 In this article, we will are going to see how to change the size of the legend in the plot in the R programming language. We will change legend size of the plot using cex argument of legend() function. In this approach to change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot. cex: This is a number indicating the amount by which plotting text and symbols should be scaled relative to the default. 1=default, 1.5 is 50% larger, 0.5 is 50% smaller, etc. Example1: In this example, we will be decreasing the size of the legend of the plot using the cex parameter as 0.5 in the legend() function of the R programming language. R x1 <- c(1, 8, 5, 3, 8, 7) y1 <- c(4, 6, 3, 8, 2, 7) plot(x1, y1, cex = .8, pch = 1, col = "red") x2<-c(4, 5, 8, 6, 4)y2<-c(9, 8, 2, 3, 1)x3<-c(2, 1, 6, 7, 4)y3<-c(7, 9, 1, 5, 2) points(x2, y2, cex = .8, pch = 2, col = "blue")points(x3, y3, cex = .8, pch = 3, col = "green") legend("topright", c("gfg1", "gfg2", "gfg3"), cex = 0.5, col = c("red", "blue", "green"), pch = c(1, 2, 3)) Output: Example 2: In this example, we will be decreasing the size of the legend of the plot using the cex parameter as 0.5 in the legend() function of the R programming language. R gfg_data <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ncol = 5) colnames(gfg_data) <- paste0("Gfg", 1:5)rownames(gfg_data) <- c('A','B') gfg_data barplot(gfg_data, col = 1 : nrow(gfg_data)) legend("topright", legend = rownames(gfg_data), pch = 15, col = 1 : nrow(gfg_data), cex = 0.5) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n30 May, 2021" }, { "code": null, "e": 26689, "s": 26487, "text": "In this article, we will are going to see how to change the size of the legend in the plot in the R programming language. We will change legend size of the plot using cex argument of legend() function." }, { "code": null, "e": 27014, "s": 26689, "text": "In this approach to change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot." }, { "code": null, "e": 27190, "s": 27014, "text": "cex: This is a number indicating the amount by which plotting text and symbols should be scaled relative to the default. 1=default, 1.5 is 50% larger, 0.5 is 50% smaller, etc." }, { "code": null, "e": 27361, "s": 27190, "text": "Example1: In this example, we will be decreasing the size of the legend of the plot using the cex parameter as 0.5 in the legend() function of the R programming language." }, { "code": null, "e": 27363, "s": 27361, "text": "R" }, { "code": "x1 <- c(1, 8, 5, 3, 8, 7) y1 <- c(4, 6, 3, 8, 2, 7) plot(x1, y1, cex = .8, pch = 1, col = \"red\") x2<-c(4, 5, 8, 6, 4)y2<-c(9, 8, 2, 3, 1)x3<-c(2, 1, 6, 7, 4)y3<-c(7, 9, 1, 5, 2) points(x2, y2, cex = .8, pch = 2, col = \"blue\")points(x3, y3, cex = .8, pch = 3, col = \"green\") legend(\"topright\", c(\"gfg1\", \"gfg2\", \"gfg3\"), cex = 0.5, col = c(\"red\", \"blue\", \"green\"), pch = c(1, 2, 3))", "e": 27780, "s": 27363, "text": null }, { "code": null, "e": 27788, "s": 27780, "text": "Output:" }, { "code": null, "e": 27960, "s": 27788, "text": "Example 2: In this example, we will be decreasing the size of the legend of the plot using the cex parameter as 0.5 in the legend() function of the R programming language." }, { "code": null, "e": 27962, "s": 27960, "text": "R" }, { "code": "gfg_data <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ncol = 5) colnames(gfg_data) <- paste0(\"Gfg\", 1:5)rownames(gfg_data) <- c('A','B') gfg_data barplot(gfg_data, col = 1 : nrow(gfg_data)) legend(\"topright\", legend = rownames(gfg_data), pch = 15, col = 1 : nrow(gfg_data), cex = 0.5)", "e": 28296, "s": 27962, "text": null }, { "code": null, "e": 28304, "s": 28296, "text": "Output:" }, { "code": null, "e": 28311, "s": 28304, "text": "Picked" }, { "code": null, "e": 28320, "s": 28311, "text": "R-ggplot" }, { "code": null, "e": 28331, "s": 28320, "text": "R Language" }, { "code": null, "e": 28429, "s": 28331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28481, "s": 28429, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28516, "s": 28481, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28554, "s": 28516, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28612, "s": 28554, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28655, "s": 28612, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28704, "s": 28655, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28741, "s": 28704, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28758, "s": 28741, "text": "R - if statement" }, { "code": null, "e": 28784, "s": 28758, "text": "Time Series Analysis in R" } ]
Dart - Generics - GeeksforGeeks
12 Mar, 2021 In Dart, by default collections are heterogeneous. However, by the use of generics, we can make a collection to hold homogeneous values. The use of Generics makes the use of a single compulsory data type to be held inside the collection. Such collections are called type-safe collections. By the use of generics, type safety is ensured in the Dart language. Syntax: Collection_name <data_type> identifier= new Collection_name<data_type> We can use List, Set, Map, and Queue generics to implement type safety in Dart. In Dart, a List is simply an ordered group of objects. A list is simply an implementation of an array. Example: Dart main() { List <int> listEx = new List <int>(); listEx.add(341); listEx.add(1); listEx.add(23); // iterating across list listEx for (int element in listEx) { print(element); } } Output: 341 1 23 In Dart, a Set represents a collection of objects in which each object can exist only once. Example: Dart main() { Set <int> SetEx = new Set <int>(); SetEx.add(12); SetEx.add(3); SetEx.add(4); // Already added once, hence wont be added SetEx.add(3); // iterating across Set SetEx for (int element in SetEx) { print(element); } } Output: 12 3 4 In Dart, Map is a dynamic collection of the key, value pairs. Example: Dart main() { // Creating a Map with Name and ids of students Map <String,int> mp={'Ankur':1,'Arnav':002,'Shivam':003}; print('Map :${mp}'); } Output: Map :{Ankur: 1, Arnav: 2, Shivam: 3} A queue is a collection that is used when the data is to be inserted in a FIFO (First in first out) manner. In Dart, a queue can be manipulated at both ends, i.e. at the start as well as the end of the queue. Example: Dart import 'dart:collection'; main() { Queue<int> q = new Queue<int>(); // Inserting at end of the queue q.addLast(1); // Inserting at end of the queue q.addLast(2); // Inserting at start of the queue q.addFirst(3); // Inserting at end of the queue q.addLast(4); // Current Queue order is 3 1 2 4. // Removing the first element(3) of the queue q.removeFirst(); // Iterating over the queue for(int element in q){ print(element); } } Output: 1 2 4 Dart Data-types Picked Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Positioned Widget Format Dates in Flutter Flutter - Managing the MediaQuery Object What is widgets in Flutter?
[ { "code": null, "e": 25261, "s": 25233, "text": "\n12 Mar, 2021" }, { "code": null, "e": 25619, "s": 25261, "text": "In Dart, by default collections are heterogeneous. However, by the use of generics, we can make a collection to hold homogeneous values. The use of Generics makes the use of a single compulsory data type to be held inside the collection. Such collections are called type-safe collections. By the use of generics, type safety is ensured in the Dart language." }, { "code": null, "e": 25627, "s": 25619, "text": "Syntax:" }, { "code": null, "e": 25699, "s": 25627, "text": "Collection_name <data_type> identifier= new Collection_name<data_type> " }, { "code": null, "e": 25779, "s": 25699, "text": "We can use List, Set, Map, and Queue generics to implement type safety in Dart." }, { "code": null, "e": 25882, "s": 25779, "text": "In Dart, a List is simply an ordered group of objects. A list is simply an implementation of an array." }, { "code": null, "e": 25891, "s": 25882, "text": "Example:" }, { "code": null, "e": 25896, "s": 25891, "text": "Dart" }, { "code": "main() { List <int> listEx = new List <int>(); listEx.add(341); listEx.add(1); listEx.add(23); // iterating across list listEx for (int element in listEx) { print(element); } }", "e": 26106, "s": 25896, "text": null }, { "code": null, "e": 26114, "s": 26106, "text": "Output:" }, { "code": null, "e": 26123, "s": 26114, "text": "341\n1\n23" }, { "code": null, "e": 26215, "s": 26123, "text": "In Dart, a Set represents a collection of objects in which each object can exist only once." }, { "code": null, "e": 26224, "s": 26215, "text": "Example:" }, { "code": null, "e": 26229, "s": 26224, "text": "Dart" }, { "code": "main() { Set <int> SetEx = new Set <int>(); SetEx.add(12); SetEx.add(3); SetEx.add(4); // Already added once, hence wont be added SetEx.add(3); // iterating across Set SetEx for (int element in SetEx) { print(element); } }", "e": 26492, "s": 26229, "text": null }, { "code": null, "e": 26500, "s": 26492, "text": "Output:" }, { "code": null, "e": 26507, "s": 26500, "text": "12\n3\n4" }, { "code": null, "e": 26569, "s": 26507, "text": "In Dart, Map is a dynamic collection of the key, value pairs." }, { "code": null, "e": 26578, "s": 26569, "text": "Example:" }, { "code": null, "e": 26583, "s": 26578, "text": "Dart" }, { "code": "main() { // Creating a Map with Name and ids of students Map <String,int> mp={'Ankur':1,'Arnav':002,'Shivam':003}; print('Map :${mp}'); }", "e": 26733, "s": 26583, "text": null }, { "code": null, "e": 26741, "s": 26733, "text": "Output:" }, { "code": null, "e": 26778, "s": 26741, "text": "Map :{Ankur: 1, Arnav: 2, Shivam: 3}" }, { "code": null, "e": 26987, "s": 26778, "text": "A queue is a collection that is used when the data is to be inserted in a FIFO (First in first out) manner. In Dart, a queue can be manipulated at both ends, i.e. at the start as well as the end of the queue." }, { "code": null, "e": 26996, "s": 26987, "text": "Example:" }, { "code": null, "e": 27001, "s": 26996, "text": "Dart" }, { "code": "import 'dart:collection'; main() { Queue<int> q = new Queue<int>(); // Inserting at end of the queue q.addLast(1); // Inserting at end of the queue q.addLast(2); // Inserting at start of the queue q.addFirst(3); // Inserting at end of the queue q.addLast(4); // Current Queue order is 3 1 2 4. // Removing the first element(3) of the queue q.removeFirst(); // Iterating over the queue for(int element in q){ print(element); } }", "e": 27498, "s": 27001, "text": null }, { "code": null, "e": 27506, "s": 27498, "text": "Output:" }, { "code": null, "e": 27512, "s": 27506, "text": "1\n2\n4" }, { "code": null, "e": 27528, "s": 27512, "text": "Dart Data-types" }, { "code": null, "e": 27535, "s": 27528, "text": "Picked" }, { "code": null, "e": 27540, "s": 27535, "text": "Dart" }, { "code": null, "e": 27638, "s": 27540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27677, "s": 27638, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27703, "s": 27677, "text": "ListView Class in Flutter" }, { "code": null, "e": 27729, "s": 27703, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27752, "s": 27729, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27770, "s": 27752, "text": "Flutter - Dialogs" }, { "code": null, "e": 27815, "s": 27770, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 27843, "s": 27815, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 27867, "s": 27843, "text": "Format Dates in Flutter" }, { "code": null, "e": 27908, "s": 27867, "text": "Flutter - Managing the MediaQuery Object" } ]
strconv.Atoi() Function in Golang With Examples - GeeksforGeeks
21 Apr, 2020 Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Atoi() function which is equivalent to ParseInt(str string, base int, bitSize int) is used to convert string type into int type. To access Atoi() function you need to import strconv Package in your program. Syntax: func Atoi(str string) (int, error) Here, str is the string. Example 1: // Golang program to illustrate// strconv.Atoi() functionpackage main import ( "fmt" "strconv") func main() { // Using Atoi() function x := "245" y, e := strconv.Atoi(x) if e == nil { fmt.Printf("%T \n %v", y, y) } } Output: int 245 Example 2: // Golang program to illustrate// strconv.Atoi() functionpackage main import ( "fmt" "strconv") func main() { // Using Atoi() function x1 := "245" fmt.Println("Before:") fmt.Printf("Type: %T ", x1) fmt.Printf("\nValue: %v", x1) y1, e1 := strconv.Atoi(x1) if e1 == nil { fmt.Println("\nAfter:") fmt.Printf("Type: %T ", y1) fmt.Printf("\nValue: %v", y1) } x2 := "1" fmt.Println("\n\nBefore:") fmt.Printf("Type: %T ", x2) fmt.Printf("\nValue: %v", x2) y2, e2 := strconv.Atoi(x2) if e2 == nil { fmt.Println("\nAfter:") fmt.Printf("Type: %T ", y2) fmt.Printf("\nValue: %v", y2) } } Output: Before: Type: string Value: 245 After: Type: int Value: 245 Before: Type: string Value: 1 After: Type: int Value: 1 Golang-strconv Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? 6 Best Books to Learn Go Programming Language Golang Maps Slices in Golang Different Ways to Find the Type of Variable in Golang Inheritance in GoLang Interfaces in Golang
[ { "code": null, "e": 25695, "s": 25667, "text": "\n21 Apr, 2020" }, { "code": null, "e": 26064, "s": 25695, "text": "Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Atoi() function which is equivalent to ParseInt(str string, base int, bitSize int) is used to convert string type into int type. To access Atoi() function you need to import strconv Package in your program." }, { "code": null, "e": 26072, "s": 26064, "text": "Syntax:" }, { "code": null, "e": 26107, "s": 26072, "text": "func Atoi(str string) (int, error)" }, { "code": null, "e": 26132, "s": 26107, "text": "Here, str is the string." }, { "code": null, "e": 26143, "s": 26132, "text": "Example 1:" }, { "code": "// Golang program to illustrate// strconv.Atoi() functionpackage main import ( \"fmt\" \"strconv\") func main() { // Using Atoi() function x := \"245\" y, e := strconv.Atoi(x) if e == nil { fmt.Printf(\"%T \\n %v\", y, y) } }", "e": 26393, "s": 26143, "text": null }, { "code": null, "e": 26401, "s": 26393, "text": "Output:" }, { "code": null, "e": 26412, "s": 26401, "text": "int \n 245\n" }, { "code": null, "e": 26423, "s": 26412, "text": "Example 2:" }, { "code": "// Golang program to illustrate// strconv.Atoi() functionpackage main import ( \"fmt\" \"strconv\") func main() { // Using Atoi() function x1 := \"245\" fmt.Println(\"Before:\") fmt.Printf(\"Type: %T \", x1) fmt.Printf(\"\\nValue: %v\", x1) y1, e1 := strconv.Atoi(x1) if e1 == nil { fmt.Println(\"\\nAfter:\") fmt.Printf(\"Type: %T \", y1) fmt.Printf(\"\\nValue: %v\", y1) } x2 := \"1\" fmt.Println(\"\\n\\nBefore:\") fmt.Printf(\"Type: %T \", x2) fmt.Printf(\"\\nValue: %v\", x2) y2, e2 := strconv.Atoi(x2) if e2 == nil { fmt.Println(\"\\nAfter:\") fmt.Printf(\"Type: %T \", y2) fmt.Printf(\"\\nValue: %v\", y2) } }", "e": 27100, "s": 26423, "text": null }, { "code": null, "e": 27108, "s": 27100, "text": "Output:" }, { "code": null, "e": 27230, "s": 27108, "text": "Before:\nType: string \nValue: 245\nAfter:\nType: int \nValue: 245\n\nBefore:\nType: string \nValue: 1\nAfter:\nType: int \nValue: 1\n" }, { "code": null, "e": 27245, "s": 27230, "text": "Golang-strconv" }, { "code": null, "e": 27257, "s": 27245, "text": "Go Language" }, { "code": null, "e": 27355, "s": 27257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27406, "s": 27355, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 27419, "s": 27406, "text": "Arrays in Go" }, { "code": null, "e": 27466, "s": 27419, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 27499, "s": 27466, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27545, "s": 27499, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27557, "s": 27545, "text": "Golang Maps" }, { "code": null, "e": 27574, "s": 27557, "text": "Slices in Golang" }, { "code": null, "e": 27628, "s": 27574, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 27650, "s": 27628, "text": "Inheritance in GoLang" } ]
ML | Reinforcement Learning Algorithm : Python Implementation using Q-learning - GeeksforGeeks
07 Jun, 2019 Prerequisites: Q-Learning technique. Reinforcement Learning is a type of Machine Learning paradigms in which a learning algorithm is trained not on preset data but rather based on a feedback system. These algorithms are touted as the future of Machine Learning as these eliminate the cost of collecting and cleaning the data. In this article, we are going to demonstrate how to implement a basic Reinforcement Learning algorithm which is called the Q-Learning technique. In this demonstration, we attempt to teach a bot to reach its destination using the Q-Learning technique. Step 1: Importing the required libraries import numpy as npimport pylab as plimport networkx as nx Step 2: Defining and visualising the graph edges = [(0, 1), (1, 5), (5, 6), (5, 4), (1, 2), (1, 3), (9, 10), (2, 4), (0, 6), (6, 7), (8, 9), (7, 8), (1, 7), (3, 9)] goal = 10G = nx.Graph()G.add_edges_from(edges)pos = nx.spring_layout(G)nx.draw_networkx_nodes(G, pos)nx.draw_networkx_edges(G, pos)nx.draw_networkx_labels(G, pos)pl.show() Note: The above graph may not look the same on reproduction of the code because the networkx library in python produces a random graph from the given edges. Step 3: Defining the reward the system for the bot MATRIX_SIZE = 11M = np.matrix(np.ones(shape =(MATRIX_SIZE, MATRIX_SIZE)))M *= -1 for point in edges: print(point) if point[1] == goal: M[point] = 100 else: M[point] = 0 if point[0] == goal: M[point[::-1]] = 100 else: M[point[::-1]]= 0 # reverse of point M[goal, goal]= 100print(M)# add goal point round trip Step 4: Defining some utility functions to be used in the training Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE])) gamma = 0.75# learning parameterinitial_state = 1 # Determines the available actions for a given statedef available_actions(state): current_state_row = M[state, ] available_action = np.where(current_state_row >= 0)[1] return available_action available_action = available_actions(initial_state) # Chooses one of the available actions at randomdef sample_next_action(available_actions_range): next_action = int(np.random.choice(available_action, 1)) return next_action action = sample_next_action(available_action) def update(current_state, action, gamma): max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1] if max_index.shape[0] > 1: max_index = int(np.random.choice(max_index, size = 1)) else: max_index = int(max_index) max_value = Q[action, max_index] Q[current_state, action] = M[current_state, action] + gamma * max_value if (np.max(Q) > 0): return(np.sum(Q / np.max(Q)*100)) else: return (0)# Updates the Q-Matrix according to the path chosen update(initial_state, action, gamma) Step 5: Training and evaluating the bot using the Q-Matrix scores = []for i in range(1000): current_state = np.random.randint(0, int(Q.shape[0])) available_action = available_actions(current_state) action = sample_next_action(available_action) score = update(current_state, action, gamma) scores.append(score) # print("Trained Q matrix:")# print(Q / np.max(Q)*100)# You can uncomment the above two lines to view the trained Q matrix # Testingcurrent_state = 0steps = [current_state] while current_state != 10: next_step_index = np.where(Q[current_state, ] == np.max(Q[current_state, ]))[1] if next_step_index.shape[0] > 1: next_step_index = int(np.random.choice(next_step_index, size = 1)) else: next_step_index = int(next_step_index) steps.append(next_step_index) current_state = next_step_index print("Most efficient path:")print(steps) pl.plot(scores)pl.xlabel('No of iterations')pl.ylabel('Reward gained')pl.show() Now, Let’s bring this bot to a more realistic setting. Let us imagine that the bot is a detective and is trying to find out the location of a large drug racket. He naturally concludes that the drug sellers will not sell their products in a location which is known to be frequented by the police and the selling locations are near the location of the drug racket. Also, the sellers leave a trace of their products where they sell it and this can help the detective in finding out the required location. We want to train our bot to find the location using these Environmental Clues. Step 6: Defining and visualizing the new graph with the environmental clues # Defining the locations of the police and the drug tracespolice = [2, 4, 5]drug_traces = [3, 8, 9] G = nx.Graph()G.add_edges_from(edges)mapping = {0:'0 - Detective', 1:'1', 2:'2 - Police', 3:'3 - Drug traces', 4:'4 - Police', 5:'5 - Police', 6:'6', 7:'7', 8:'Drug traces', 9:'9 - Drug traces', 10:'10 - Drug racket location'} H = nx.relabel_nodes(G, mapping)pos = nx.spring_layout(H)nx.draw_networkx_nodes(H, pos, node_size =[200, 200, 200, 200, 200, 200, 200, 200])nx.draw_networkx_edges(H, pos)nx.draw_networkx_labels(H, pos)pl.show() Note: The above graph may look a bit different from the previous graph but they, in fact, are the same graphs. This is due to the random placement of nodes by the networkx library. Step 7: Defining some utility functions for the training process Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))env_police = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))env_drugs = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))initial_state = 1 # Same as abovedef available_actions(state): current_state_row = M[state, ] av_action = np.where(current_state_row >= 0)[1] return av_action # Same as abovedef sample_next_action(available_actions_range): next_action = int(np.random.choice(available_action, 1)) return next_action # Exploring the environmentdef collect_environmental_data(action): found = [] if action in police: found.append('p') if action in drug_traces: found.append('d') return (found) available_action = available_actions(initial_state)action = sample_next_action(available_action) def update(current_state, action, gamma): max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1] if max_index.shape[0] > 1: max_index = int(np.random.choice(max_index, size = 1)) else: max_index = int(max_index) max_value = Q[action, max_index] Q[current_state, action] = M[current_state, action] + gamma * max_value environment = collect_environmental_data(action) if 'p' in environment: env_police[current_state, action] += 1 if 'd' in environment: env_drugs[current_state, action] += 1 if (np.max(Q) > 0): return(np.sum(Q / np.max(Q)*100)) else: return (0)# Same as aboveupdate(initial_state, action, gamma) def available_actions_with_env_help(state): current_state_row = M[state, ] av_action = np.where(current_state_row >= 0)[1] # if there are multiple routes, dis-favor anything negative env_pos_row = env_matrix_snap[state, av_action] if (np.sum(env_pos_row < 0)): # can we remove the negative directions from av_act? temp_av_action = av_action[np.array(env_pos_row)[0]>= 0] if len(temp_av_action) > 0: av_action = temp_av_action return av_action# Determines the available actions according to the environment Step 8: Visualising the Environmental matrices scores = []for i in range(1000): current_state = np.random.randint(0, int(Q.shape[0])) available_action = available_actions(current_state) action = sample_next_action(available_action) score = update(current_state, action, gamma) # print environmental matricesprint('Police Found')print(env_police)print('')print('Drug traces Found')print(env_drugs) Step 9: Training and evaluating the model scores = []for i in range(1000): current_state = np.random.randint(0, int(Q.shape[0])) available_action = available_actions_with_env_help(current_state) action = sample_next_action(available_action) score = update(current_state, action, gamma) scores.append(score) pl.plot(scores)pl.xlabel('Number of iterations')pl.ylabel('Reward gained')pl.show() The example taken above was a very basic one and many practical examples like Self Driving Cars involve the concept of Game Theory. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25613, "s": 25585, "text": "\n07 Jun, 2019" }, { "code": null, "e": 25650, "s": 25613, "text": "Prerequisites: Q-Learning technique." }, { "code": null, "e": 25939, "s": 25650, "text": "Reinforcement Learning is a type of Machine Learning paradigms in which a learning algorithm is trained not on preset data but rather based on a feedback system. These algorithms are touted as the future of Machine Learning as these eliminate the cost of collecting and cleaning the data." }, { "code": null, "e": 26190, "s": 25939, "text": "In this article, we are going to demonstrate how to implement a basic Reinforcement Learning algorithm which is called the Q-Learning technique. In this demonstration, we attempt to teach a bot to reach its destination using the Q-Learning technique." }, { "code": null, "e": 26231, "s": 26190, "text": "Step 1: Importing the required libraries" }, { "code": "import numpy as npimport pylab as plimport networkx as nx", "e": 26289, "s": 26231, "text": null }, { "code": null, "e": 26332, "s": 26289, "text": "Step 2: Defining and visualising the graph" }, { "code": "edges = [(0, 1), (1, 5), (5, 6), (5, 4), (1, 2), (1, 3), (9, 10), (2, 4), (0, 6), (6, 7), (8, 9), (7, 8), (1, 7), (3, 9)] goal = 10G = nx.Graph()G.add_edges_from(edges)pos = nx.spring_layout(G)nx.draw_networkx_nodes(G, pos)nx.draw_networkx_edges(G, pos)nx.draw_networkx_labels(G, pos)pl.show()", "e": 26644, "s": 26332, "text": null }, { "code": null, "e": 26801, "s": 26644, "text": "Note: The above graph may not look the same on reproduction of the code because the networkx library in python produces a random graph from the given edges." }, { "code": null, "e": 26852, "s": 26801, "text": "Step 3: Defining the reward the system for the bot" }, { "code": "MATRIX_SIZE = 11M = np.matrix(np.ones(shape =(MATRIX_SIZE, MATRIX_SIZE)))M *= -1 for point in edges: print(point) if point[1] == goal: M[point] = 100 else: M[point] = 0 if point[0] == goal: M[point[::-1]] = 100 else: M[point[::-1]]= 0 # reverse of point M[goal, goal]= 100print(M)# add goal point round trip", "e": 27214, "s": 26852, "text": null }, { "code": null, "e": 27281, "s": 27214, "text": "Step 4: Defining some utility functions to be used in the training" }, { "code": "Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE])) gamma = 0.75# learning parameterinitial_state = 1 # Determines the available actions for a given statedef available_actions(state): current_state_row = M[state, ] available_action = np.where(current_state_row >= 0)[1] return available_action available_action = available_actions(initial_state) # Chooses one of the available actions at randomdef sample_next_action(available_actions_range): next_action = int(np.random.choice(available_action, 1)) return next_action action = sample_next_action(available_action) def update(current_state, action, gamma): max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1] if max_index.shape[0] > 1: max_index = int(np.random.choice(max_index, size = 1)) else: max_index = int(max_index) max_value = Q[action, max_index] Q[current_state, action] = M[current_state, action] + gamma * max_value if (np.max(Q) > 0): return(np.sum(Q / np.max(Q)*100)) else: return (0)# Updates the Q-Matrix according to the path chosen update(initial_state, action, gamma)", "e": 28376, "s": 27281, "text": null }, { "code": null, "e": 28435, "s": 28376, "text": "Step 5: Training and evaluating the bot using the Q-Matrix" }, { "code": "scores = []for i in range(1000): current_state = np.random.randint(0, int(Q.shape[0])) available_action = available_actions(current_state) action = sample_next_action(available_action) score = update(current_state, action, gamma) scores.append(score) # print(\"Trained Q matrix:\")# print(Q / np.max(Q)*100)# You can uncomment the above two lines to view the trained Q matrix # Testingcurrent_state = 0steps = [current_state] while current_state != 10: next_step_index = np.where(Q[current_state, ] == np.max(Q[current_state, ]))[1] if next_step_index.shape[0] > 1: next_step_index = int(np.random.choice(next_step_index, size = 1)) else: next_step_index = int(next_step_index) steps.append(next_step_index) current_state = next_step_index print(\"Most efficient path:\")print(steps) pl.plot(scores)pl.xlabel('No of iterations')pl.ylabel('Reward gained')pl.show()", "e": 29346, "s": 28435, "text": null }, { "code": null, "e": 29927, "s": 29346, "text": "Now, Let’s bring this bot to a more realistic setting. Let us imagine that the bot is a detective and is trying to find out the location of a large drug racket. He naturally concludes that the drug sellers will not sell their products in a location which is known to be frequented by the police and the selling locations are near the location of the drug racket. Also, the sellers leave a trace of their products where they sell it and this can help the detective in finding out the required location. We want to train our bot to find the location using these Environmental Clues." }, { "code": null, "e": 30003, "s": 29927, "text": "Step 6: Defining and visualizing the new graph with the environmental clues" }, { "code": "# Defining the locations of the police and the drug tracespolice = [2, 4, 5]drug_traces = [3, 8, 9] G = nx.Graph()G.add_edges_from(edges)mapping = {0:'0 - Detective', 1:'1', 2:'2 - Police', 3:'3 - Drug traces', 4:'4 - Police', 5:'5 - Police', 6:'6', 7:'7', 8:'Drug traces', 9:'9 - Drug traces', 10:'10 - Drug racket location'} H = nx.relabel_nodes(G, mapping)pos = nx.spring_layout(H)nx.draw_networkx_nodes(H, pos, node_size =[200, 200, 200, 200, 200, 200, 200, 200])nx.draw_networkx_edges(H, pos)nx.draw_networkx_labels(H, pos)pl.show() ", "e": 30564, "s": 30003, "text": null }, { "code": null, "e": 30745, "s": 30564, "text": "Note: The above graph may look a bit different from the previous graph but they, in fact, are the same graphs. This is due to the random placement of nodes by the networkx library." }, { "code": null, "e": 30810, "s": 30745, "text": "Step 7: Defining some utility functions for the training process" }, { "code": "Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))env_police = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))env_drugs = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))initial_state = 1 # Same as abovedef available_actions(state): current_state_row = M[state, ] av_action = np.where(current_state_row >= 0)[1] return av_action # Same as abovedef sample_next_action(available_actions_range): next_action = int(np.random.choice(available_action, 1)) return next_action # Exploring the environmentdef collect_environmental_data(action): found = [] if action in police: found.append('p') if action in drug_traces: found.append('d') return (found) available_action = available_actions(initial_state)action = sample_next_action(available_action) def update(current_state, action, gamma): max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1] if max_index.shape[0] > 1: max_index = int(np.random.choice(max_index, size = 1)) else: max_index = int(max_index) max_value = Q[action, max_index] Q[current_state, action] = M[current_state, action] + gamma * max_value environment = collect_environmental_data(action) if 'p' in environment: env_police[current_state, action] += 1 if 'd' in environment: env_drugs[current_state, action] += 1 if (np.max(Q) > 0): return(np.sum(Q / np.max(Q)*100)) else: return (0)# Same as aboveupdate(initial_state, action, gamma) def available_actions_with_env_help(state): current_state_row = M[state, ] av_action = np.where(current_state_row >= 0)[1] # if there are multiple routes, dis-favor anything negative env_pos_row = env_matrix_snap[state, av_action] if (np.sum(env_pos_row < 0)): # can we remove the negative directions from av_act? temp_av_action = av_action[np.array(env_pos_row)[0]>= 0] if len(temp_av_action) > 0: av_action = temp_av_action return av_action# Determines the available actions according to the environment", "e": 32810, "s": 30810, "text": null }, { "code": null, "e": 32857, "s": 32810, "text": "Step 8: Visualising the Environmental matrices" }, { "code": "scores = []for i in range(1000): current_state = np.random.randint(0, int(Q.shape[0])) available_action = available_actions(current_state) action = sample_next_action(available_action) score = update(current_state, action, gamma) # print environmental matricesprint('Police Found')print(env_police)print('')print('Drug traces Found')print(env_drugs)", "e": 33220, "s": 32857, "text": null }, { "code": null, "e": 33262, "s": 33220, "text": "Step 9: Training and evaluating the model" }, { "code": "scores = []for i in range(1000): current_state = np.random.randint(0, int(Q.shape[0])) available_action = available_actions_with_env_help(current_state) action = sample_next_action(available_action) score = update(current_state, action, gamma) scores.append(score) pl.plot(scores)pl.xlabel('Number of iterations')pl.ylabel('Reward gained')pl.show()", "e": 33627, "s": 33262, "text": null }, { "code": null, "e": 33759, "s": 33627, "text": "The example taken above was a very basic one and many practical examples like Self Driving Cars involve the concept of Game Theory." }, { "code": null, "e": 33776, "s": 33759, "text": "Machine Learning" }, { "code": null, "e": 33783, "s": 33776, "text": "Python" }, { "code": null, "e": 33800, "s": 33783, "text": "Machine Learning" }, { "code": null, "e": 33898, "s": 33800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33939, "s": 33898, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 33972, "s": 33939, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 34000, "s": 33972, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 34036, "s": 34000, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 34091, "s": 34036, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 34119, "s": 34091, "text": "Read JSON file using Python" }, { "code": null, "e": 34169, "s": 34119, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34191, "s": 34169, "text": "Python map() function" } ]
Calinski-Harabasz Index – Cluster Validity indices | Set 3 - GeeksforGeeks
25 Apr, 2022 Prerequisites: Cluster Validity Index Clustering validation has been recognized as one of the important factors essential to the success of clustering algorithms. How to effectively and efficiently assess the clustering results of clustering algorithms is the key to the problem. Generally, cluster validity measures are categorized into 3 classes (Internal cluster validation, External cluster validation and Relative cluster validation). In this article, we focus on an internal cluster validation index i.e. Calinski-Harabasz Index. Calinski-Harabasz Index: Calinski-Harabasz (CH) Index (introduced by Calinski and Harabasz in 1974) can be used to evaluate the model when ground truth labels are not known where the validation of how well the clustering has been done is made using quantities and features inherent to the dataset. The CH Index (also known as Variance ratio criterion) is a measure of how similar an object is to its own cluster (cohesion) compared to other clusters (separation). Here cohesion is estimated based on the distances from the data points in a cluster to its cluster centroid and separation is based on the distance of the cluster centroids from the global centroid. CH index has a form of (a . Separation)/(b . Cohesion) , where a and b are weights. Calculation of Calinski-Harabasz Index: The CH index for K number of clusters on a dataset D =[ d1 , d2 , d3 , ... dN ] is defined as, where, nk and ck are the no. of points and centroid of the kth cluster respectively, c is the global centroid, N is the total no. of data points. Higher value of CH index means the clusters are dense and well separated, although there is no “acceptable” cut-off value. We need to choose that solution which gives a peak or at least an abrupt elbow on the line plot of CH indices. On the other hand, if the line is smooth (horizontal or ascending or descending) then there is no such reason to prefer one solution over others. Line-plot of CH values vs No. of clusters for IRIS dataset Below is the Python implementation of the above CH index using the sklearn library : python3 from sklearn import datasetsfrom sklearn.cluster import KMeansfrom sklearn import metricsfrom sklearn.metrics import pairwise_distancesimport numpy as np # loading the datasetX, y = datasets.load_iris(return_X_y=True) # K-Meanskmeans = KMeans(n_clusters=3, random_state=1).fit(X) # we store the cluster labelslabels = kmeans.labels_ print(metrics.calinski_harabasz_score(X, labels)) Output: 561.62 References: https://scikit-learn.org/stable/modules/clustering.html#calinski-harabasz-index pyshark Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Activation functions in Neural Networks Introduction to Recurrent Neural Network Decision Tree Introduction with example Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25665, "s": 25637, "text": "\n25 Apr, 2022" }, { "code": null, "e": 25703, "s": 25665, "text": "Prerequisites: Cluster Validity Index" }, { "code": null, "e": 26105, "s": 25703, "text": "Clustering validation has been recognized as one of the important factors essential to the success of clustering algorithms. How to effectively and efficiently assess the clustering results of clustering algorithms is the key to the problem. Generally, cluster validity measures are categorized into 3 classes (Internal cluster validation, External cluster validation and Relative cluster validation)." }, { "code": null, "e": 26201, "s": 26105, "text": "In this article, we focus on an internal cluster validation index i.e. Calinski-Harabasz Index." }, { "code": null, "e": 26226, "s": 26201, "text": "Calinski-Harabasz Index:" }, { "code": null, "e": 26949, "s": 26226, "text": "Calinski-Harabasz (CH) Index (introduced by Calinski and Harabasz in 1974) can be used to evaluate the model when ground truth labels are not known where the validation of how well the clustering has been done is made using quantities and features inherent to the dataset. The CH Index (also known as Variance ratio criterion) is a measure of how similar an object is to its own cluster (cohesion) compared to other clusters (separation). Here cohesion is estimated based on the distances from the data points in a cluster to its cluster centroid and separation is based on the distance of the cluster centroids from the global centroid. CH index has a form of (a . Separation)/(b . Cohesion) , where a and b are weights. " }, { "code": null, "e": 26989, "s": 26949, "text": "Calculation of Calinski-Harabasz Index:" }, { "code": null, "e": 27084, "s": 26989, "text": "The CH index for K number of clusters on a dataset D =[ d1 , d2 , d3 , ... dN ] is defined as," }, { "code": null, "e": 27234, "s": 27086, "text": "where, nk and ck are the no. of points and centroid of the kth cluster respectively, c is the global centroid, N is the total no. of data points." }, { "code": null, "e": 27617, "s": 27236, "text": "Higher value of CH index means the clusters are dense and well separated, although there is no “acceptable” cut-off value. We need to choose that solution which gives a peak or at least an abrupt elbow on the line plot of CH indices. On the other hand, if the line is smooth (horizontal or ascending or descending) then there is no such reason to prefer one solution over others. " }, { "code": null, "e": 27678, "s": 27619, "text": "Line-plot of CH values vs No. of clusters for IRIS dataset" }, { "code": null, "e": 27765, "s": 27680, "text": "Below is the Python implementation of the above CH index using the sklearn library :" }, { "code": null, "e": 27775, "s": 27767, "text": "python3" }, { "code": "from sklearn import datasetsfrom sklearn.cluster import KMeansfrom sklearn import metricsfrom sklearn.metrics import pairwise_distancesimport numpy as np # loading the datasetX, y = datasets.load_iris(return_X_y=True) # K-Meanskmeans = KMeans(n_clusters=3, random_state=1).fit(X) # we store the cluster labelslabels = kmeans.labels_ print(metrics.calinski_harabasz_score(X, labels))", "e": 28158, "s": 27775, "text": null }, { "code": null, "e": 28166, "s": 28158, "text": "Output:" }, { "code": null, "e": 28173, "s": 28166, "text": "561.62" }, { "code": null, "e": 28186, "s": 28173, "text": "References: " }, { "code": null, "e": 28267, "s": 28186, "text": "https://scikit-learn.org/stable/modules/clustering.html#calinski-harabasz-index " }, { "code": null, "e": 28275, "s": 28267, "text": "pyshark" }, { "code": null, "e": 28292, "s": 28275, "text": "Machine Learning" }, { "code": null, "e": 28299, "s": 28292, "text": "Python" }, { "code": null, "e": 28316, "s": 28299, "text": "Machine Learning" }, { "code": null, "e": 28414, "s": 28316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28428, "s": 28414, "text": "Decision Tree" }, { "code": null, "e": 28468, "s": 28428, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 28509, "s": 28468, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28549, "s": 28509, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 28582, "s": 28549, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28610, "s": 28582, "text": "Read JSON file using Python" }, { "code": null, "e": 28660, "s": 28610, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28682, "s": 28660, "text": "Python map() function" } ]
Count ancestors with smaller value for each node of a Binary Tree - GeeksforGeeks
01 Jun, 2021 Given a Binary Tree consisting of N nodes, valued from 1 to N, rooted at node 1, the task is for each node is to count the number of ancestors with a value smaller than that of the current node. Examples: Input: Below is the given Tree: 1 / \ 4 5 / /\ 6 3 2Output: 0 1 1 1 1 2Explanation: Since node 1 is the root node, it has no ancestors.Ancestors of node 2: {1, 5}. Number of ancestors having value smaller than 2 is 1.Ancestors of node 3: {1, 5}. Number of ancestors having value smaller than 3 is 1.Ancestors of node 4: {1}. Number of ancestors having value smaller than 4 is 1.Ancestors of node 5: {1}. Number of ancestors having value smaller than 5 is 1.Ancestors of node 6: {1, 4}. Number of ancestors having value smaller than 6 is 2. Input: Below is the given Tree: 1 / \ 3 2 \ 4Output: 0 1 1 2 Explanation: Node 1 has no ancestors.Ancestors of node 2: {1}. Number of ancestors having value smaller than 2 is 1.Ancestors of node 3: {1}. Number of ancestors having value smaller than 3 is 1.Ancestors of node 4: {1, 2}. Number of ancestors having value smaller than 4 is 2. Approach: The idea is to perform DFS traversal from the root node of the Tree and store the immediate parent of each node in an array. Then iterate over each node and using the parent array, compare its value with all its ancestors. Finally, print the result. Follow the steps below to solve the problem: Initialize an array, say par[] of size N, with -1, to store the immediate parent of each node. Perform DFS traversal from the root node and perform the following steps:Update the parent of the current node.Recursively call the children of the current node. Update the parent of the current node. Recursively call the children of the current node. Now, iterate over the range [1, N] using a variable i and perform the following steps:Store the current node in a variable, say node.Iterate while par[node] is not equal to -1:If par[node] is less than i, then increment cnt by 1.Update node as par[node].After completing the above steps, print the value of cnt as the value for the current node. Store the current node in a variable, say node. Iterate while par[node] is not equal to -1:If par[node] is less than i, then increment cnt by 1.Update node as par[node]. If par[node] is less than i, then increment cnt by 1. Update node as par[node]. After completing the above steps, print the value of cnt as the value for the current node. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to add an edge// between nodes u and vvoid add_edge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Function to perform the DFS Traversal// and store parent of each nodevoid dfs(vector<int>& parent, vector<int> adj[], int u, int par = -1){ // Store the immediate parent parent[u] = par; // Traverse the children of // the current node for (auto child : adj[u]) { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); }} // Function to count the number of// ancestors with values smaller// than that of the current nodevoid countSmallerAncestors( vector<int> adj[], int n){ // Stores the parent of each node vector<int> parent(int(1e5), 0); // Perform the DFS Traversal dfs(parent, adj, 1); // Traverse all the nodes for (int i = 1; i <= n; i++) { int node = i; // Store the number of ancestors // smaller than node int cnt = 0; // Loop until parent[node] != -1 while (parent[node] != -1) { // If the condition satisfies, // increment cnt by 1 if (parent[node] < i) cnt += 1; node = parent[node]; } // Print the required result // for the current node cout << cnt << " "; }} // Driver Codeint main(){ int N = 6; vector<int> adj[int(1e5)]; // Tree Formation add_edge(adj, 1, 5); add_edge(adj, 1, 4); add_edge(adj, 4, 6); add_edge(adj, 5, 3); add_edge(adj, 5, 2); countSmallerAncestors(adj, N); return 0;} // Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to add an edge// between nodes u and vstatic void add_edge(ArrayList<ArrayList<Integer>> adj, int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to perform the DFS Traversal// and store parent of each nodestatic void dfs(ArrayList<Integer> parent, ArrayList<ArrayList<Integer>> adj, int u, int par){ // Store the immediate parent parent.set(u,par); // Traverse the children of // the current node for(int child : adj.get(u)) { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); }} // Function to count the number of// ancestors with values smaller// than that of the current nodestatic void countSmallerAncestors( ArrayList<ArrayList<Integer>> adj, int n){ // Stores the parent of each node ArrayList<Integer> parent = new ArrayList<Integer>(); for(int i = 0; i < (int)(1e5); i++) { parent.add(0); } // Perform the DFS Traversal dfs(parent, adj, 1, -1); // Traverse all the nodes for(int i = 1; i <= n; i++) { int node = i; // Store the number of ancestors // smaller than node int cnt = 0; // Loop until parent[node] != -1 while (parent.get(node) != -1) { // If the condition satisfies, // increment cnt by 1 if (parent.get(node) < i) cnt += 1; node = parent.get(node); } // Print the required result // for the current node System.out.print(cnt + " "); }} // Driver codepublic static void main (String[] args){ int N = 6; ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < (int)(1e5); i++) { adj.add(new ArrayList<Integer>()); } // Tree Formation add_edge(adj, 1, 5); add_edge(adj, 1, 4); add_edge(adj, 4, 6); add_edge(adj, 5, 3); add_edge(adj, 5, 2); countSmallerAncestors(adj, N);}} // This code is contributed by avanitrachhadiya2155 # Python3 program for the above approach # Function to add an edge# between nodes u and vdef add_edge(u, v): global adj adj[u].append(v) adj[v].append(u) # Function to perform the DFS Traversal# and store parent of each nodedef dfs(u, par = -1): global adj, parent # Store the immediate parent parent[u] = par # Traverse the children of # the current node for child in adj[u]: # Recursively call for # function dfs for the # child node if (child != par): dfs(child, u) # Function to count the number of# ancestors with values smaller# than that of the current nodedef countSmallerAncestors(n): global parent, adj # Stores the parent of each node # Perform the DFS Traversal dfs(1) # Traverse all the nodes for i in range(1, n + 1): node = i # Store the number of ancestors # smaller than node cnt = 0 # Loop until parent[node] != -1 while (parent[node] != -1): # If the condition satisfies, # increment cnt by 1 if (parent[node] < i): cnt += 1 node = parent[node] # Print the required result # for the current node print(cnt, end = " ") # Driver Codeif __name__ == '__main__': N = 6 adj = [[] for i in range(10**5)] parent = [0] * (10**5) # Tree Formation add_edge(1, 5) add_edge(1, 4) add_edge(4, 6) add_edge(5, 3) add_edge(5, 2) countSmallerAncestors(N) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to add an edge // between nodes u and v static void add_edge(List<List<int>> adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } // Function to perform the DFS Traversal // and store parent of each node static void dfs(List<int> parent, List<List<int>> adj, int u, int par = -1) { // Store the immediate parent parent[u] = par; // Traverse the children of // the current node foreach(int child in adj[u]) { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); } } // Function to count the number of // ancestors with values smaller // than that of the current node static void countSmallerAncestors( List<List<int>> adj, int n) { // Stores the parent of each node List<int> parent = new List<int>(); for(int i = 0; i < (int)(1e5); i++) { parent.Add(0); } // Perform the DFS Traversal dfs(parent, adj, 1); // Traverse all the nodes for (int i = 1; i <= n; i++) { int node = i; // Store the number of ancestors // smaller than node int cnt = 0; // Loop until parent[node] != -1 while (parent[node] != -1) { // If the condition satisfies, // increment cnt by 1 if (parent[node] < i) cnt += 1; node = parent[node]; } // Print the required result // for the current node Console.Write(cnt + " "); } } static void Main() { int N = 6; List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < (int)(1e5); i++) { adj.Add(new List<int>()); } // Tree Formation add_edge(adj, 1, 5); add_edge(adj, 1, 4); add_edge(adj, 4, 6); add_edge(adj, 5, 3); add_edge(adj, 5, 2); countSmallerAncestors(adj, N); }} <script> // JavaScript program for the above approach // Function to add an edge// between nodes u and vfunction add_edge(adj, u, v){ adj[u].push(v); adj[v].push(u);} // Function to perform the DFS Traversal// and store parent of each nodefunction dfs(parent, adj, u, par = -1){ // Store the immediate parent parent[u] = par; // Traverse the children of // the current node adj[u].forEach(child => { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); });} // Function to count the number of// ancestors with values smaller// than that of the current nodefunction countSmallerAncestors(adj, n){ // Stores the parent of each node var parent = Array(100000).fill(0); // Perform the DFS Traversal dfs(parent, adj, 1); // Traverse all the nodes for (var i = 1; i <= n; i++) { var node = i; // Store the number of ancestors // smaller than node var cnt = 0; // Loop until parent[node] != -1 while (parent[node] != -1) { // If the condition satisfies, // increment cnt by 1 if (parent[node] < i) cnt += 1; node = parent[node]; } // Print the required result // for the current node document.write( cnt + " "); }} // Driver Code var N = 6;var adj = Array.from(Array(100000), ()=>Array()); // Tree Formationadd_edge(adj, 1, 5);add_edge(adj, 1, 4);add_edge(adj, 4, 6);add_edge(adj, 5, 3);add_edge(adj, 5, 2);countSmallerAncestors(adj, N); </script> 0 1 1 1 1 2 Time Complexity: O(N2)Auxiliary Space: O(N) mohit kumar 29 divyeshrabadiya07 avanitrachhadiya2155 itsok DFS Mathematical Recursion Tree Mathematical Recursion DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Program for Sum of the digits of a given number
[ { "code": null, "e": 25937, "s": 25909, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26132, "s": 25937, "text": "Given a Binary Tree consisting of N nodes, valued from 1 to N, rooted at node 1, the task is for each node is to count the number of ancestors with a value smaller than that of the current node." }, { "code": null, "e": 26142, "s": 26132, "text": "Examples:" }, { "code": null, "e": 26771, "s": 26142, "text": "Input: Below is the given Tree: 1 / \\ 4 5 / /\\ 6 3 2Output: 0 1 1 1 1 2Explanation: Since node 1 is the root node, it has no ancestors.Ancestors of node 2: {1, 5}. Number of ancestors having value smaller than 2 is 1.Ancestors of node 3: {1, 5}. Number of ancestors having value smaller than 3 is 1.Ancestors of node 4: {1}. Number of ancestors having value smaller than 4 is 1.Ancestors of node 5: {1}. Number of ancestors having value smaller than 5 is 1.Ancestors of node 6: {1, 4}. Number of ancestors having value smaller than 6 is 2." }, { "code": null, "e": 27198, "s": 26771, "text": "Input: Below is the given Tree: 1 / \\ 3 2 \\ 4Output: 0 1 1 2 Explanation: Node 1 has no ancestors.Ancestors of node 2: {1}. Number of ancestors having value smaller than 2 is 1.Ancestors of node 3: {1}. Number of ancestors having value smaller than 3 is 1.Ancestors of node 4: {1, 2}. Number of ancestors having value smaller than 4 is 2." }, { "code": null, "e": 27503, "s": 27198, "text": "Approach: The idea is to perform DFS traversal from the root node of the Tree and store the immediate parent of each node in an array. Then iterate over each node and using the parent array, compare its value with all its ancestors. Finally, print the result. Follow the steps below to solve the problem:" }, { "code": null, "e": 27598, "s": 27503, "text": "Initialize an array, say par[] of size N, with -1, to store the immediate parent of each node." }, { "code": null, "e": 27760, "s": 27598, "text": "Perform DFS traversal from the root node and perform the following steps:Update the parent of the current node.Recursively call the children of the current node." }, { "code": null, "e": 27799, "s": 27760, "text": "Update the parent of the current node." }, { "code": null, "e": 27850, "s": 27799, "text": "Recursively call the children of the current node." }, { "code": null, "e": 28196, "s": 27850, "text": "Now, iterate over the range [1, N] using a variable i and perform the following steps:Store the current node in a variable, say node.Iterate while par[node] is not equal to -1:If par[node] is less than i, then increment cnt by 1.Update node as par[node].After completing the above steps, print the value of cnt as the value for the current node." }, { "code": null, "e": 28244, "s": 28196, "text": "Store the current node in a variable, say node." }, { "code": null, "e": 28366, "s": 28244, "text": "Iterate while par[node] is not equal to -1:If par[node] is less than i, then increment cnt by 1.Update node as par[node]." }, { "code": null, "e": 28420, "s": 28366, "text": "If par[node] is less than i, then increment cnt by 1." }, { "code": null, "e": 28446, "s": 28420, "text": "Update node as par[node]." }, { "code": null, "e": 28538, "s": 28446, "text": "After completing the above steps, print the value of cnt as the value for the current node." }, { "code": null, "e": 28589, "s": 28538, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28593, "s": 28589, "text": "C++" }, { "code": null, "e": 28598, "s": 28593, "text": "Java" }, { "code": null, "e": 28606, "s": 28598, "text": "Python3" }, { "code": null, "e": 28609, "s": 28606, "text": "C#" }, { "code": null, "e": 28620, "s": 28609, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to add an edge// between nodes u and vvoid add_edge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Function to perform the DFS Traversal// and store parent of each nodevoid dfs(vector<int>& parent, vector<int> adj[], int u, int par = -1){ // Store the immediate parent parent[u] = par; // Traverse the children of // the current node for (auto child : adj[u]) { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); }} // Function to count the number of// ancestors with values smaller// than that of the current nodevoid countSmallerAncestors( vector<int> adj[], int n){ // Stores the parent of each node vector<int> parent(int(1e5), 0); // Perform the DFS Traversal dfs(parent, adj, 1); // Traverse all the nodes for (int i = 1; i <= n; i++) { int node = i; // Store the number of ancestors // smaller than node int cnt = 0; // Loop until parent[node] != -1 while (parent[node] != -1) { // If the condition satisfies, // increment cnt by 1 if (parent[node] < i) cnt += 1; node = parent[node]; } // Print the required result // for the current node cout << cnt << \" \"; }} // Driver Codeint main(){ int N = 6; vector<int> adj[int(1e5)]; // Tree Formation add_edge(adj, 1, 5); add_edge(adj, 1, 4); add_edge(adj, 4, 6); add_edge(adj, 5, 3); add_edge(adj, 5, 2); countSmallerAncestors(adj, N); return 0;}", "e": 30399, "s": 28620, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to add an edge// between nodes u and vstatic void add_edge(ArrayList<ArrayList<Integer>> adj, int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to perform the DFS Traversal// and store parent of each nodestatic void dfs(ArrayList<Integer> parent, ArrayList<ArrayList<Integer>> adj, int u, int par){ // Store the immediate parent parent.set(u,par); // Traverse the children of // the current node for(int child : adj.get(u)) { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); }} // Function to count the number of// ancestors with values smaller// than that of the current nodestatic void countSmallerAncestors( ArrayList<ArrayList<Integer>> adj, int n){ // Stores the parent of each node ArrayList<Integer> parent = new ArrayList<Integer>(); for(int i = 0; i < (int)(1e5); i++) { parent.add(0); } // Perform the DFS Traversal dfs(parent, adj, 1, -1); // Traverse all the nodes for(int i = 1; i <= n; i++) { int node = i; // Store the number of ancestors // smaller than node int cnt = 0; // Loop until parent[node] != -1 while (parent.get(node) != -1) { // If the condition satisfies, // increment cnt by 1 if (parent.get(node) < i) cnt += 1; node = parent.get(node); } // Print the required result // for the current node System.out.print(cnt + \" \"); }} // Driver codepublic static void main (String[] args){ int N = 6; ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < (int)(1e5); i++) { adj.add(new ArrayList<Integer>()); } // Tree Formation add_edge(adj, 1, 5); add_edge(adj, 1, 4); add_edge(adj, 4, 6); add_edge(adj, 5, 3); add_edge(adj, 5, 2); countSmallerAncestors(adj, N);}} // This code is contributed by avanitrachhadiya2155", "e": 32654, "s": 30399, "text": null }, { "code": "# Python3 program for the above approach # Function to add an edge# between nodes u and vdef add_edge(u, v): global adj adj[u].append(v) adj[v].append(u) # Function to perform the DFS Traversal# and store parent of each nodedef dfs(u, par = -1): global adj, parent # Store the immediate parent parent[u] = par # Traverse the children of # the current node for child in adj[u]: # Recursively call for # function dfs for the # child node if (child != par): dfs(child, u) # Function to count the number of# ancestors with values smaller# than that of the current nodedef countSmallerAncestors(n): global parent, adj # Stores the parent of each node # Perform the DFS Traversal dfs(1) # Traverse all the nodes for i in range(1, n + 1): node = i # Store the number of ancestors # smaller than node cnt = 0 # Loop until parent[node] != -1 while (parent[node] != -1): # If the condition satisfies, # increment cnt by 1 if (parent[node] < i): cnt += 1 node = parent[node] # Print the required result # for the current node print(cnt, end = \" \") # Driver Codeif __name__ == '__main__': N = 6 adj = [[] for i in range(10**5)] parent = [0] * (10**5) # Tree Formation add_edge(1, 5) add_edge(1, 4) add_edge(4, 6) add_edge(5, 3) add_edge(5, 2) countSmallerAncestors(N) # This code is contributed by mohit kumar 29", "e": 34252, "s": 32654, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to add an edge // between nodes u and v static void add_edge(List<List<int>> adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } // Function to perform the DFS Traversal // and store parent of each node static void dfs(List<int> parent, List<List<int>> adj, int u, int par = -1) { // Store the immediate parent parent[u] = par; // Traverse the children of // the current node foreach(int child in adj[u]) { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); } } // Function to count the number of // ancestors with values smaller // than that of the current node static void countSmallerAncestors( List<List<int>> adj, int n) { // Stores the parent of each node List<int> parent = new List<int>(); for(int i = 0; i < (int)(1e5); i++) { parent.Add(0); } // Perform the DFS Traversal dfs(parent, adj, 1); // Traverse all the nodes for (int i = 1; i <= n; i++) { int node = i; // Store the number of ancestors // smaller than node int cnt = 0; // Loop until parent[node] != -1 while (parent[node] != -1) { // If the condition satisfies, // increment cnt by 1 if (parent[node] < i) cnt += 1; node = parent[node]; } // Print the required result // for the current node Console.Write(cnt + \" \"); } } static void Main() { int N = 6; List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < (int)(1e5); i++) { adj.Add(new List<int>()); } // Tree Formation add_edge(adj, 1, 5); add_edge(adj, 1, 4); add_edge(adj, 4, 6); add_edge(adj, 5, 3); add_edge(adj, 5, 2); countSmallerAncestors(adj, N); }}", "e": 36513, "s": 34252, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to add an edge// between nodes u and vfunction add_edge(adj, u, v){ adj[u].push(v); adj[v].push(u);} // Function to perform the DFS Traversal// and store parent of each nodefunction dfs(parent, adj, u, par = -1){ // Store the immediate parent parent[u] = par; // Traverse the children of // the current node adj[u].forEach(child => { // Recursively call for // function dfs for the // child node if (child != par) dfs(parent, adj, child, u); });} // Function to count the number of// ancestors with values smaller// than that of the current nodefunction countSmallerAncestors(adj, n){ // Stores the parent of each node var parent = Array(100000).fill(0); // Perform the DFS Traversal dfs(parent, adj, 1); // Traverse all the nodes for (var i = 1; i <= n; i++) { var node = i; // Store the number of ancestors // smaller than node var cnt = 0; // Loop until parent[node] != -1 while (parent[node] != -1) { // If the condition satisfies, // increment cnt by 1 if (parent[node] < i) cnt += 1; node = parent[node]; } // Print the required result // for the current node document.write( cnt + \" \"); }} // Driver Code var N = 6;var adj = Array.from(Array(100000), ()=>Array()); // Tree Formationadd_edge(adj, 1, 5);add_edge(adj, 1, 4);add_edge(adj, 4, 6);add_edge(adj, 5, 3);add_edge(adj, 5, 2);countSmallerAncestors(adj, N); </script>", "e": 38142, "s": 36513, "text": null }, { "code": null, "e": 38154, "s": 38142, "text": "0 1 1 1 1 2" }, { "code": null, "e": 38200, "s": 38156, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 38215, "s": 38200, "text": "mohit kumar 29" }, { "code": null, "e": 38233, "s": 38215, "text": "divyeshrabadiya07" }, { "code": null, "e": 38254, "s": 38233, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38260, "s": 38254, "text": "itsok" }, { "code": null, "e": 38264, "s": 38260, "text": "DFS" }, { "code": null, "e": 38277, "s": 38264, "text": "Mathematical" }, { "code": null, "e": 38287, "s": 38277, "text": "Recursion" }, { "code": null, "e": 38292, "s": 38287, "text": "Tree" }, { "code": null, "e": 38305, "s": 38292, "text": "Mathematical" }, { "code": null, "e": 38315, "s": 38305, "text": "Recursion" }, { "code": null, "e": 38319, "s": 38315, "text": "DFS" }, { "code": null, "e": 38324, "s": 38319, "text": "Tree" }, { "code": null, "e": 38422, "s": 38324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38466, "s": 38422, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 38508, "s": 38466, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 38539, "s": 38508, "text": "Modular multiplicative inverse" }, { "code": null, "e": 38610, "s": 38539, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 38635, "s": 38610, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38720, "s": 38635, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 38730, "s": 38720, "text": "Recursion" }, { "code": null, "e": 38757, "s": 38730, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 38785, "s": 38757, "text": "Backtracking | Introduction" } ]
Express.js | app.listen() Function - GeeksforGeeks
06 Nov, 2021 The app.listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node’s http.Server.listen() method.If the port number is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).The app returned by express() is in fact a JavaScript function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback). Javascript var express = require('express')var https = require('https')var http = require('http')var app = express() http.createServer(app).listen(80)https.createServer(options, app).listen(443) Syntax: app.listen([port[, host[, backlog]]][, callback]) Explanation of the syntax: (Optional) It specifies the port on which we want our app to listen.(Optional) It specifies the IP Address of the host on which we want our app to listen. You can specify the host if and only if you have already specified the port. ( since you have a closing(‘]’) bracket after ([, host[, backlog]]) as you can see in above syntax, so this means port must be specified before specifying host and backlog).(Optional) It specifies the max length of queue of pending connections. You can specify the backlog if and only if you have already specifies port and host.( since you have a closing bracket after ([, backlog]), so this means you will have to specify host before specifying backlogs)(Optional) It specifies a function that will get executed, once your app starts listening to specified port. You can specify callback alone i.e., without specifying port, host and backlogs.( since this is a separate set of arguments in opening and closing brackets([, callback]) ,this means you can specify these arguments without specifying the argument of previous opening and closing square brackets. (Optional) It specifies the port on which we want our app to listen. (Optional) It specifies the IP Address of the host on which we want our app to listen. You can specify the host if and only if you have already specified the port. ( since you have a closing(‘]’) bracket after ([, host[, backlog]]) as you can see in above syntax, so this means port must be specified before specifying host and backlog). (Optional) It specifies the max length of queue of pending connections. You can specify the backlog if and only if you have already specifies port and host.( since you have a closing bracket after ([, backlog]), so this means you will have to specify host before specifying backlogs) (Optional) It specifies a function that will get executed, once your app starts listening to specified port. You can specify callback alone i.e., without specifying port, host and backlogs.( since this is a separate set of arguments in opening and closing brackets([, callback]) ,this means you can specify these arguments without specifying the argument of previous opening and closing square brackets. Installation of express module: You can visit the link to Install express module. You can install this package by using this command. npm install express After installing express module, you can check your express version in command prompt using the command. npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Filename: index.js Javascript var express = require('express');var app = express();var PORT = 3000; app.listen(PORT, function(err){ if (err) console.log("Error in server setup") console.log("Server listening on Port", PORT);}) Steps to run the program: The project structure will look like this: Make sure you have installed express module using the following command: npm install express Run index.js file using below command: node index.js Output: Server listening on Port 3000 So this is how you can use the express app.listen() function which Binds and listens for connections on the specified host and port. cpsaket clintra Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript 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": 25659, "s": 25631, "text": "\n06 Nov, 2021" }, { "code": null, "e": 26287, "s": 25659, "text": "The app.listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node’s http.Server.listen() method.If the port number is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).The app returned by express() is in fact a JavaScript function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback)." }, { "code": null, "e": 26298, "s": 26287, "text": "Javascript" }, { "code": "var express = require('express')var https = require('https')var http = require('http')var app = express() http.createServer(app).listen(80)https.createServer(options, app).listen(443)", "e": 26482, "s": 26298, "text": null }, { "code": null, "e": 26491, "s": 26482, "text": "Syntax: " }, { "code": null, "e": 26541, "s": 26491, "text": "app.listen([port[, host[, backlog]]][, callback])" }, { "code": null, "e": 26568, "s": 26541, "text": "Explanation of the syntax:" }, { "code": null, "e": 27660, "s": 26568, "text": "(Optional) It specifies the port on which we want our app to listen.(Optional) It specifies the IP Address of the host on which we want our app to listen. You can specify the host if and only if you have already specified the port. ( since you have a closing(‘]’) bracket after ([, host[, backlog]]) as you can see in above syntax, so this means port must be specified before specifying host and backlog).(Optional) It specifies the max length of queue of pending connections. You can specify the backlog if and only if you have already specifies port and host.( since you have a closing bracket after ([, backlog]), so this means you will have to specify host before specifying backlogs)(Optional) It specifies a function that will get executed, once your app starts listening to specified port. You can specify callback alone i.e., without specifying port, host and backlogs.( since this is a separate set of arguments in opening and closing brackets([, callback]) ,this means you can specify these arguments without specifying the argument of previous opening and closing square brackets." }, { "code": null, "e": 27729, "s": 27660, "text": "(Optional) It specifies the port on which we want our app to listen." }, { "code": null, "e": 28067, "s": 27729, "text": "(Optional) It specifies the IP Address of the host on which we want our app to listen. You can specify the host if and only if you have already specified the port. ( since you have a closing(‘]’) bracket after ([, host[, backlog]]) as you can see in above syntax, so this means port must be specified before specifying host and backlog)." }, { "code": null, "e": 28351, "s": 28067, "text": "(Optional) It specifies the max length of queue of pending connections. You can specify the backlog if and only if you have already specifies port and host.( since you have a closing bracket after ([, backlog]), so this means you will have to specify host before specifying backlogs)" }, { "code": null, "e": 28755, "s": 28351, "text": "(Optional) It specifies a function that will get executed, once your app starts listening to specified port. You can specify callback alone i.e., without specifying port, host and backlogs.( since this is a separate set of arguments in opening and closing brackets([, callback]) ,this means you can specify these arguments without specifying the argument of previous opening and closing square brackets." }, { "code": null, "e": 28788, "s": 28755, "text": "Installation of express module: " }, { "code": null, "e": 28891, "s": 28788, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 28911, "s": 28891, "text": "npm install express" }, { "code": null, "e": 29017, "s": 28911, "text": "After installing express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 29037, "s": 29017, "text": "npm version express" }, { "code": null, "e": 29173, "s": 29037, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 29187, "s": 29173, "text": "node index.js" }, { "code": null, "e": 29207, "s": 29187, "text": "Filename: index.js " }, { "code": null, "e": 29218, "s": 29207, "text": "Javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.listen(PORT, function(err){ if (err) console.log(\"Error in server setup\") console.log(\"Server listening on Port\", PORT);})", "e": 29421, "s": 29218, "text": null }, { "code": null, "e": 29448, "s": 29421, "text": "Steps to run the program: " }, { "code": null, "e": 29492, "s": 29448, "text": "The project structure will look like this: " }, { "code": null, "e": 29566, "s": 29492, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 29586, "s": 29566, "text": "npm install express" }, { "code": null, "e": 29626, "s": 29586, "text": "Run index.js file using below command: " }, { "code": null, "e": 29640, "s": 29626, "text": "node index.js" }, { "code": null, "e": 29650, "s": 29640, "text": "Output: " }, { "code": null, "e": 29680, "s": 29650, "text": "Server listening on Port 3000" }, { "code": null, "e": 29814, "s": 29680, "text": "So this is how you can use the express app.listen() function which Binds and listens for connections on the specified host and port. " }, { "code": null, "e": 29822, "s": 29814, "text": "cpsaket" }, { "code": null, "e": 29830, "s": 29822, "text": "clintra" }, { "code": null, "e": 29841, "s": 29830, "text": "Express.js" }, { "code": null, "e": 29849, "s": 29841, "text": "Node.js" }, { "code": null, "e": 29866, "s": 29849, "text": "Web Technologies" }, { "code": null, "e": 29964, "s": 29866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29994, "s": 29964, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 30023, "s": 29994, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 30080, "s": 30023, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 30134, "s": 30080, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 30171, "s": 30134, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 30211, "s": 30171, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30256, "s": 30211, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30299, "s": 30256, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30349, "s": 30299, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Use If Statement in Excel VBA? - GeeksforGeeks
19 Jul, 2021 VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to use how to use the If statement in Excel VBA. In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window. Now select Customize the Ribbon from the pop-down menu. In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement. Developer -> Visual Basic -> Tools -> Macros Now create a Macro and give any suitable name. This will open the Editor window where can write the code. The syntax is : If condition/expression Then Code Block for True value Flow Diagram : Example: Consider a company that wants to hire employees for a certain role. The company kept eligibility criteria as the age of the person. The age of the candidate who can apply for this interview must be less than 27 years. Sub Allocate_Employee() 'Declaring and initializing the variable age Dim age As Integer age = 30 If age >= 27 Then MsgBox "You are not eligible for this post." End If End Sub Output: Since, the age is 30, the IF condition becomes TRUE and the code block inside IF statement executes. Some helpful links to get more insights about Macros, VBA in Excel : Record Macros in Excel.How to Create a Macro in Excel? Record Macros in Excel. How to Create a Macro in Excel? Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Extract the Last Word From a Cell in Excel? How to Calculate Deciles in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n19 Jul, 2021" }, { "code": null, "e": 26499, "s": 26289, "text": "VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend." }, { "code": null, "e": 26578, "s": 26499, "text": "In this article, we are going to use how to use the If statement in Excel VBA." }, { "code": null, "e": 26685, "s": 26578, "text": "In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. " }, { "code": null, "e": 26749, "s": 26685, "text": "The Developer Tab can be enabled easily by a two-step process :" }, { "code": null, "e": 26821, "s": 26749, "text": "Right-click on any of the existing tabs at the top of the Excel window." }, { "code": null, "e": 26877, "s": 26821, "text": "Now select Customize the Ribbon from the pop-down menu." }, { "code": null, "e": 26957, "s": 26877, "text": "In the Excel Options Box, check the box Developer to enable it and click on OK." }, { "code": null, "e": 26992, "s": 26957, "text": "Now, the Developer Tab is visible." }, { "code": null, "e": 27126, "s": 26992, "text": "Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement." }, { "code": null, "e": 27172, "s": 27126, "text": "Developer -> Visual Basic -> Tools -> Macros" }, { "code": null, "e": 27219, "s": 27172, "text": "Now create a Macro and give any suitable name." }, { "code": null, "e": 27278, "s": 27219, "text": "This will open the Editor window where can write the code." }, { "code": null, "e": 27294, "s": 27278, "text": "The syntax is :" }, { "code": null, "e": 27349, "s": 27294, "text": "If condition/expression Then\nCode Block for True value" }, { "code": null, "e": 27364, "s": 27349, "text": "Flow Diagram :" }, { "code": null, "e": 27591, "s": 27364, "text": "Example: Consider a company that wants to hire employees for a certain role. The company kept eligibility criteria as the age of the person. The age of the candidate who can apply for this interview must be less than 27 years." }, { "code": null, "e": 27767, "s": 27591, "text": "Sub Allocate_Employee()\n'Declaring and initializing the variable age\nDim age As Integer\nage = 30\nIf age >= 27 Then\n MsgBox \"You are not eligible for this post.\"\nEnd If\nEnd Sub" }, { "code": null, "e": 27776, "s": 27767, "text": "Output: " }, { "code": null, "e": 27877, "s": 27776, "text": "Since, the age is 30, the IF condition becomes TRUE and the code block inside IF statement executes." }, { "code": null, "e": 27946, "s": 27877, "text": "Some helpful links to get more insights about Macros, VBA in Excel :" }, { "code": null, "e": 28001, "s": 27946, "text": "Record Macros in Excel.How to Create a Macro in Excel?" }, { "code": null, "e": 28025, "s": 28001, "text": "Record Macros in Excel." }, { "code": null, "e": 28057, "s": 28025, "text": "How to Create a Macro in Excel?" }, { "code": null, "e": 28064, "s": 28057, "text": "Picked" }, { "code": null, "e": 28070, "s": 28064, "text": "Excel" }, { "code": null, "e": 28168, "s": 28070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28196, "s": 28168, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 28251, "s": 28196, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 28292, "s": 28251, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 28342, "s": 28292, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 28358, "s": 28342, "text": "Macros in Excel" }, { "code": null, "e": 28392, "s": 28358, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 28450, "s": 28392, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 28506, "s": 28450, "text": "How to Remove Duplicates From Array Using VBA in Excel?" }, { "code": null, "e": 28557, "s": 28506, "text": "How to Extract the Last Word From a Cell in Excel?" } ]
How to use if, else & elif in Python Lambda Functions - GeeksforGeeks
21 Feb, 2022 Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else & elif in Lambda Functions. The lambda function will return a value for every validated input. Here, if block will be returned when the condition is true, and else block will be returned when the condition is false. Syntax: lambda <arguments> : <statement1> if <condition> else <statement2> Here, the lambda function will return statement1 when if the condition is true and return statement2 when if the condition is false. Example: Here, We are going to find whether a number is even or odd. when we pass number 12 to lambda function it will execute statement 1 and statement2 for 11. Python3 # Use if-else in Lambda Functions # check if number is even or oddresult = lambda x : f"{x} is even" if x %2==0 else f"{x} is odd" # print for numbersprint(result(12))print(result(11)) 12 is even 11 is odd We can also use nested if, if-else in lambda function. Here we will create a lambda function to check if two number is equal or greater or lesser. We will implement this using the lambda function. Syntax: lambda <args> : <statement1> if <condition > ( <statement2> if <condition> else <statement3>) Here, statement1 will be returned when if the condition is true, statement2 will be returned when elif true, and statement3 will be returned when else is executed. Example: Here, we passed 2 numbers to the lambda function. and check the relation between them. That is if one number is greater or equal or lesser than another number Python3 # Use if-else in Lambda Functions # check if two numbe is equal or greater or lesserresult = lambda x,y : f"{x} is smaller than {y}" \if x < y else (f"{x} is greater than {y}" if x > y \ else f"{x} is equal to {y}") # print for numbersprint(result(12, 11))print(result(12, 12))print(result(12, 13)) 12 is greater than 11 12 is equal to 12 12 is smaller than 13 sumitgumber28 Picked python-lambda Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n21 Feb, 2022" }, { "code": null, "e": 25794, "s": 25537, "text": "Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else & elif in Lambda Functions." }, { "code": null, "e": 25983, "s": 25794, "text": "The lambda function will return a value for every validated input. Here, if block will be returned when the condition is true, and else block will be returned when the condition is false. " }, { "code": null, "e": 25991, "s": 25983, "text": "Syntax:" }, { "code": null, "e": 26058, "s": 25991, "text": "lambda <arguments> : <statement1> if <condition> else <statement2>" }, { "code": null, "e": 26191, "s": 26058, "text": "Here, the lambda function will return statement1 when if the condition is true and return statement2 when if the condition is false." }, { "code": null, "e": 26200, "s": 26191, "text": "Example:" }, { "code": null, "e": 26354, "s": 26200, "text": "Here, We are going to find whether a number is even or odd. when we pass number 12 to lambda function it will execute statement 1 and statement2 for 11. " }, { "code": null, "e": 26362, "s": 26354, "text": "Python3" }, { "code": "# Use if-else in Lambda Functions # check if number is even or oddresult = lambda x : f\"{x} is even\" if x %2==0 else f\"{x} is odd\" # print for numbersprint(result(12))print(result(11))", "e": 26547, "s": 26362, "text": null }, { "code": null, "e": 26568, "s": 26547, "text": "12 is even\n11 is odd" }, { "code": null, "e": 26765, "s": 26568, "text": "We can also use nested if, if-else in lambda function. Here we will create a lambda function to check if two number is equal or greater or lesser. We will implement this using the lambda function." }, { "code": null, "e": 26773, "s": 26765, "text": "Syntax:" }, { "code": null, "e": 26867, "s": 26773, "text": "lambda <args> : <statement1> if <condition > ( <statement2> if <condition> else <statement3>)" }, { "code": null, "e": 27032, "s": 26867, "text": "Here, statement1 will be returned when if the condition is true, statement2 will be returned when elif true, and statement3 will be returned when else is executed. " }, { "code": null, "e": 27041, "s": 27032, "text": "Example:" }, { "code": null, "e": 27200, "s": 27041, "text": "Here, we passed 2 numbers to the lambda function. and check the relation between them. That is if one number is greater or equal or lesser than another number" }, { "code": null, "e": 27208, "s": 27200, "text": "Python3" }, { "code": "# Use if-else in Lambda Functions # check if two numbe is equal or greater or lesserresult = lambda x,y : f\"{x} is smaller than {y}\" \\if x < y else (f\"{x} is greater than {y}\" if x > y \\ else f\"{x} is equal to {y}\") # print for numbersprint(result(12, 11))print(result(12, 12))print(result(12, 13))", "e": 27522, "s": 27208, "text": null }, { "code": null, "e": 27587, "s": 27525, "text": "12 is greater than 11\n12 is equal to 12\n12 is smaller than 13" }, { "code": null, "e": 27603, "s": 27589, "text": "sumitgumber28" }, { "code": null, "e": 27610, "s": 27603, "text": "Picked" }, { "code": null, "e": 27624, "s": 27610, "text": "python-lambda" }, { "code": null, "e": 27631, "s": 27624, "text": "Python" }, { "code": null, "e": 27729, "s": 27631, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27761, "s": 27729, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27803, "s": 27761, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27845, "s": 27803, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27872, "s": 27845, "text": "Python Classes and Objects" }, { "code": null, "e": 27928, "s": 27872, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27950, "s": 27928, "text": "Defaultdict in Python" }, { "code": null, "e": 27989, "s": 27950, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28020, "s": 27989, "text": "Python | os.path.join() method" }, { "code": null, "e": 28049, "s": 28020, "text": "Create a directory in Python" } ]
MoviePy – Applying Resize effect on Video Clip - GeeksforGeeks
01 Aug, 2020 In this article we will see how we can apply resize effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. We can resize the video with the help of resize method to resize the video clip, resize filter is the type of filter applied on it. In order to do this we will use fx method with the VideoFileClip object Syntax : clip.fx( vfx.resize, width= 280) Argument : It takes vfx object and width or height as optional argument Return : It returns VideoFileClip object Below is the implementation # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting only first 5 secondsclip = clip.subclip(0, 5) # applying resize filterfinal = clip.fx( vfx.resize, width = 280) # showing final clipfinal.ipython_display() Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Another example # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip from itclip = clip.subclip(0, 5) # applying resize filterfinal = clip.fx( vfx.resize, width = 280) # showing final clipfinal.ipython_display() Output : Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 Convert integer to string in Python
[ { "code": null, "e": 25607, "s": 25579, "text": "\n01 Aug, 2020" }, { "code": null, "e": 25939, "s": 25607, "text": "In this article we will see how we can apply resize effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. We can resize the video with the help of resize method to resize the video clip, resize filter is the type of filter applied on it." }, { "code": null, "e": 26011, "s": 25939, "text": "In order to do this we will use fx method with the VideoFileClip object" }, { "code": null, "e": 26053, "s": 26011, "text": "Syntax : clip.fx( vfx.resize, width= 280)" }, { "code": null, "e": 26125, "s": 26053, "text": "Argument : It takes vfx object and width or height as optional argument" }, { "code": null, "e": 26166, "s": 26125, "text": "Return : It returns VideoFileClip object" }, { "code": null, "e": 26194, "s": 26166, "text": "Below is the implementation" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip(\"dsa_geek.webm\") # getting only first 5 secondsclip = clip.subclip(0, 5) # applying resize filterfinal = clip.fx( vfx.resize, width = 280) # showing final clipfinal.ipython_display()", "e": 26515, "s": 26194, "text": null }, { "code": null, "e": 26524, "s": 26515, "text": "Output :" }, { "code": null, "e": 26774, "s": 26524, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 26790, "s": 26774, "text": "Another example" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclip from itclip = clip.subclip(0, 5) # applying resize filterfinal = clip.fx( vfx.resize, width = 280) # showing final clipfinal.ipython_display()", "e": 27085, "s": 26790, "text": null }, { "code": null, "e": 27094, "s": 27085, "text": "Output :" }, { "code": null, "e": 27537, "s": 27094, "text": "Moviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n\n" }, { "code": null, "e": 27552, "s": 27537, "text": "Python-MoviePy" }, { "code": null, "e": 27559, "s": 27552, "text": "Python" }, { "code": null, "e": 27657, "s": 27559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27675, "s": 27657, "text": "Python Dictionary" }, { "code": null, "e": 27707, "s": 27675, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27729, "s": 27707, "text": "Enumerate() in Python" }, { "code": null, "e": 27771, "s": 27729, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27801, "s": 27771, "text": "Iterate over a list in Python" }, { "code": null, "e": 27827, "s": 27801, "text": "Python String | replace()" }, { "code": null, "e": 27856, "s": 27827, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27900, "s": 27856, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27937, "s": 27900, "text": "Create a Pandas DataFrame from Lists" } ]
Scala - String Methods with Examples - GeeksforGeeks
03 Jul, 2020 In Scala, as in Java, a string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In the rest of this section, we discuss the important methods of java.lang.String class. char charAt(int index): This method is used to returns the character at the given index.Example:// Scala program of charAt() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Getting a character at the given index // Using charAt() methods val result = "GeeksforGeeks".charAt(3) println("Result : " + result) }}Output:Result : kint compareTo(Object o): This method is used for the comparison of one string to another object.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val val1 = "Hello" val val2 = "GeeksforGeeks" val result = val1.compareTo(val2) println("Result : " + result) }}Output:Result : 1int compareTo(String anotherString): This method is used to compares two strings lexicographically. If two strings match then it returns 0, else it returns the difference between the two.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val result = "Geeks".compareTo("Geeks") println("Result : " + result) }}Output:Result : 0int compareToIgnoreCase(String str): This method is used for comparing two strings lexicographically. It ignoring the case differences.Example:// Scala program of compareToIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using compareToIgnoreCase() methods val result = "Geeks".compareToIgnoreCase("geeks") println("Result : " + result) }}Output:Result : 0 String concat(String str): This method is used for concatenation of the two strings. It join two strings together and made a single string.Example:// Scala program of concat() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Concatenate two strings // Using concat() methods val result = "Geeks".concat("forGeeks") println("Result : " + result) }}Output:Result : GeeksforGeeksBoolean contentEquals(StringBuffer sb): This method is used to compares a string to a StringBuffer’s contents. If they are equal then it returns true otherwise it will return false.Example:// Scala program of contentEquals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using contentEquals() methods val a = new StringBuffer("Geeks") val result = "Geeks".contentEquals(a) println("Result : " + result) }}Output:Result : trueBoolean endsWith(String suffix): This method is used to return true if the string ends with the suffix specified. Otherwise, it returns false.Example:// Scala program of endsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using endsWith() methods val result = "Geeks".endsWith("s") println("Result : " + result) }}Output:Result : trueBoolean equals(Object anObject): This method is used to returns true if the string and the object are equal. Otherwise, it returns false.Example:// Scala program of equals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equals() methods val result = "Geeks".equals("Geeks") println("Result : " + result) }}Output:Result : trueBoolean equalsIgnoreCase(String anotherString): This methods works like equals() but it ignores the case differences.Example:// Scala program of equalsIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equalsIgnoreCase() methods val result = "Geeks".equalsIgnoreCase("gEeks") println("Result : " + result) }}Output:Result : true byte getBytes(): This method helps in encoding a string into a sequence of bytes and it also helps in storing it into a new byte array.Example:// Scala program of getBytes() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using getBytes() methods val result = "ABCcba".getBytes() println("Result : " + result) }}Output:Result : [B@506e1b77int indexOf(int ch): This method helps in returning the index of the first occurrence of the character in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeks".indexOf('e') println("Result : " + result) }}Output:Result : 1int indexOf(int ch, int fromIndex): This method works similar to that indexOf. The only difference is that it begins searching at the specified index.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeksforgeeks".indexOf('g',5) println("Result : " + result) }}Output:Result : 8int indexOf(String str): This method is used to return the index of the first occurrence of the substring we specify, in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeksforgeeeks".indexOf("ks") println("Result : " + result) }}Output:Result : 3String intern(): This method is used to return the canonical representation for the string object.Example:// Scala program of intern() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using intern() methods val result = "Geeks,\n\tForGeeks".intern() println("Result : " + result) }}Output:Result : Geeks, ForGeeks int lastIndexOf(int ch): This method is used to return the index of the last occurrence of the character we specify.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = "Geeks".lastIndexOf('e') println("Result : " + result) }}Output:Result : 2int lastIndexOf(String str): This method is used to return the index of the last occurrence of the substring we specify, in the string.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = "Geeksforgeeks".lastIndexOf("ek") println("Result : " + result) }}Output:Result : 10int length(): This method is used to return the length of a string.Example:// Scala program of length() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using length() methods val result = "Geeks".length() println("Result : " + result) }}Output:Result : 5String replaceAll(String regex, String replacement): This method is used to replace the substring with the replacement string provided by user.Example:// Scala program of replaceAll() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceAll() methods val result = "potdotnothotokayslot".replaceAll(".ot","**") println("Result : " + result) }}Output:Result : ********okays**String replaceFirst(String regex, String replacement): If in the above example, we want to replace only the first such occurrence.Example:// Scala program of replaceFirst() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceFirst() methods val result = "potdotnothotokayslot".replaceFirst(".ot","**") println("Result : " + result) }}Output:Result : **dotnothotokayslotString[] split(String regex): This method is used to split the string around matches of the regular expression we specify. It returns a String array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = "PfsoQmsoRcsoGfGkso".split(".so") for ( a <-result ) { // Displays output println(a) } } } Output:P Q R GfG Boolean startsWith(String prefix, int toffset): This method is used to return true if the string starts with the given index. Otherwise, it will return false.Example:// Scala program of startsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = "Geeks".startsWith("ee", 1) println("Result : " + result) }}Output:Result : trueCharSequence subSequence(int beginIndex, int endIndex): This method is used to return the sub string from the given string. Here starting index and ending index of a sub string is given.Example:// Scala program of subSequence() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using subSequence() methods val result = "Geeks".subSequence(1,4) println("Result : " + result) }}Output:Result : eekString substring(int beginIndex): This method is used to return the characters of the string beginning from the given index till the end of the string.Example:// Scala program of substring() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = "Geeks".substring(3) println("Result : " + result) }}Output:Result : kschar[] toCharArray(): This method is used to convert the string into a CharArray.Example:// Scala program of toCharArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toCharArray method val result = "GeeksforGeeks".toCharArray() for(m1<-result) { // Displays output println(m1) } } } Output:G e e k s f o r G e e k sString toLowerCase(): This method is used to convert all the characters into lower case.Example:// Scala program of toLowerCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toLowerCase() methods val result = "GEekS".toLowerCase() println("Result : " + result) }}Output:Result : geeksString toString(): This method is used to return a String object itself.Example:// Scala program of toString() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toString() methods val result = "9".toString() println("Result : " + result) }}Output:Result : 9String toUpperCase(): This method is used to convert the string into upper case.Example:// Scala program of toUpperCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toUpperCase() methods val result = "Geeks".toUpperCase() println("Result : " + result) }}Output:Result : GEEKSString trim(): This method is used to remove the leading and trailing whitespaces from the string.Example:// Scala program of trim() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using trim() methods val result = " Geeks ".trim() println("Result : " + result) }}Output:Result : GeeksString substring(int beginIndex, int endIndex): This method is used to return the part of the string beginning at beginIndex and ending at endIndex.Example:// Scala program of substring() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = "Piyush".substring(1, 4) println("Result : " + result) }}Output:Result : iyuBoolean startsWith(String prefix): This method is used to return true if the string starts with the given prefix. Otherwise, returns false.Example:// Scala program of startsWith() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = "Ayush".startsWith(" Ay") println("Result : " + result) }}Output:String[] split(String regex, int limit): This method is like split, the only change is that we can limit the number of members for the array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = "NidhifsoSinghmsoAcso".split(".so", 2) for ( m1 <-result ) { // Displays output println(m1) } } } Output:Nidhi SinghmsoAcsoBoolean matches(String regex): This method is used to return true, if string matches the regular expression specified.Example:// Scala program of matches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using matches() methods val result = "Ayushi".matches(".i.*") println("Result : " + result) }}Output:Result : falseBoolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len): This method is used to return true if two strings regions are equal.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = "Ayushi".regionMatches(true, 0, "Ayush", 0, 3) println("Result : " + result) }}Output:Result : trueString replace(char oldChar, char newChar): This method is used to replace the oldChar occurences with the newChar ones.Example:// Scala program of replace() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replace() methods val result = "sanjay sharma".replace('s','$') println("Result : " + result) }}Output:Result : $anjay $harmaint hashCode(): This method is used to return hash code of a string.Example:// Scala program of hashCode() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using hashCode() methods val result = "Ayushi".hashCode() println("Result : " + result) }}Output:Result : 1976240247Boolean regionMatches(int toffset, String other, int offset, int len): This method does not have any ignore case, else it is same as above method.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = "Ayushi".regionMatches(true, 0, "Ayushi", 0, 4) println("Result : " + result) }}Output:Result : true char charAt(int index): This method is used to returns the character at the given index.Example:// Scala program of charAt() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Getting a character at the given index // Using charAt() methods val result = "GeeksforGeeks".charAt(3) println("Result : " + result) }}Output:Result : k Example: // Scala program of charAt() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Getting a character at the given index // Using charAt() methods val result = "GeeksforGeeks".charAt(3) println("Result : " + result) }} Output: Result : k int compareTo(Object o): This method is used for the comparison of one string to another object.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val val1 = "Hello" val val2 = "GeeksforGeeks" val result = val1.compareTo(val2) println("Result : " + result) }}Output:Result : 1 // Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val val1 = "Hello" val val2 = "GeeksforGeeks" val result = val1.compareTo(val2) println("Result : " + result) }} Output: Result : 1 int compareTo(String anotherString): This method is used to compares two strings lexicographically. If two strings match then it returns 0, else it returns the difference between the two.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val result = "Geeks".compareTo("Geeks") println("Result : " + result) }}Output:Result : 0 // Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val result = "Geeks".compareTo("Geeks") println("Result : " + result) }} Output: Result : 0 int compareToIgnoreCase(String str): This method is used for comparing two strings lexicographically. It ignoring the case differences.Example:// Scala program of compareToIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using compareToIgnoreCase() methods val result = "Geeks".compareToIgnoreCase("geeks") println("Result : " + result) }}Output:Result : 0 // Scala program of compareToIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using compareToIgnoreCase() methods val result = "Geeks".compareToIgnoreCase("geeks") println("Result : " + result) }} Output: Result : 0 String concat(String str): This method is used for concatenation of the two strings. It join two strings together and made a single string.Example:// Scala program of concat() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Concatenate two strings // Using concat() methods val result = "Geeks".concat("forGeeks") println("Result : " + result) }}Output:Result : GeeksforGeeks // Scala program of concat() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Concatenate two strings // Using concat() methods val result = "Geeks".concat("forGeeks") println("Result : " + result) }} Output: Result : GeeksforGeeks Boolean contentEquals(StringBuffer sb): This method is used to compares a string to a StringBuffer’s contents. If they are equal then it returns true otherwise it will return false.Example:// Scala program of contentEquals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using contentEquals() methods val a = new StringBuffer("Geeks") val result = "Geeks".contentEquals(a) println("Result : " + result) }}Output:Result : true // Scala program of contentEquals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using contentEquals() methods val a = new StringBuffer("Geeks") val result = "Geeks".contentEquals(a) println("Result : " + result) }} Output: Result : true Boolean endsWith(String suffix): This method is used to return true if the string ends with the suffix specified. Otherwise, it returns false.Example:// Scala program of endsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using endsWith() methods val result = "Geeks".endsWith("s") println("Result : " + result) }}Output:Result : true // Scala program of endsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using endsWith() methods val result = "Geeks".endsWith("s") println("Result : " + result) }} Output: Result : true Boolean equals(Object anObject): This method is used to returns true if the string and the object are equal. Otherwise, it returns false.Example:// Scala program of equals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equals() methods val result = "Geeks".equals("Geeks") println("Result : " + result) }}Output:Result : true // Scala program of equals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equals() methods val result = "Geeks".equals("Geeks") println("Result : " + result) }} Output: Result : true Boolean equalsIgnoreCase(String anotherString): This methods works like equals() but it ignores the case differences.Example:// Scala program of equalsIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equalsIgnoreCase() methods val result = "Geeks".equalsIgnoreCase("gEeks") println("Result : " + result) }}Output:Result : true // Scala program of equalsIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equalsIgnoreCase() methods val result = "Geeks".equalsIgnoreCase("gEeks") println("Result : " + result) }} Output: Result : true byte getBytes(): This method helps in encoding a string into a sequence of bytes and it also helps in storing it into a new byte array.Example:// Scala program of getBytes() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using getBytes() methods val result = "ABCcba".getBytes() println("Result : " + result) }}Output:Result : [B@506e1b77 // Scala program of getBytes() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using getBytes() methods val result = "ABCcba".getBytes() println("Result : " + result) }} Output: Result : [B@506e1b77 int indexOf(int ch): This method helps in returning the index of the first occurrence of the character in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeks".indexOf('e') println("Result : " + result) }}Output:Result : 1 // Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeks".indexOf('e') println("Result : " + result) }} Output: Result : 1 int indexOf(int ch, int fromIndex): This method works similar to that indexOf. The only difference is that it begins searching at the specified index.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeksforgeeks".indexOf('g',5) println("Result : " + result) }}Output:Result : 8 // Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeksforgeeks".indexOf('g',5) println("Result : " + result) }} Output: Result : 8 int indexOf(String str): This method is used to return the index of the first occurrence of the substring we specify, in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeksforgeeeks".indexOf("ks") println("Result : " + result) }}Output:Result : 3 // Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = "Geeksforgeeeks".indexOf("ks") println("Result : " + result) }} Output: Result : 3 String intern(): This method is used to return the canonical representation for the string object.Example:// Scala program of intern() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using intern() methods val result = "Geeks,\n\tForGeeks".intern() println("Result : " + result) }}Output:Result : Geeks, ForGeeks // Scala program of intern() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using intern() methods val result = "Geeks,\n\tForGeeks".intern() println("Result : " + result) }} Output: Result : Geeks, ForGeeks int lastIndexOf(int ch): This method is used to return the index of the last occurrence of the character we specify.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = "Geeks".lastIndexOf('e') println("Result : " + result) }}Output:Result : 2 // Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = "Geeks".lastIndexOf('e') println("Result : " + result) }} Output: Result : 2 int lastIndexOf(String str): This method is used to return the index of the last occurrence of the substring we specify, in the string.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = "Geeksforgeeks".lastIndexOf("ek") println("Result : " + result) }}Output:Result : 10 // Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = "Geeksforgeeks".lastIndexOf("ek") println("Result : " + result) }} Output: Result : 10 int length(): This method is used to return the length of a string.Example:// Scala program of length() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using length() methods val result = "Geeks".length() println("Result : " + result) }}Output:Result : 5 // Scala program of length() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using length() methods val result = "Geeks".length() println("Result : " + result) }} Output: Result : 5 String replaceAll(String regex, String replacement): This method is used to replace the substring with the replacement string provided by user.Example:// Scala program of replaceAll() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceAll() methods val result = "potdotnothotokayslot".replaceAll(".ot","**") println("Result : " + result) }}Output:Result : ********okays** // Scala program of replaceAll() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceAll() methods val result = "potdotnothotokayslot".replaceAll(".ot","**") println("Result : " + result) }} Output: Result : ********okays** String replaceFirst(String regex, String replacement): If in the above example, we want to replace only the first such occurrence.Example:// Scala program of replaceFirst() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceFirst() methods val result = "potdotnothotokayslot".replaceFirst(".ot","**") println("Result : " + result) }}Output:Result : **dotnothotokayslot // Scala program of replaceFirst() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceFirst() methods val result = "potdotnothotokayslot".replaceFirst(".ot","**") println("Result : " + result) }} Output: Result : **dotnothotokayslot String[] split(String regex): This method is used to split the string around matches of the regular expression we specify. It returns a String array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = "PfsoQmsoRcsoGfGkso".split(".so") for ( a <-result ) { // Displays output println(a) } } } Output:P Q R GfG // Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = "PfsoQmsoRcsoGfGkso".split(".so") for ( a <-result ) { // Displays output println(a) } } } Output: P Q R GfG Boolean startsWith(String prefix, int toffset): This method is used to return true if the string starts with the given index. Otherwise, it will return false.Example:// Scala program of startsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = "Geeks".startsWith("ee", 1) println("Result : " + result) }}Output:Result : true // Scala program of startsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = "Geeks".startsWith("ee", 1) println("Result : " + result) }} Output: Result : true CharSequence subSequence(int beginIndex, int endIndex): This method is used to return the sub string from the given string. Here starting index and ending index of a sub string is given.Example:// Scala program of subSequence() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using subSequence() methods val result = "Geeks".subSequence(1,4) println("Result : " + result) }}Output:Result : eek // Scala program of subSequence() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using subSequence() methods val result = "Geeks".subSequence(1,4) println("Result : " + result) }} Output: Result : eek String substring(int beginIndex): This method is used to return the characters of the string beginning from the given index till the end of the string.Example:// Scala program of substring() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = "Geeks".substring(3) println("Result : " + result) }}Output:Result : ks // Scala program of substring() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = "Geeks".substring(3) println("Result : " + result) }} Output: Result : ks char[] toCharArray(): This method is used to convert the string into a CharArray.Example:// Scala program of toCharArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toCharArray method val result = "GeeksforGeeks".toCharArray() for(m1<-result) { // Displays output println(m1) } } } Output:G e e k s f o r G e e k s // Scala program of toCharArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toCharArray method val result = "GeeksforGeeks".toCharArray() for(m1<-result) { // Displays output println(m1) } } } Output: G e e k s f o r G e e k s String toLowerCase(): This method is used to convert all the characters into lower case.Example:// Scala program of toLowerCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toLowerCase() methods val result = "GEekS".toLowerCase() println("Result : " + result) }}Output:Result : geeks // Scala program of toLowerCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toLowerCase() methods val result = "GEekS".toLowerCase() println("Result : " + result) }} Output: Result : geeks String toString(): This method is used to return a String object itself.Example:// Scala program of toString() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toString() methods val result = "9".toString() println("Result : " + result) }}Output:Result : 9 // Scala program of toString() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toString() methods val result = "9".toString() println("Result : " + result) }} Output: Result : 9 String toUpperCase(): This method is used to convert the string into upper case.Example:// Scala program of toUpperCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toUpperCase() methods val result = "Geeks".toUpperCase() println("Result : " + result) }}Output:Result : GEEKS // Scala program of toUpperCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toUpperCase() methods val result = "Geeks".toUpperCase() println("Result : " + result) }} Output: Result : GEEKS String trim(): This method is used to remove the leading and trailing whitespaces from the string.Example:// Scala program of trim() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using trim() methods val result = " Geeks ".trim() println("Result : " + result) }}Output:Result : Geeks // Scala program of trim() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using trim() methods val result = " Geeks ".trim() println("Result : " + result) }} Output: Result : Geeks String substring(int beginIndex, int endIndex): This method is used to return the part of the string beginning at beginIndex and ending at endIndex.Example:// Scala program of substring() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = "Piyush".substring(1, 4) println("Result : " + result) }}Output:Result : iyu // Scala program of substring() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = "Piyush".substring(1, 4) println("Result : " + result) }} Output: Result : iyu Boolean startsWith(String prefix): This method is used to return true if the string starts with the given prefix. Otherwise, returns false.Example:// Scala program of startsWith() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = "Ayush".startsWith(" Ay") println("Result : " + result) }}Output: // Scala program of startsWith() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = "Ayush".startsWith(" Ay") println("Result : " + result) }} Output: String[] split(String regex, int limit): This method is like split, the only change is that we can limit the number of members for the array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = "NidhifsoSinghmsoAcso".split(".so", 2) for ( m1 <-result ) { // Displays output println(m1) } } } Output:Nidhi SinghmsoAcso // Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = "NidhifsoSinghmsoAcso".split(".so", 2) for ( m1 <-result ) { // Displays output println(m1) } } } Output: Nidhi SinghmsoAcso Boolean matches(String regex): This method is used to return true, if string matches the regular expression specified.Example:// Scala program of matches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using matches() methods val result = "Ayushi".matches(".i.*") println("Result : " + result) }}Output:Result : false // Scala program of matches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using matches() methods val result = "Ayushi".matches(".i.*") println("Result : " + result) }} Output: Result : false Boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len): This method is used to return true if two strings regions are equal.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = "Ayushi".regionMatches(true, 0, "Ayush", 0, 3) println("Result : " + result) }}Output:Result : true // Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = "Ayushi".regionMatches(true, 0, "Ayush", 0, 3) println("Result : " + result) }} Output: Result : true String replace(char oldChar, char newChar): This method is used to replace the oldChar occurences with the newChar ones.Example:// Scala program of replace() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replace() methods val result = "sanjay sharma".replace('s','$') println("Result : " + result) }}Output:Result : $anjay $harma // Scala program of replace() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replace() methods val result = "sanjay sharma".replace('s','$') println("Result : " + result) }} Output: Result : $anjay $harma int hashCode(): This method is used to return hash code of a string.Example:// Scala program of hashCode() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using hashCode() methods val result = "Ayushi".hashCode() println("Result : " + result) }}Output:Result : 1976240247 // Scala program of hashCode() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using hashCode() methods val result = "Ayushi".hashCode() println("Result : " + result) }} Output: Result : 1976240247 Boolean regionMatches(int toffset, String other, int offset, int len): This method does not have any ignore case, else it is same as above method.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = "Ayushi".regionMatches(true, 0, "Ayushi", 0, 4) println("Result : " + result) }}Output:Result : true // Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = "Ayushi".regionMatches(true, 0, "Ayushi", 0, 4) println("Result : " + result) }} Output: Result : true Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala List filter() method with example Type Casting in Scala Class and Object in Scala Scala Map Scala Lists Inheritance in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala List contains() method with example Operators in Scala
[ { "code": null, "e": 25225, "s": 25197, "text": "\n03 Jul, 2020" }, { "code": null, "e": 25475, "s": 25225, "text": "In Scala, as in Java, a string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In the rest of this section, we discuss the important methods of java.lang.String class." }, { "code": null, "e": 41373, "s": 25475, "text": "char charAt(int index): This method is used to returns the character at the given index.Example:// Scala program of charAt() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Getting a character at the given index // Using charAt() methods val result = \"GeeksforGeeks\".charAt(3) println(\"Result : \" + result) }}Output:Result : kint compareTo(Object o): This method is used for the comparison of one string to another object.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val val1 = \"Hello\" val val2 = \"GeeksforGeeks\" val result = val1.compareTo(val2) println(\"Result : \" + result) }}Output:Result : 1int compareTo(String anotherString): This method is used to compares two strings lexicographically. If two strings match then it returns 0, else it returns the difference between the two.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val result = \"Geeks\".compareTo(\"Geeks\") println(\"Result : \" + result) }}Output:Result : 0int compareToIgnoreCase(String str): This method is used for comparing two strings lexicographically. It ignoring the case differences.Example:// Scala program of compareToIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using compareToIgnoreCase() methods val result = \"Geeks\".compareToIgnoreCase(\"geeks\") println(\"Result : \" + result) }}Output:Result : 0\nString concat(String str): This method is used for concatenation of the two strings. It join two strings together and made a single string.Example:// Scala program of concat() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Concatenate two strings // Using concat() methods val result = \"Geeks\".concat(\"forGeeks\") println(\"Result : \" + result) }}Output:Result : GeeksforGeeksBoolean contentEquals(StringBuffer sb): This method is used to compares a string to a StringBuffer’s contents. If they are equal then it returns true otherwise it will return false.Example:// Scala program of contentEquals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using contentEquals() methods val a = new StringBuffer(\"Geeks\") val result = \"Geeks\".contentEquals(a) println(\"Result : \" + result) }}Output:Result : trueBoolean endsWith(String suffix): This method is used to return true if the string ends with the suffix specified. Otherwise, it returns false.Example:// Scala program of endsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using endsWith() methods val result = \"Geeks\".endsWith(\"s\") println(\"Result : \" + result) }}Output:Result : trueBoolean equals(Object anObject): This method is used to returns true if the string and the object are equal. Otherwise, it returns false.Example:// Scala program of equals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equals() methods val result = \"Geeks\".equals(\"Geeks\") println(\"Result : \" + result) }}Output:Result : trueBoolean equalsIgnoreCase(String anotherString): This methods works like equals() but it ignores the case differences.Example:// Scala program of equalsIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equalsIgnoreCase() methods val result = \"Geeks\".equalsIgnoreCase(\"gEeks\") println(\"Result : \" + result) }}Output:Result : true\nbyte getBytes(): This method helps in encoding a string into a sequence of bytes and it also helps in storing it into a new byte array.Example:// Scala program of getBytes() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using getBytes() methods val result = \"ABCcba\".getBytes() println(\"Result : \" + result) }}Output:Result : [B@506e1b77int indexOf(int ch): This method helps in returning the index of the first occurrence of the character in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeks\".indexOf('e') println(\"Result : \" + result) }}Output:Result : 1int indexOf(int ch, int fromIndex): This method works similar to that indexOf. The only difference is that it begins searching at the specified index.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeksforgeeks\".indexOf('g',5) println(\"Result : \" + result) }}Output:Result : 8int indexOf(String str): This method is used to return the index of the first occurrence of the substring we specify, in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeksforgeeeks\".indexOf(\"ks\") println(\"Result : \" + result) }}Output:Result : 3String intern(): This method is used to return the canonical representation for the string object.Example:// Scala program of intern() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using intern() methods val result = \"Geeks,\\n\\tForGeeks\".intern() println(\"Result : \" + result) }}Output:Result : Geeks,\n ForGeeks\nint lastIndexOf(int ch): This method is used to return the index of the last occurrence of the character we specify.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = \"Geeks\".lastIndexOf('e') println(\"Result : \" + result) }}Output:Result : 2int lastIndexOf(String str): This method is used to return the index of the last occurrence of the substring we specify, in the string.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = \"Geeksforgeeks\".lastIndexOf(\"ek\") println(\"Result : \" + result) }}Output:Result : 10int length(): This method is used to return the length of a string.Example:// Scala program of length() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using length() methods val result = \"Geeks\".length() println(\"Result : \" + result) }}Output:Result : 5String replaceAll(String regex, String replacement): This method is used to replace the substring with the replacement string provided by user.Example:// Scala program of replaceAll() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceAll() methods val result = \"potdotnothotokayslot\".replaceAll(\".ot\",\"**\") println(\"Result : \" + result) }}Output:Result : ********okays**String replaceFirst(String regex, String replacement): If in the above example, we want to replace only the first such occurrence.Example:// Scala program of replaceFirst() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceFirst() methods val result = \"potdotnothotokayslot\".replaceFirst(\".ot\",\"**\") println(\"Result : \" + result) }}Output:Result : **dotnothotokayslotString[] split(String regex): This method is used to split the string around matches of the regular expression we specify. It returns a String array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = \"PfsoQmsoRcsoGfGkso\".split(\".so\") for ( a <-result ) { // Displays output println(a) } } } Output:P\nQ\nR\nGfG\nBoolean startsWith(String prefix, int toffset): This method is used to return true if the string starts with the given index. Otherwise, it will return false.Example:// Scala program of startsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = \"Geeks\".startsWith(\"ee\", 1) println(\"Result : \" + result) }}Output:Result : trueCharSequence subSequence(int beginIndex, int endIndex): This method is used to return the sub string from the given string. Here starting index and ending index of a sub string is given.Example:// Scala program of subSequence() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using subSequence() methods val result = \"Geeks\".subSequence(1,4) println(\"Result : \" + result) }}Output:Result : eekString substring(int beginIndex): This method is used to return the characters of the string beginning from the given index till the end of the string.Example:// Scala program of substring() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = \"Geeks\".substring(3) println(\"Result : \" + result) }}Output:Result : kschar[] toCharArray(): This method is used to convert the string into a CharArray.Example:// Scala program of toCharArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toCharArray method val result = \"GeeksforGeeks\".toCharArray() for(m1<-result) { // Displays output println(m1) } } } Output:G\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\nsString toLowerCase(): This method is used to convert all the characters into lower case.Example:// Scala program of toLowerCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toLowerCase() methods val result = \"GEekS\".toLowerCase() println(\"Result : \" + result) }}Output:Result : geeksString toString(): This method is used to return a String object itself.Example:// Scala program of toString() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toString() methods val result = \"9\".toString() println(\"Result : \" + result) }}Output:Result : 9String toUpperCase(): This method is used to convert the string into upper case.Example:// Scala program of toUpperCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toUpperCase() methods val result = \"Geeks\".toUpperCase() println(\"Result : \" + result) }}Output:Result : GEEKSString trim(): This method is used to remove the leading and trailing whitespaces from the string.Example:// Scala program of trim() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using trim() methods val result = \" Geeks \".trim() println(\"Result : \" + result) }}Output:Result : GeeksString substring(int beginIndex, int endIndex): This method is used to return the part of the string beginning at beginIndex and ending at endIndex.Example:// Scala program of substring() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = \"Piyush\".substring(1, 4) println(\"Result : \" + result) }}Output:Result : iyuBoolean startsWith(String prefix): This method is used to return true if the string starts with the given prefix. Otherwise, returns false.Example:// Scala program of startsWith() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = \"Ayush\".startsWith(\" Ay\") println(\"Result : \" + result) }}Output:String[] split(String regex, int limit): This method is like split, the only change is that we can limit the number of members for the array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = \"NidhifsoSinghmsoAcso\".split(\".so\", 2) for ( m1 <-result ) { // Displays output println(m1) } } } Output:Nidhi\nSinghmsoAcsoBoolean matches(String regex): This method is used to return true, if string matches the regular expression specified.Example:// Scala program of matches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using matches() methods val result = \"Ayushi\".matches(\".i.*\") println(\"Result : \" + result) }}Output:Result : falseBoolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len): This method is used to return true if two strings regions are equal.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = \"Ayushi\".regionMatches(true, 0, \"Ayush\", 0, 3) println(\"Result : \" + result) }}Output:Result : trueString replace(char oldChar, char newChar): This method is used to replace the oldChar occurences with the newChar ones.Example:// Scala program of replace() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replace() methods val result = \"sanjay sharma\".replace('s','$') println(\"Result : \" + result) }}Output:Result : $anjay $harmaint hashCode(): This method is used to return hash code of a string.Example:// Scala program of hashCode() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using hashCode() methods val result = \"Ayushi\".hashCode() println(\"Result : \" + result) }}Output:Result : 1976240247Boolean regionMatches(int toffset, String other, int offset, int len): This method does not have any ignore case, else it is same as above method.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = \"Ayushi\".regionMatches(true, 0, \"Ayushi\", 0, 4) println(\"Result : \" + result) }}Output:Result : true" }, { "code": null, "e": 41795, "s": 41373, "text": "char charAt(int index): This method is used to returns the character at the given index.Example:// Scala program of charAt() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Getting a character at the given index // Using charAt() methods val result = \"GeeksforGeeks\".charAt(3) println(\"Result : \" + result) }}Output:Result : k" }, { "code": null, "e": 41804, "s": 41795, "text": "Example:" }, { "code": "// Scala program of charAt() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Getting a character at the given index // Using charAt() methods val result = \"GeeksforGeeks\".charAt(3) println(\"Result : \" + result) }}", "e": 42113, "s": 41804, "text": null }, { "code": null, "e": 42121, "s": 42113, "text": "Output:" }, { "code": null, "e": 42132, "s": 42121, "text": "Result : k" }, { "code": null, "e": 42604, "s": 42132, "text": "int compareTo(Object o): This method is used for the comparison of one string to another object.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val val1 = \"Hello\" val val2 = \"GeeksforGeeks\" val result = val1.compareTo(val2) println(\"Result : \" + result) }}Output:Result : 1" }, { "code": "// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val val1 = \"Hello\" val val2 = \"GeeksforGeeks\" val result = val1.compareTo(val2) println(\"Result : \" + result) }}", "e": 42955, "s": 42604, "text": null }, { "code": null, "e": 42963, "s": 42955, "text": "Output:" }, { "code": null, "e": 42974, "s": 42963, "text": "Result : 1" }, { "code": null, "e": 43483, "s": 42974, "text": "int compareTo(String anotherString): This method is used to compares two strings lexicographically. If two strings match then it returns 0, else it returns the difference between the two.Example:// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val result = \"Geeks\".compareTo(\"Geeks\") println(\"Result : \" + result) }}Output:Result : 0" }, { "code": "// Scala program of compareTo() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Compare two strings // Using compateTo() methods val result = \"Geeks\".compareTo(\"Geeks\") println(\"Result : \" + result) }}", "e": 43780, "s": 43483, "text": null }, { "code": null, "e": 43788, "s": 43780, "text": "Output:" }, { "code": null, "e": 43799, "s": 43788, "text": "Result : 0" }, { "code": null, "e": 44261, "s": 43799, "text": "int compareToIgnoreCase(String str): This method is used for comparing two strings lexicographically. It ignoring the case differences.Example:// Scala program of compareToIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using compareToIgnoreCase() methods val result = \"Geeks\".compareToIgnoreCase(\"geeks\") println(\"Result : \" + result) }}Output:Result : 0\n" }, { "code": "// Scala program of compareToIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using compareToIgnoreCase() methods val result = \"Geeks\".compareToIgnoreCase(\"geeks\") println(\"Result : \" + result) }}", "e": 44562, "s": 44261, "text": null }, { "code": null, "e": 44570, "s": 44562, "text": "Output:" }, { "code": null, "e": 44582, "s": 44570, "text": "Result : 0\n" }, { "code": null, "e": 45053, "s": 44582, "text": "String concat(String str): This method is used for concatenation of the two strings. It join two strings together and made a single string.Example:// Scala program of concat() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Concatenate two strings // Using concat() methods val result = \"Geeks\".concat(\"forGeeks\") println(\"Result : \" + result) }}Output:Result : GeeksforGeeks" }, { "code": "// Scala program of concat() method // Creating Object object GFG{ // Main method def main(args: Array[String]){ // Concatenate two strings // Using concat() methods val result = \"Geeks\".concat(\"forGeeks\") println(\"Result : \" + result) }}", "e": 45348, "s": 45053, "text": null }, { "code": null, "e": 45356, "s": 45348, "text": "Output:" }, { "code": null, "e": 45379, "s": 45356, "text": "Result : GeeksforGeeks" }, { "code": null, "e": 45906, "s": 45379, "text": "Boolean contentEquals(StringBuffer sb): This method is used to compares a string to a StringBuffer’s contents. If they are equal then it returns true otherwise it will return false.Example:// Scala program of contentEquals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using contentEquals() methods val a = new StringBuffer(\"Geeks\") val result = \"Geeks\".contentEquals(a) println(\"Result : \" + result) }}Output:Result : true" }, { "code": "// Scala program of contentEquals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using contentEquals() methods val a = new StringBuffer(\"Geeks\") val result = \"Geeks\".contentEquals(a) println(\"Result : \" + result) }}", "e": 46224, "s": 45906, "text": null }, { "code": null, "e": 46232, "s": 46224, "text": "Output:" }, { "code": null, "e": 46246, "s": 46232, "text": "Result : true" }, { "code": null, "e": 46682, "s": 46246, "text": "Boolean endsWith(String suffix): This method is used to return true if the string ends with the suffix specified. Otherwise, it returns false.Example:// Scala program of endsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using endsWith() methods val result = \"Geeks\".endsWith(\"s\") println(\"Result : \" + result) }}Output:Result : true" }, { "code": "// Scala program of endsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using endsWith() methods val result = \"Geeks\".endsWith(\"s\") println(\"Result : \" + result) }}", "e": 46948, "s": 46682, "text": null }, { "code": null, "e": 46956, "s": 46948, "text": "Output:" }, { "code": null, "e": 46970, "s": 46956, "text": "Result : true" }, { "code": null, "e": 47397, "s": 46970, "text": "Boolean equals(Object anObject): This method is used to returns true if the string and the object are equal. Otherwise, it returns false.Example:// Scala program of equals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equals() methods val result = \"Geeks\".equals(\"Geeks\") println(\"Result : \" + result) }}Output:Result : true" }, { "code": "// Scala program of equals() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equals() methods val result = \"Geeks\".equals(\"Geeks\") println(\"Result : \" + result) }}", "e": 47659, "s": 47397, "text": null }, { "code": null, "e": 47667, "s": 47659, "text": "Output:" }, { "code": null, "e": 47681, "s": 47667, "text": "Result : true" }, { "code": null, "e": 48119, "s": 47681, "text": "Boolean equalsIgnoreCase(String anotherString): This methods works like equals() but it ignores the case differences.Example:// Scala program of equalsIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equalsIgnoreCase() methods val result = \"Geeks\".equalsIgnoreCase(\"gEeks\") println(\"Result : \" + result) }}Output:Result : true\n" }, { "code": "// Scala program of equalsIgnoreCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using equalsIgnoreCase() methods val result = \"Geeks\".equalsIgnoreCase(\"gEeks\") println(\"Result : \" + result) }}", "e": 48411, "s": 48119, "text": null }, { "code": null, "e": 48419, "s": 48411, "text": "Output:" }, { "code": null, "e": 48434, "s": 48419, "text": "Result : true\n" }, { "code": null, "e": 48866, "s": 48434, "text": "byte getBytes(): This method helps in encoding a string into a sequence of bytes and it also helps in storing it into a new byte array.Example:// Scala program of getBytes() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using getBytes() methods val result = \"ABCcba\".getBytes() println(\"Result : \" + result) }}Output:Result : [B@506e1b77" }, { "code": "// Scala program of getBytes() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using getBytes() methods val result = \"ABCcba\".getBytes() println(\"Result : \" + result) }}", "e": 49128, "s": 48866, "text": null }, { "code": null, "e": 49136, "s": 49128, "text": "Output:" }, { "code": null, "e": 49157, "s": 49136, "text": "Result : [B@506e1b77" }, { "code": null, "e": 49560, "s": 49157, "text": "int indexOf(int ch): This method helps in returning the index of the first occurrence of the character in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeks\".indexOf('e') println(\"Result : \" + result) }}Output:Result : 1" }, { "code": "// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeks\".indexOf('e') println(\"Result : \" + result) }}", "e": 49821, "s": 49560, "text": null }, { "code": null, "e": 49829, "s": 49821, "text": "Output:" }, { "code": null, "e": 49840, "s": 49829, "text": "Result : 1" }, { "code": null, "e": 50286, "s": 49840, "text": "int indexOf(int ch, int fromIndex): This method works similar to that indexOf. The only difference is that it begins searching at the specified index.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeksforgeeks\".indexOf('g',5) println(\"Result : \" + result) }}Output:Result : 8" }, { "code": "// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeksforgeeks\".indexOf('g',5) println(\"Result : \" + result) }}", "e": 50557, "s": 50286, "text": null }, { "code": null, "e": 50565, "s": 50557, "text": "Output:" }, { "code": null, "e": 50576, "s": 50565, "text": "Result : 8" }, { "code": null, "e": 51004, "s": 50576, "text": "int indexOf(String str): This method is used to return the index of the first occurrence of the substring we specify, in the string.Example:// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeksforgeeeks\".indexOf(\"ks\") println(\"Result : \" + result) }}Output:Result : 3" }, { "code": "// Scala program of indexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using indexOf() methods val result = \"Geeksforgeeeks\".indexOf(\"ks\") println(\"Result : \" + result) }}", "e": 51275, "s": 51004, "text": null }, { "code": null, "e": 51283, "s": 51275, "text": "Output:" }, { "code": null, "e": 51294, "s": 51283, "text": "Result : 3" }, { "code": null, "e": 51704, "s": 51294, "text": "String intern(): This method is used to return the canonical representation for the string object.Example:// Scala program of intern() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using intern() methods val result = \"Geeks,\\n\\tForGeeks\".intern() println(\"Result : \" + result) }}Output:Result : Geeks,\n ForGeeks\n" }, { "code": "// Scala program of intern() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using intern() methods val result = \"Geeks,\\n\\tForGeeks\".intern() println(\"Result : \" + result) }}", "e": 51972, "s": 51704, "text": null }, { "code": null, "e": 51980, "s": 51972, "text": "Output:" }, { "code": null, "e": 52010, "s": 51980, "text": "Result : Geeks,\n ForGeeks\n" }, { "code": null, "e": 52424, "s": 52010, "text": "int lastIndexOf(int ch): This method is used to return the index of the last occurrence of the character we specify.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = \"Geeks\".lastIndexOf('e') println(\"Result : \" + result) }}Output:Result : 2" }, { "code": "// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = \"Geeks\".lastIndexOf('e') println(\"Result : \" + result) }}", "e": 52697, "s": 52424, "text": null }, { "code": null, "e": 52705, "s": 52697, "text": "Output:" }, { "code": null, "e": 52716, "s": 52705, "text": "Result : 2" }, { "code": null, "e": 53159, "s": 52716, "text": "int lastIndexOf(String str): This method is used to return the index of the last occurrence of the substring we specify, in the string.Example:// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = \"Geeksforgeeks\".lastIndexOf(\"ek\") println(\"Result : \" + result) }}Output:Result : 10" }, { "code": "// Scala program of lastIndexOf() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using lastIndexOf() methods val result = \"Geeksforgeeks\".lastIndexOf(\"ek\") println(\"Result : \" + result) }}", "e": 53441, "s": 53159, "text": null }, { "code": null, "e": 53449, "s": 53441, "text": "Output:" }, { "code": null, "e": 53461, "s": 53449, "text": "Result : 10" }, { "code": null, "e": 53808, "s": 53461, "text": "int length(): This method is used to return the length of a string.Example:// Scala program of length() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using length() methods val result = \"Geeks\".length() println(\"Result : \" + result) }}Output:Result : 5" }, { "code": "// Scala program of length() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using length() methods val result = \"Geeks\".length() println(\"Result : \" + result) }}", "e": 54063, "s": 53808, "text": null }, { "code": null, "e": 54071, "s": 54063, "text": "Output:" }, { "code": null, "e": 54082, "s": 54071, "text": "Result : 5" }, { "code": null, "e": 54556, "s": 54082, "text": "String replaceAll(String regex, String replacement): This method is used to replace the substring with the replacement string provided by user.Example:// Scala program of replaceAll() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceAll() methods val result = \"potdotnothotokayslot\".replaceAll(\".ot\",\"**\") println(\"Result : \" + result) }}Output:Result : ********okays**" }, { "code": "// Scala program of replaceAll() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceAll() methods val result = \"potdotnothotokayslot\".replaceAll(\".ot\",\"**\") println(\"Result : \" + result) }}", "e": 54848, "s": 54556, "text": null }, { "code": null, "e": 54856, "s": 54848, "text": "Output:" }, { "code": null, "e": 54881, "s": 54856, "text": "Result : ********okays**" }, { "code": null, "e": 55352, "s": 54881, "text": "String replaceFirst(String regex, String replacement): If in the above example, we want to replace only the first such occurrence.Example:// Scala program of replaceFirst() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceFirst() methods val result = \"potdotnothotokayslot\".replaceFirst(\".ot\",\"**\") println(\"Result : \" + result) }}Output:Result : **dotnothotokayslot" }, { "code": "// Scala program of replaceFirst() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replaceFirst() methods val result = \"potdotnothotokayslot\".replaceFirst(\".ot\",\"**\") println(\"Result : \" + result) }}", "e": 55650, "s": 55352, "text": null }, { "code": null, "e": 55658, "s": 55650, "text": "Output:" }, { "code": null, "e": 55687, "s": 55658, "text": "Result : **dotnothotokayslot" }, { "code": null, "e": 56217, "s": 55687, "text": "String[] split(String regex): This method is used to split the string around matches of the regular expression we specify. It returns a String array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = \"PfsoQmsoRcsoGfGkso\".split(\".so\") for ( a <-result ) { // Displays output println(a) } } } Output:P\nQ\nR\nGfG\n" }, { "code": "// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = \"PfsoQmsoRcsoGfGkso\".split(\".so\") for ( a <-result ) { // Displays output println(a) } } } ", "e": 56573, "s": 56217, "text": null }, { "code": null, "e": 56581, "s": 56573, "text": "Output:" }, { "code": null, "e": 56592, "s": 56581, "text": "P\nQ\nR\nGfG\n" }, { "code": null, "e": 57052, "s": 56592, "text": "Boolean startsWith(String prefix, int toffset): This method is used to return true if the string starts with the given index. Otherwise, it will return false.Example:// Scala program of startsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = \"Geeks\".startsWith(\"ee\", 1) println(\"Result : \" + result) }}Output:Result : true" }, { "code": "// Scala program of startsWith() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = \"Geeks\".startsWith(\"ee\", 1) println(\"Result : \" + result) }}", "e": 57326, "s": 57052, "text": null }, { "code": null, "e": 57334, "s": 57326, "text": "Output:" }, { "code": null, "e": 57348, "s": 57334, "text": "Result : true" }, { "code": null, "e": 57834, "s": 57348, "text": "CharSequence subSequence(int beginIndex, int endIndex): This method is used to return the sub string from the given string. Here starting index and ending index of a sub string is given.Example:// Scala program of subSequence() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using subSequence() methods val result = \"Geeks\".subSequence(1,4) println(\"Result : \" + result) }}Output:Result : eek" }, { "code": "// Scala program of subSequence() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using subSequence() methods val result = \"Geeks\".subSequence(1,4) println(\"Result : \" + result) }}", "e": 58107, "s": 57834, "text": null }, { "code": null, "e": 58115, "s": 58107, "text": "Output:" }, { "code": null, "e": 58128, "s": 58115, "text": "Result : eek" }, { "code": null, "e": 58570, "s": 58128, "text": "String substring(int beginIndex): This method is used to return the characters of the string beginning from the given index till the end of the string.Example:// Scala program of substring() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = \"Geeks\".substring(3) println(\"Result : \" + result) }}Output:Result : ks" }, { "code": "// Scala program of substring() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = \"Geeks\".substring(3) println(\"Result : \" + result) }}", "e": 58835, "s": 58570, "text": null }, { "code": null, "e": 58843, "s": 58835, "text": "Output:" }, { "code": null, "e": 58855, "s": 58843, "text": "Result : ks" }, { "code": null, "e": 59330, "s": 58855, "text": "char[] toCharArray(): This method is used to convert the string into a CharArray.Example:// Scala program of toCharArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toCharArray method val result = \"GeeksforGeeks\".toCharArray() for(m1<-result) { // Displays output println(m1) } } } Output:G\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns" }, { "code": "// Scala program of toCharArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying toCharArray method val result = \"GeeksforGeeks\".toCharArray() for(m1<-result) { // Displays output println(m1) } } } ", "e": 59684, "s": 59330, "text": null }, { "code": null, "e": 59692, "s": 59684, "text": "Output:" }, { "code": null, "e": 59718, "s": 59692, "text": "G\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns" }, { "code": null, "e": 60105, "s": 59718, "text": "String toLowerCase(): This method is used to convert all the characters into lower case.Example:// Scala program of toLowerCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toLowerCase() methods val result = \"GEekS\".toLowerCase() println(\"Result : \" + result) }}Output:Result : geeks" }, { "code": "// Scala program of toLowerCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toLowerCase() methods val result = \"GEekS\".toLowerCase() println(\"Result : \" + result) }}", "e": 60375, "s": 60105, "text": null }, { "code": null, "e": 60383, "s": 60375, "text": "Output:" }, { "code": null, "e": 60398, "s": 60383, "text": "Result : geeks" }, { "code": null, "e": 60752, "s": 60398, "text": "String toString(): This method is used to return a String object itself.Example:// Scala program of toString() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toString() methods val result = \"9\".toString() println(\"Result : \" + result) }}Output:Result : 9" }, { "code": "// Scala program of toString() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toString() methods val result = \"9\".toString() println(\"Result : \" + result) }}", "e": 61009, "s": 60752, "text": null }, { "code": null, "e": 61017, "s": 61009, "text": "Output:" }, { "code": null, "e": 61028, "s": 61017, "text": "Result : 9" }, { "code": null, "e": 61407, "s": 61028, "text": "String toUpperCase(): This method is used to convert the string into upper case.Example:// Scala program of toUpperCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toUpperCase() methods val result = \"Geeks\".toUpperCase() println(\"Result : \" + result) }}Output:Result : GEEKS" }, { "code": "// Scala program of toUpperCase() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using toUpperCase() methods val result = \"Geeks\".toUpperCase() println(\"Result : \" + result) }}", "e": 61677, "s": 61407, "text": null }, { "code": null, "e": 61685, "s": 61677, "text": "Output:" }, { "code": null, "e": 61700, "s": 61685, "text": "Result : GEEKS" }, { "code": null, "e": 62078, "s": 61700, "text": "String trim(): This method is used to remove the leading and trailing whitespaces from the string.Example:// Scala program of trim() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using trim() methods val result = \" Geeks \".trim() println(\"Result : \" + result) }}Output:Result : Geeks" }, { "code": "// Scala program of trim() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using trim() methods val result = \" Geeks \".trim() println(\"Result : \" + result) }}", "e": 62329, "s": 62078, "text": null }, { "code": null, "e": 62337, "s": 62329, "text": "Output:" }, { "code": null, "e": 62352, "s": 62337, "text": "Result : Geeks" }, { "code": null, "e": 62799, "s": 62352, "text": "String substring(int beginIndex, int endIndex): This method is used to return the part of the string beginning at beginIndex and ending at endIndex.Example:// Scala program of substring() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = \"Piyush\".substring(1, 4) println(\"Result : \" + result) }}Output:Result : iyu" }, { "code": "// Scala program of substring() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using substring() methods val result = \"Piyush\".substring(1, 4) println(\"Result : \" + result) }}", "e": 63071, "s": 62799, "text": null }, { "code": null, "e": 63079, "s": 63071, "text": "Output:" }, { "code": null, "e": 63092, "s": 63079, "text": "Result : iyu" }, { "code": null, "e": 63521, "s": 63092, "text": "Boolean startsWith(String prefix): This method is used to return true if the string starts with the given prefix. Otherwise, returns false.Example:// Scala program of startsWith() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = \"Ayush\".startsWith(\" Ay\") println(\"Result : \" + result) }}Output:" }, { "code": "// Scala program of startsWith() // method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using startsWith() methods val result = \"Ayush\".startsWith(\" Ay\") println(\"Result : \" + result) }}", "e": 63796, "s": 63521, "text": null }, { "code": null, "e": 63804, "s": 63796, "text": "Output:" }, { "code": null, "e": 64329, "s": 63804, "text": "String[] split(String regex, int limit): This method is like split, the only change is that we can limit the number of members for the array.Example:// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = \"NidhifsoSinghmsoAcso\".split(\".so\", 2) for ( m1 <-result ) { // Displays output println(m1) } } } Output:Nidhi\nSinghmsoAcso" }, { "code": "// Scala program of split() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying split method val result = \"NidhifsoSinghmsoAcso\".split(\".so\", 2) for ( m1 <-result ) { // Displays output println(m1) } } } ", "e": 64680, "s": 64329, "text": null }, { "code": null, "e": 64688, "s": 64680, "text": "Output:" }, { "code": null, "e": 64707, "s": 64688, "text": "Nidhi\nSinghmsoAcso" }, { "code": null, "e": 65119, "s": 64707, "text": "Boolean matches(String regex): This method is used to return true, if string matches the regular expression specified.Example:// Scala program of matches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using matches() methods val result = \"Ayushi\".matches(\".i.*\") println(\"Result : \" + result) }}Output:Result : false" }, { "code": "// Scala program of matches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using matches() methods val result = \"Ayushi\".matches(\".i.*\") println(\"Result : \" + result) }}", "e": 65384, "s": 65119, "text": null }, { "code": null, "e": 65392, "s": 65384, "text": "Output:" }, { "code": null, "e": 65407, "s": 65392, "text": "Result : false" }, { "code": null, "e": 65893, "s": 65407, "text": "Boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len): This method is used to return true if two strings regions are equal.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = \"Ayushi\".regionMatches(true, 0, \"Ayush\", 0, 3) println(\"Result : \" + result) }}Output:Result : true" }, { "code": "// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = \"Ayushi\".regionMatches(true, 0, \"Ayush\", 0, 3) println(\"Result : \" + result) }}", "e": 66192, "s": 65893, "text": null }, { "code": null, "e": 66200, "s": 66192, "text": "Output:" }, { "code": null, "e": 66214, "s": 66200, "text": "Result : true" }, { "code": null, "e": 66644, "s": 66214, "text": "String replace(char oldChar, char newChar): This method is used to replace the oldChar occurences with the newChar ones.Example:// Scala program of replace() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replace() methods val result = \"sanjay sharma\".replace('s','$') println(\"Result : \" + result) }}Output:Result : $anjay $harma" }, { "code": "// Scala program of replace() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using replace() methods val result = \"sanjay sharma\".replace('s','$') println(\"Result : \" + result) }}", "e": 66917, "s": 66644, "text": null }, { "code": null, "e": 66925, "s": 66917, "text": "Output:" }, { "code": null, "e": 66948, "s": 66925, "text": "Result : $anjay $harma" }, { "code": null, "e": 67312, "s": 66948, "text": "int hashCode(): This method is used to return hash code of a string.Example:// Scala program of hashCode() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using hashCode() methods val result = \"Ayushi\".hashCode() println(\"Result : \" + result) }}Output:Result : 1976240247" }, { "code": "// Scala program of hashCode() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using hashCode() methods val result = \"Ayushi\".hashCode() println(\"Result : \" + result) }}", "e": 67574, "s": 67312, "text": null }, { "code": null, "e": 67582, "s": 67574, "text": "Output:" }, { "code": null, "e": 67602, "s": 67582, "text": "Result : 1976240247" }, { "code": null, "e": 68119, "s": 67602, "text": "Boolean regionMatches(int toffset, String other, int offset, int len): This method does not have any ignore case, else it is same as above method.Example:// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = \"Ayushi\".regionMatches(true, 0, \"Ayushi\", 0, 4) println(\"Result : \" + result) }}Output:Result : true" }, { "code": "// Scala program of regionMatches() method // Creating Object object GFG{ // Main method def main(args: Array[String]) { // Using regionMatches() methods val result = \"Ayushi\".regionMatches(true, 0, \"Ayushi\", 0, 4) println(\"Result : \" + result) }}", "e": 68462, "s": 68119, "text": null }, { "code": null, "e": 68470, "s": 68462, "text": "Output:" }, { "code": null, "e": 68484, "s": 68470, "text": "Result : true" }, { "code": null, "e": 68498, "s": 68484, "text": "Scala-Strings" }, { "code": null, "e": 68504, "s": 68498, "text": "Scala" }, { "code": null, "e": 68602, "s": 68504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 68642, "s": 68602, "text": "Scala List filter() method with example" }, { "code": null, "e": 68664, "s": 68642, "text": "Type Casting in Scala" }, { "code": null, "e": 68690, "s": 68664, "text": "Class and Object in Scala" }, { "code": null, "e": 68700, "s": 68690, "text": "Scala Map" }, { "code": null, "e": 68712, "s": 68700, "text": "Scala Lists" }, { "code": null, "e": 68733, "s": 68712, "text": "Inheritance in Scala" }, { "code": null, "e": 68786, "s": 68733, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 68828, "s": 68786, "text": "Scala List contains() method with example" } ]
Map of Sets in C++ STL with Examples - GeeksforGeeks
28 Oct, 2021 Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. Map of Sets in STL: A map of sets can be very useful in designing complex data structures and algorithms. Syntax: map<datatype, set<datatype>> map_of_set : stores a set of numbers corresponding to a number or map<set<datatype>, datatype> map_of_set : stores a number corresponding to a set of numbers Lets see how to implement Maps of Sets in C++: C++ // C++ program to demonstrate use of map of set #include <bits/stdc++.h>using namespace std; void show(map<int, set<string> >& mapOfSet){ // Using iterator to access // key, value pairs present // inside the mapOfSet for (auto it = mapOfSet.begin(); it != mapOfSet.end(); it++) { // Key is integer cout << it->first << " => "; // Value is a set of string set<string> st = it->second; // Strings will be printed // in sorted order as set // maintains the order for (auto it = st.begin(); it != st.end(); it++) { cout << (*it) << ' '; } cout << '\n'; }} // Driver codeint main(){ // Declaring a map whose key // is of integer type and // value is a set of string map<int, set<string> > mapOfSet; // Inserting values in the // set mapped with key 1 mapOfSet[1].insert("Geeks"); mapOfSet[1].insert("For"); // Set stores unique or // distinct elements only mapOfSet[1].insert("Geeks"); // Inserting values in the // set mapped with key 2 mapOfSet[2].insert("Is"); mapOfSet[2].insert("The"); // Inserting values in the // set mapped with key 3 mapOfSet[3].insert("Great"); mapOfSet[3].insert("Learning"); // Inserting values in the // set mapped with key 4 mapOfSet[4].insert("Platform"); show(mapOfSet); return 0;} 1 => For Geeks 2 => Is The 3 => Great Learning 4 => Platform cpp-map cpp-set C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++ Queue in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n28 Oct, 2021" }, { "code": null, "e": 25536, "s": 25367, "text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values." }, { "code": null, "e": 25813, "s": 25536, "text": "Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element." }, { "code": null, "e": 25919, "s": 25813, "text": "Map of Sets in STL: A map of sets can be very useful in designing complex data structures and algorithms." }, { "code": null, "e": 25927, "s": 25919, "text": "Syntax:" }, { "code": null, "e": 26019, "s": 25927, "text": "map<datatype, set<datatype>> map_of_set : stores a set of numbers corresponding to a number" }, { "code": null, "e": 26022, "s": 26019, "text": "or" }, { "code": null, "e": 26114, "s": 26022, "text": "map<set<datatype>, datatype> map_of_set : stores a number corresponding to a set of numbers" }, { "code": null, "e": 26161, "s": 26114, "text": "Lets see how to implement Maps of Sets in C++:" }, { "code": null, "e": 26165, "s": 26161, "text": "C++" }, { "code": "// C++ program to demonstrate use of map of set #include <bits/stdc++.h>using namespace std; void show(map<int, set<string> >& mapOfSet){ // Using iterator to access // key, value pairs present // inside the mapOfSet for (auto it = mapOfSet.begin(); it != mapOfSet.end(); it++) { // Key is integer cout << it->first << \" => \"; // Value is a set of string set<string> st = it->second; // Strings will be printed // in sorted order as set // maintains the order for (auto it = st.begin(); it != st.end(); it++) { cout << (*it) << ' '; } cout << '\\n'; }} // Driver codeint main(){ // Declaring a map whose key // is of integer type and // value is a set of string map<int, set<string> > mapOfSet; // Inserting values in the // set mapped with key 1 mapOfSet[1].insert(\"Geeks\"); mapOfSet[1].insert(\"For\"); // Set stores unique or // distinct elements only mapOfSet[1].insert(\"Geeks\"); // Inserting values in the // set mapped with key 2 mapOfSet[2].insert(\"Is\"); mapOfSet[2].insert(\"The\"); // Inserting values in the // set mapped with key 3 mapOfSet[3].insert(\"Great\"); mapOfSet[3].insert(\"Learning\"); // Inserting values in the // set mapped with key 4 mapOfSet[4].insert(\"Platform\"); show(mapOfSet); return 0;}", "e": 27594, "s": 26165, "text": null }, { "code": null, "e": 27660, "s": 27594, "text": "1 => For Geeks \n2 => Is The \n3 => Great Learning \n4 => Platform \n" }, { "code": null, "e": 27668, "s": 27660, "text": "cpp-map" }, { "code": null, "e": 27676, "s": 27668, "text": "cpp-set" }, { "code": null, "e": 27680, "s": 27676, "text": "C++" }, { "code": null, "e": 27684, "s": 27680, "text": "CPP" }, { "code": null, "e": 27782, "s": 27684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27810, "s": 27782, "text": "Operator Overloading in C++" }, { "code": null, "e": 27830, "s": 27810, "text": "Polymorphism in C++" }, { "code": null, "e": 27863, "s": 27830, "text": "Friend class and function in C++" }, { "code": null, "e": 27887, "s": 27863, "text": "Sorting a vector in C++" }, { "code": null, "e": 27912, "s": 27887, "text": "std::string class in C++" }, { "code": null, "e": 27956, "s": 27912, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27980, "s": 27956, "text": "Inline Functions in C++" }, { "code": null, "e": 28025, "s": 27980, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 28078, "s": 28025, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
C Program For Writing A Function To Delete A Linked List - GeeksforGeeks
08 Dec, 2021 Algorithm For C:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C // C program to delete a linked list#include<stdio.h>#include<stdlib.h>#include<assert.h> // Link list node struct Node{ int data; struct Node* next;}; // Function to delete the entire // linked list void deleteList(struct Node** head_ref){ // define head_ref to get the real head struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; free(current); current = next; } // Define head_ref to affect the real // head back in the caller. *head_ref = NULL;} /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; // Use push() to construct list // 1->12->1->4->1 push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); printf("Deleting linked list"); deleteList(&head); printf("Linked list deleted");} Output: Deleting linked list Linked list deleted Time Complexity: O(n) Auxiliary Space: O(1) Please refer complete article on Write a function to delete a Linked List for more details! Delete a Linked List Linked Lists C Language C Programs Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25531, "s": 25503, "text": "\n08 Dec, 2021" }, { "code": null, "e": 25720, "s": 25531, "text": "Algorithm For C:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted." }, { "code": null, "e": 25736, "s": 25720, "text": "Implementation:" }, { "code": null, "e": 25738, "s": 25736, "text": "C" }, { "code": "// C program to delete a linked list#include<stdio.h>#include<stdlib.h>#include<assert.h> // Link list node struct Node{ int data; struct Node* next;}; // Function to delete the entire // linked list void deleteList(struct Node** head_ref){ // define head_ref to get the real head struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; free(current); current = next; } // Define head_ref to affect the real // head back in the caller. *head_ref = NULL;} /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; // Use push() to construct list // 1->12->1->4->1 push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); printf(\"Deleting linked list\"); deleteList(&head); printf(\"Linked list deleted\");}", "e": 27154, "s": 25738, "text": null }, { "code": null, "e": 27162, "s": 27154, "text": "Output:" }, { "code": null, "e": 27203, "s": 27162, "text": "Deleting linked list\nLinked list deleted" }, { "code": null, "e": 27247, "s": 27203, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 27339, "s": 27247, "text": "Please refer complete article on Write a function to delete a Linked List for more details!" }, { "code": null, "e": 27360, "s": 27339, "text": "Delete a Linked List" }, { "code": null, "e": 27373, "s": 27360, "text": "Linked Lists" }, { "code": null, "e": 27384, "s": 27373, "text": "C Language" }, { "code": null, "e": 27395, "s": 27384, "text": "C Programs" }, { "code": null, "e": 27407, "s": 27395, "text": "Linked List" }, { "code": null, "e": 27419, "s": 27407, "text": "Linked List" }, { "code": null, "e": 27517, "s": 27419, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27555, "s": 27517, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27581, "s": 27555, "text": "Exception Handling in C++" }, { "code": null, "e": 27601, "s": 27581, "text": "Multithreading in C" }, { "code": null, "e": 27623, "s": 27601, "text": "'this' pointer in C++" }, { "code": null, "e": 27664, "s": 27623, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27677, "s": 27664, "text": "Strings in C" }, { "code": null, "e": 27718, "s": 27677, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27759, "s": 27718, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27794, "s": 27759, "text": "Header files in C/C++ and its uses" } ]
Flutter - Material Design - GeeksforGeeks
22 Feb, 2022 If someone wants to quickly build beautiful, scalable apps across platforms? Then Material Design is the way to go. Material is an adaptable design system, backed by open-source code, that helps developers easily build high-quality, digital experiences. From design guidelines to developer components, Material can help developers build products faster. Material design guidelines provide best practices and user interface design. Usability and platform guidance to help make sure that our app works for all users, regardless of the platform they are using. Within the guidelines, there are components which are the building blocks that make a product usable and functional. Each component page includes guidance on how they should be used, interaction pattern, and design specifications giving you the information developer need to ensure you get it right. And the good news is flutter also supports material design. There is all kind of Material design widgets in flutter be it buttons, expanding panels, animations and much more. In this article, we are going to how we can use flutters Material Design widgets can help developers quickly break down a design and turn it into real code that runs on both iOS and Android. A color theme in Material refers to a restrained set of colors that define an interface. The default Material Theme incorporates vivid, colors like the primary and secondary, as well as color slots for backgrounds, surfaces, errors, and more. Defining a color theme. This way is helpful because it helps craft a consistent and rational color story that can be used globally and consistently throughout your app. This helps users perceive content and more easily know how the app works. One refinement of the color theme is. On Colors. On colors are named so because they appear on other elements. For example, the on background color for the below app is black, because the text that appears on the background is black, as well as other elements like icons. That also appears on the background. On colors are useful because they can help ensure that content appearing in various contexts throughout your app remains consistent and readable. They also give you a steady global control over things like color contrast, so you don’t need to fine-tune the text on every surface with the same color as long as the corresponding on color for those surfaces meets contrast requirements. These colors can also have different emphasis levels, which can be helpful for transferring information in state-rich situations or when you create a dark theme. Typography in material design is based on a type scale. A type scale is a hierarchy of type styles that can be used for various circumstances throughout a layout. The Material type scale is a mixture of 13 reusable styles that each have an intended application and meaning, all the way from big headline styles to body text captions and buttons. Working out a good type scale for your app keeps typography consistent and significant to users, while providing enough stylistic options to create a compelling appearances and character. Type is one of the subsystems that allows you to theme Material components, customizing them to create something unique. Each component’s typography fits into a category. For example, the text on a button belongs to the button category, which is shared by the buttons in a dialog box and tab labels. So changing attributes like typeface style, size, and spacing causes a ripple effect. It customizes all the typography belonging to that category. Below is a list of all major Material Design Widgets in flutter. AppBar BottomNavigationBar Drawer MaterialApp Scaffold SliverAppBar TabBar TabBarView WidgetsApp ButtonBar DropdownButton FlatButton FloatingActionButton IconButton OutlineButton PopupMenuButton RaisedButton Checkbox Date & Time Picker Radio Slider Switch TextField AlertDialog BottomSheet ExpansionPanel SimpleDialog Card Chip CircularProgressIndicator DataTable GridView Icon Image LinearProgressIndicator Tooltip Divider ListTile Stepper There are many more material design widgets available to more about then you can visit the official website. Now we will see the implementation of two material design widgets, the first is Appbar widget and the second is the Card widget. Example 1: Appbar main.dart file Dart import "package:flutter/material.dart"; // importing flutter material design libraryvoid main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text("GeeksforGeeks"), leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu Icon', onPressed: () {}, ), actions: <Widget>[ IconButton( icon: Icon(Icons.note), tooltip: 'Comment Icon', onPressed: () {}, ), SizedBox( width: 30, ) //IconButton //IconButton ], //<Widget>[] backgroundColor: Colors.green, elevation: 20.0, //IconButton shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), //BorderRadius.only ), //RoundedRectangleBorder brightness: Brightness.light, ), //AppBar body: Center( //Text ), //Center ), //Scaffold )); //MaterialApp} Output: Explanation: In the main.dart file the first thing that we did is we imported the material design library which is going let us use material design widget which in this case are MaterialApp, Scaffold, and Appbar. After initializing the app we have the MaterialApp class which is going to hold the entire widget tree for the application. In the home parameter of the MaterialApp class, we have a Scaffold widget that basically provides the whole screen of the device to render app widgets. Then inside the Scaffold widget, we have AppBar widget which is occupying the appBar parameter. The green color in the appbar is provided the be backgroundColor property, the menu icon is provided by the leading property, the text ‘GeeksforGeeks’ is provided by the title property and at the right corner the action parameter is holding note icon and a SizedBox (to provide gap from the debug banner). And the body of the app is blank currently. To know more about AppBar widget click here. Example 2: Card main.dart file Dart import 'package:flutter/material.dart'; //imported google's material design libraryvoid main() { runApp( /**Our App Widget Tree Starts Here**/ MaterialApp( home: Scaffold( appBar: AppBar( title: Text("GeeksforGeeks"), leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu Icon', onPressed: () {}, ), actions: <Widget>[ IconButton( icon: Icon(Icons.note), tooltip: 'Comment Icon', onPressed: () {}, ), SizedBox( width: 30, ) //IconButton //IconButton ], //<Widget>[] backgroundColor: Colors.green, elevation: 20.0, //IconButton shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), //BorderRadius.only ), //RoundedRectangleBorder brightness: Brightness.light, ), //AppBar body: Center( /** Card Widget **/ child: Card( elevation: 60, shadowColor: Colors.black, color: Colors.greenAccent[100], child: SizedBox( width: 300, height: 450, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.green[300], radius: 108, child: Text( "C++", style: TextStyle( fontSize: 100, fontWeight: FontWeight.bold, color: Colors.green[900]), ), ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'C++ Programming Language', style: TextStyle( fontSize: 20, color: Colors.green[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'C++ is a general purpose programing language and widely used now a days for competitive programming. It has imperative, object-oriented and generic programming features.', style: TextStyle( fontSize: 15, color: Colors.green[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox SizedBox( width: 120, child: RaisedButton( onPressed: () => null, color: Colors.green, child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Buy Now'), ], ), //Row ), //Padding ), //RaisedButton ) //SizedBox ], ), //Column ), //Padding ), //SizedBox ), //Card ), //Center ), //Scaffold ) //MaterialApp );} Output: Explanation: This app is the further continuation of the previous app, in this example, we are going to add a Card widget in the body of the app, which was blank earlier. In the body parameter of the MaterialApp the parent widget is Center which is holding the Card widget. Card widget is utilizing four of its parameter in total, which are: elevation : It uplifts the card from its background by providing a bit of black shadow. Here it is 60. shadowColor : It provides color to the shadow. The above property also uses the color provided by this parameter. Here the shadow color is black. color: As the name suggests it provide the background color for the card. In this case, the color of the card is greenAccent[100]. child: This property would hold all the content of the app. Here the SizedBox widget with dimensions 300X450 is going to hold all the content of the app which is arranged by a Column widget. Inside the Column widget, there are CircularAvatar, two Text widgets, and a RaisedButton all separated by SizedBox of height 10. These were just two examples of the material design widget in flutter, to see more examples you can click on the link provided in the above list. surinderdawra388 sagartomar9927 simranarora5sos arorakashish0911 Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25261, "s": 25233, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25379, "s": 25261, "text": " If someone wants to quickly build beautiful, scalable apps across platforms? Then Material Design is the way to go. " }, { "code": null, "e": 26121, "s": 25379, "text": "Material is an adaptable design system, backed by open-source code, that helps developers easily build high-quality, digital experiences. From design guidelines to developer components, Material can help developers build products faster. Material design guidelines provide best practices and user interface design. Usability and platform guidance to help make sure that our app works for all users, regardless of the platform they are using. Within the guidelines, there are components which are the building blocks that make a product usable and functional. Each component page includes guidance on how they should be used, interaction pattern, and design specifications giving you the information developer need to ensure you get it right." }, { "code": null, "e": 26487, "s": 26121, "text": "And the good news is flutter also supports material design. There is all kind of Material design widgets in flutter be it buttons, expanding panels, animations and much more. In this article, we are going to how we can use flutters Material Design widgets can help developers quickly break down a design and turn it into real code that runs on both iOS and Android." }, { "code": null, "e": 26974, "s": 26487, "text": "A color theme in Material refers to a restrained set of colors that define an interface. The default Material Theme incorporates vivid, colors like the primary and secondary, as well as color slots for backgrounds, surfaces, errors, and more. Defining a color theme. This way is helpful because it helps craft a consistent and rational color story that can be used globally and consistently throughout your app. This helps users perceive content and more easily know how the app works. " }, { "code": null, "e": 27429, "s": 26974, "text": "One refinement of the color theme is. On Colors. On colors are named so because they appear on other elements. For example, the on background color for the below app is black, because the text that appears on the background is black, as well as other elements like icons. That also appears on the background. On colors are useful because they can help ensure that content appearing in various contexts throughout your app remains consistent and readable." }, { "code": null, "e": 27830, "s": 27429, "text": "They also give you a steady global control over things like color contrast, so you don’t need to fine-tune the text on every surface with the same color as long as the corresponding on color for those surfaces meets contrast requirements. These colors can also have different emphasis levels, which can be helpful for transferring information in state-rich situations or when you create a dark theme." }, { "code": null, "e": 28364, "s": 27830, "text": "Typography in material design is based on a type scale. A type scale is a hierarchy of type styles that can be used for various circumstances throughout a layout. The Material type scale is a mixture of 13 reusable styles that each have an intended application and meaning, all the way from big headline styles to body text captions and buttons. Working out a good type scale for your app keeps typography consistent and significant to users, while providing enough stylistic options to create a compelling appearances and character." }, { "code": null, "e": 28811, "s": 28364, "text": "Type is one of the subsystems that allows you to theme Material components, customizing them to create something unique. Each component’s typography fits into a category. For example, the text on a button belongs to the button category, which is shared by the buttons in a dialog box and tab labels. So changing attributes like typeface style, size, and spacing causes a ripple effect. It customizes all the typography belonging to that category." }, { "code": null, "e": 28876, "s": 28811, "text": "Below is a list of all major Material Design Widgets in flutter." }, { "code": null, "e": 28883, "s": 28876, "text": "AppBar" }, { "code": null, "e": 28903, "s": 28883, "text": "BottomNavigationBar" }, { "code": null, "e": 28910, "s": 28903, "text": "Drawer" }, { "code": null, "e": 28922, "s": 28910, "text": "MaterialApp" }, { "code": null, "e": 28931, "s": 28922, "text": "Scaffold" }, { "code": null, "e": 28944, "s": 28931, "text": "SliverAppBar" }, { "code": null, "e": 28951, "s": 28944, "text": "TabBar" }, { "code": null, "e": 28962, "s": 28951, "text": "TabBarView" }, { "code": null, "e": 28973, "s": 28962, "text": "WidgetsApp" }, { "code": null, "e": 28983, "s": 28973, "text": "ButtonBar" }, { "code": null, "e": 28998, "s": 28983, "text": "DropdownButton" }, { "code": null, "e": 29009, "s": 28998, "text": "FlatButton" }, { "code": null, "e": 29030, "s": 29009, "text": "FloatingActionButton" }, { "code": null, "e": 29041, "s": 29030, "text": "IconButton" }, { "code": null, "e": 29055, "s": 29041, "text": "OutlineButton" }, { "code": null, "e": 29071, "s": 29055, "text": "PopupMenuButton" }, { "code": null, "e": 29084, "s": 29071, "text": "RaisedButton" }, { "code": null, "e": 29093, "s": 29084, "text": "Checkbox" }, { "code": null, "e": 29112, "s": 29093, "text": "Date & Time Picker" }, { "code": null, "e": 29118, "s": 29112, "text": "Radio" }, { "code": null, "e": 29125, "s": 29118, "text": "Slider" }, { "code": null, "e": 29132, "s": 29125, "text": "Switch" }, { "code": null, "e": 29142, "s": 29132, "text": "TextField" }, { "code": null, "e": 29154, "s": 29142, "text": "AlertDialog" }, { "code": null, "e": 29166, "s": 29154, "text": "BottomSheet" }, { "code": null, "e": 29181, "s": 29166, "text": "ExpansionPanel" }, { "code": null, "e": 29194, "s": 29181, "text": "SimpleDialog" }, { "code": null, "e": 29199, "s": 29194, "text": "Card" }, { "code": null, "e": 29204, "s": 29199, "text": "Chip" }, { "code": null, "e": 29230, "s": 29204, "text": "CircularProgressIndicator" }, { "code": null, "e": 29240, "s": 29230, "text": "DataTable" }, { "code": null, "e": 29249, "s": 29240, "text": "GridView" }, { "code": null, "e": 29254, "s": 29249, "text": "Icon" }, { "code": null, "e": 29260, "s": 29254, "text": "Image" }, { "code": null, "e": 29284, "s": 29260, "text": "LinearProgressIndicator" }, { "code": null, "e": 29292, "s": 29284, "text": "Tooltip" }, { "code": null, "e": 29300, "s": 29292, "text": "Divider" }, { "code": null, "e": 29309, "s": 29300, "text": "ListTile" }, { "code": null, "e": 29317, "s": 29309, "text": "Stepper" }, { "code": null, "e": 29555, "s": 29317, "text": "There are many more material design widgets available to more about then you can visit the official website. Now we will see the implementation of two material design widgets, the first is Appbar widget and the second is the Card widget." }, { "code": null, "e": 29573, "s": 29555, "text": "Example 1: Appbar" }, { "code": null, "e": 29588, "s": 29573, "text": "main.dart file" }, { "code": null, "e": 29593, "s": 29588, "text": "Dart" }, { "code": "import \"package:flutter/material.dart\"; // importing flutter material design libraryvoid main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text(\"GeeksforGeeks\"), leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu Icon', onPressed: () {}, ), actions: <Widget>[ IconButton( icon: Icon(Icons.note), tooltip: 'Comment Icon', onPressed: () {}, ), SizedBox( width: 30, ) //IconButton //IconButton ], //<Widget>[] backgroundColor: Colors.green, elevation: 20.0, //IconButton shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), //BorderRadius.only ), //RoundedRectangleBorder brightness: Brightness.light, ), //AppBar body: Center( //Text ), //Center ), //Scaffold )); //MaterialApp}", "e": 30654, "s": 29593, "text": null }, { "code": null, "e": 30663, "s": 30654, "text": "Output: " }, { "code": null, "e": 31600, "s": 30663, "text": "Explanation: In the main.dart file the first thing that we did is we imported the material design library which is going let us use material design widget which in this case are MaterialApp, Scaffold, and Appbar. After initializing the app we have the MaterialApp class which is going to hold the entire widget tree for the application. In the home parameter of the MaterialApp class, we have a Scaffold widget that basically provides the whole screen of the device to render app widgets. Then inside the Scaffold widget, we have AppBar widget which is occupying the appBar parameter. The green color in the appbar is provided the be backgroundColor property, the menu icon is provided by the leading property, the text ‘GeeksforGeeks’ is provided by the title property and at the right corner the action parameter is holding note icon and a SizedBox (to provide gap from the debug banner). And the body of the app is blank currently. " }, { "code": null, "e": 31645, "s": 31600, "text": "To know more about AppBar widget click here." }, { "code": null, "e": 31661, "s": 31645, "text": "Example 2: Card" }, { "code": null, "e": 31676, "s": 31661, "text": "main.dart file" }, { "code": null, "e": 31681, "s": 31676, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; //imported google's material design libraryvoid main() { runApp( /**Our App Widget Tree Starts Here**/ MaterialApp( home: Scaffold( appBar: AppBar( title: Text(\"GeeksforGeeks\"), leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu Icon', onPressed: () {}, ), actions: <Widget>[ IconButton( icon: Icon(Icons.note), tooltip: 'Comment Icon', onPressed: () {}, ), SizedBox( width: 30, ) //IconButton //IconButton ], //<Widget>[] backgroundColor: Colors.green, elevation: 20.0, //IconButton shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)), //BorderRadius.only ), //RoundedRectangleBorder brightness: Brightness.light, ), //AppBar body: Center( /** Card Widget **/ child: Card( elevation: 60, shadowColor: Colors.black, color: Colors.greenAccent[100], child: SizedBox( width: 300, height: 450, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.green[300], radius: 108, child: Text( \"C++\", style: TextStyle( fontSize: 100, fontWeight: FontWeight.bold, color: Colors.green[900]), ), ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'C++ Programming Language', style: TextStyle( fontSize: 20, color: Colors.green[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'C++ is a general purpose programing language and widely used now a days for competitive programming. It has imperative, object-oriented and generic programming features.', style: TextStyle( fontSize: 15, color: Colors.green[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox SizedBox( width: 120, child: RaisedButton( onPressed: () => null, color: Colors.green, child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Buy Now'), ], ), //Row ), //Padding ), //RaisedButton ) //SizedBox ], ), //Column ), //Padding ), //SizedBox ), //Card ), //Center ), //Scaffold ) //MaterialApp );}", "e": 35297, "s": 31681, "text": null }, { "code": null, "e": 35306, "s": 35297, "text": "Output: " }, { "code": null, "e": 35648, "s": 35306, "text": "Explanation: This app is the further continuation of the previous app, in this example, we are going to add a Card widget in the body of the app, which was blank earlier. In the body parameter of the MaterialApp the parent widget is Center which is holding the Card widget. Card widget is utilizing four of its parameter in total, which are:" }, { "code": null, "e": 35751, "s": 35648, "text": "elevation : It uplifts the card from its background by providing a bit of black shadow. Here it is 60." }, { "code": null, "e": 35897, "s": 35751, "text": "shadowColor : It provides color to the shadow. The above property also uses the color provided by this parameter. Here the shadow color is black." }, { "code": null, "e": 36028, "s": 35897, "text": "color: As the name suggests it provide the background color for the card. In this case, the color of the card is greenAccent[100]." }, { "code": null, "e": 36348, "s": 36028, "text": "child: This property would hold all the content of the app. Here the SizedBox widget with dimensions 300X450 is going to hold all the content of the app which is arranged by a Column widget. Inside the Column widget, there are CircularAvatar, two Text widgets, and a RaisedButton all separated by SizedBox of height 10." }, { "code": null, "e": 36494, "s": 36348, "text": "These were just two examples of the material design widget in flutter, to see more examples you can click on the link provided in the above list." }, { "code": null, "e": 36511, "s": 36494, "text": "surinderdawra388" }, { "code": null, "e": 36526, "s": 36511, "text": "sagartomar9927" }, { "code": null, "e": 36542, "s": 36526, "text": "simranarora5sos" }, { "code": null, "e": 36559, "s": 36542, "text": "arorakashish0911" }, { "code": null, "e": 36566, "s": 36559, "text": "Picked" }, { "code": null, "e": 36571, "s": 36566, "text": "Dart" }, { "code": null, "e": 36579, "s": 36571, "text": "Flutter" }, { "code": null, "e": 36677, "s": 36579, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36716, "s": 36677, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 36742, "s": 36716, "text": "ListView Class in Flutter" }, { "code": null, "e": 36768, "s": 36742, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 36791, "s": 36768, "text": "Flutter - Stack Widget" }, { "code": null, "e": 36809, "s": 36791, "text": "Flutter - Dialogs" }, { "code": null, "e": 36848, "s": 36809, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 36865, "s": 36848, "text": "Flutter Tutorial" }, { "code": null, "e": 36891, "s": 36865, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 36914, "s": 36891, "text": "Flutter - Stack Widget" } ]
Read File Into an Array in Java - GeeksforGeeks
21 Feb, 2022 In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method. To store the content of the file better use the collection storage type instead of a static array as we don’t know the exact lines or word count of files. Then convert the collection type to the array as per the requirement. As to read the content of the file, first we need to create a file with some text in it. Let us consider the below text is present in the file named file.txt Geeks,for Geeks Learning portal There are mainly 4 approaches to read the content of the file and store it in the array. They are mentioned below- Using BufferedReader to read the fileUsing Scanner to read the filereadAllLines() methodUsing FileReader Using BufferedReader to read the file Using Scanner to read the file readAllLines() method Using FileReader It was the easiest way for developers to code it to get the content of the file and it is also a preferred way to read the file because it takes fewer number reading calls because it uses a char buffer that simultaneously reads multiple values from a character input stream. BufferedReader bf=new BufferedReader (new FileReader(filename)) BufferedReader also provides a method called readLine that takes the entire line in a file as a string. Below is the example code to store the content of the file in an array. Example: Java // import necessary packagesimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; public class GFG { // to handle exceptions include throws public static void main(String[] args) throws IOException { // list that holds strings of a file List<String> listOfStrings = new ArrayList<String>(); // load data from file BufferedReader bf = new BufferedReader( new FileReader("file.txt")); // read entire line as string String line = bf.readLine(); // checking for end of file while (line != null) { listOfStrings.add(line); line = bf.readLine(); } // closing bufferreader object bf.close(); // storing the data in arraylist to array String[] array = listOfStrings.toArray(new String[0]); // printing each line of file // which is stored in array for (String str : array) { System.out.println(str); } }} Output: Geeks,for Geeks Learning portal Explanation: In this code, we used BufferedReader to read and load the content of a file, and then we used the readLine method to get each line of the file as a string and stored/added in ArrayList and finally we converted that ArrayList to Array using toArray method. But in order to specify any delimiter to separate data in a file, In that case, a Scanner will be helpful. As we can see that there are 2 strings in the first line of a file but using BufferedReader we got them as a combined string. Note: While reading the file, if the file is in same location where the program code is saved then no need to mention path just specify the file name. If the file is in a different location with respect to the program saved location then we should specify the path along with the filename. The scanner is mainly used to read data from users for primitive datatypes. But even to get data from a file Scanner can be used along with File or FileReader to load data of a file. This Scanner generally breaks the tokens into strings by a default delimiter space but even we can explicitly specify the other delimiters by using the useDelimiter method. Syntax: Scanner sc = new Scanner(new FileReader("filename")).useDelimiter("delimiter to separate strings"); The scanner is present in util package which we need to import before using it and it also provides readLine() and hasNext() to check the end of the file i.e., whether there are any strings available or not to read. Below is the example code to store the content of the file in an array using Scanner. Example: Java // import necessary packagesimport java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Scanner; public class GFG { // include throws to handle some file handling exceptions public static void main(String[] args) throws IOException { // arraylist to store strings List<String> listOfStrings = new ArrayList<String>(); // load content of file based on specific delimiter Scanner sc = new Scanner(new FileReader("file.txt")) .useDelimiter(",\\s*"); String str; // checking end of file while (sc.hasNext()) { str = sc.next(); // adding each string to arraylist listOfStrings.add(str); } // convert any arraylist to array String[] array = listOfStrings.toArray(new String[0]); // print each string in array for (String eachString : array) { System.out.println(eachString); } }} Output Geeks for Geeks Learning portal Explanation: In this code, we used Scanner to read and load the content of the file, and here there is a flexibility of specifying the delimiter using the useDelimiter method so that we can separate strings based on delimiter and each of these strings separated based on delimiter are stored/added in ArrayList and we can check EOF by using hasNext method. Finally, we converted that ArrayList to Array using the toArray method. As we specified delimiter value as “,” (comma) we got 2 separated strings geeks and for. If we didn’t specify any delimiter method to Scanner then it will separate strings based on spaces. Note: There is another method called readAllLines present in Files class use to read the content of file line by line To use this first we need to import Files and Paths classes from the file package. The benefit of using this method is it reduces the lines of code to fetch and store data. Syntax of this is mentioned below- FIles.readAllLines(Paths("filename")) Below is the code to load the content of the file and store it in an array using readAllLines method. Example: Java // import necessary packages and classesimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.util.ArrayList;import java.util.List; public class Box { // add throws to main method to handle exceptions public static void main(String[] args) throws IOException { List<String> listOfStrings = new ArrayList<String>(); // load the data from file listOfStrings = Files.readAllLines(Paths.get("file.txt")); // convert arraylist to array String[] array = listOfStrings.toArray(new String[0]); // print each line of string in array for (String eachString : array) { System.out.println(eachString); } }} Output Geeks,for Geeks Learning portal Explanation: Here we used readAllLines method to get each line in a file and return a list of strings. This list is converted to an array using the toArray method. Using FileReader we can load the data in the file and can read character-wise data from the FileReader object. Before using FIleReader in a program we need to import FileReader class from the io package. Syntax: FileReader filereaderObj=new FileReader("filename"); Let’s see the below example code to read data from a file and store it in an array using FileReader. Example: Java // import necessary packagesimport java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; class GFG { // to handle exceptions include throws public static void main(String[] args) throws IOException { // list that holds strings of a file List<String> listOfStrings = new ArrayList<String>(); // load data from file FileReader fr = new FileReader("file.txt"); // Created a string to store each character // to form word String s = new String(); char ch; // checking for EOF while (fr.ready()) { ch = (char)fr.read(); // Used to specify the delimiters if (ch == '\n' || ch == ' ' || ch == ',') { // Storing each string in arraylist listOfStrings.add(s.toString()); // clearing content in string s = new String(); } else { // appending each character to string if the // current character is not delimiter s += ch; } } if (s.length() > 0) { // appending last line of strings to list listOfStrings.add(s.toString()); } // storing the data in arraylist to array String[] array = listOfStrings.toArray(new String[0]); // printing each line of file which is stored in // array for (String str : array) { System.out.println(str); } }} Output Geeks for Geeks Learning portal Explanation: In this code, we used FileReader to load data from a file in its object. This object holds data as a stream of characters and we can fetch data from it as a character by character. So we store each character in a string and if the character fetched was any delimiter i.e., specified in if statement [\n, (space) ‘ ‘, (comma) ‘,’] then we store that string in ArrayList and clear the content in the string if not then append that character to string. Like this, we store all the strings in a file into an ArrayList and this is converted to Array. These are all possible approaches that can be followed to read data from files and store it in the array. sagartomar9927 kk773572498 as5853535 Java-Arrays Java-Files Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Internal Working of HashMap in Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n21 Feb, 2022" }, { "code": null, "e": 25618, "s": 25225, "text": "In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method. To store the content of the file better use the collection storage type instead of a static array as we don’t know the exact lines or word count of files. Then convert the collection type to the array as per the requirement." }, { "code": null, "e": 25776, "s": 25618, "text": "As to read the content of the file, first we need to create a file with some text in it. Let us consider the below text is present in the file named file.txt" }, { "code": null, "e": 25808, "s": 25776, "text": "Geeks,for\nGeeks\nLearning portal" }, { "code": null, "e": 25923, "s": 25808, "text": "There are mainly 4 approaches to read the content of the file and store it in the array. They are mentioned below-" }, { "code": null, "e": 26028, "s": 25923, "text": "Using BufferedReader to read the fileUsing Scanner to read the filereadAllLines() methodUsing FileReader" }, { "code": null, "e": 26066, "s": 26028, "text": "Using BufferedReader to read the file" }, { "code": null, "e": 26097, "s": 26066, "text": "Using Scanner to read the file" }, { "code": null, "e": 26119, "s": 26097, "text": "readAllLines() method" }, { "code": null, "e": 26136, "s": 26119, "text": "Using FileReader" }, { "code": null, "e": 26411, "s": 26136, "text": "It was the easiest way for developers to code it to get the content of the file and it is also a preferred way to read the file because it takes fewer number reading calls because it uses a char buffer that simultaneously reads multiple values from a character input stream." }, { "code": null, "e": 26475, "s": 26411, "text": "BufferedReader bf=new BufferedReader (new FileReader(filename))" }, { "code": null, "e": 26579, "s": 26475, "text": "BufferedReader also provides a method called readLine that takes the entire line in a file as a string." }, { "code": null, "e": 26651, "s": 26579, "text": "Below is the example code to store the content of the file in an array." }, { "code": null, "e": 26660, "s": 26651, "text": "Example:" }, { "code": null, "e": 26665, "s": 26660, "text": "Java" }, { "code": "// import necessary packagesimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; public class GFG { // to handle exceptions include throws public static void main(String[] args) throws IOException { // list that holds strings of a file List<String> listOfStrings = new ArrayList<String>(); // load data from file BufferedReader bf = new BufferedReader( new FileReader(\"file.txt\")); // read entire line as string String line = bf.readLine(); // checking for end of file while (line != null) { listOfStrings.add(line); line = bf.readLine(); } // closing bufferreader object bf.close(); // storing the data in arraylist to array String[] array = listOfStrings.toArray(new String[0]); // printing each line of file // which is stored in array for (String str : array) { System.out.println(str); } }}", "e": 27787, "s": 26665, "text": null }, { "code": null, "e": 27795, "s": 27787, "text": "Output:" }, { "code": null, "e": 27827, "s": 27795, "text": "Geeks,for\nGeeks\nLearning portal" }, { "code": null, "e": 28096, "s": 27827, "text": "Explanation: In this code, we used BufferedReader to read and load the content of a file, and then we used the readLine method to get each line of the file as a string and stored/added in ArrayList and finally we converted that ArrayList to Array using toArray method." }, { "code": null, "e": 28329, "s": 28096, "text": "But in order to specify any delimiter to separate data in a file, In that case, a Scanner will be helpful. As we can see that there are 2 strings in the first line of a file but using BufferedReader we got them as a combined string." }, { "code": null, "e": 28619, "s": 28329, "text": "Note: While reading the file, if the file is in same location where the program code is saved then no need to mention path just specify the file name. If the file is in a different location with respect to the program saved location then we should specify the path along with the filename." }, { "code": null, "e": 28975, "s": 28619, "text": "The scanner is mainly used to read data from users for primitive datatypes. But even to get data from a file Scanner can be used along with File or FileReader to load data of a file. This Scanner generally breaks the tokens into strings by a default delimiter space but even we can explicitly specify the other delimiters by using the useDelimiter method." }, { "code": null, "e": 28983, "s": 28975, "text": "Syntax:" }, { "code": null, "e": 29083, "s": 28983, "text": "Scanner sc = new Scanner(new FileReader(\"filename\")).useDelimiter(\"delimiter to separate strings\");" }, { "code": null, "e": 29299, "s": 29083, "text": "The scanner is present in util package which we need to import before using it and it also provides readLine() and hasNext() to check the end of the file i.e., whether there are any strings available or not to read." }, { "code": null, "e": 29385, "s": 29299, "text": "Below is the example code to store the content of the file in an array using Scanner." }, { "code": null, "e": 29394, "s": 29385, "text": "Example:" }, { "code": null, "e": 29399, "s": 29394, "text": "Java" }, { "code": "// import necessary packagesimport java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Scanner; public class GFG { // include throws to handle some file handling exceptions public static void main(String[] args) throws IOException { // arraylist to store strings List<String> listOfStrings = new ArrayList<String>(); // load content of file based on specific delimiter Scanner sc = new Scanner(new FileReader(\"file.txt\")) .useDelimiter(\",\\\\s*\"); String str; // checking end of file while (sc.hasNext()) { str = sc.next(); // adding each string to arraylist listOfStrings.add(str); } // convert any arraylist to array String[] array = listOfStrings.toArray(new String[0]); // print each string in array for (String eachString : array) { System.out.println(eachString); } }}", "e": 30471, "s": 29399, "text": null }, { "code": null, "e": 30479, "s": 30471, "text": " Output" }, { "code": null, "e": 30511, "s": 30479, "text": "Geeks\nfor\nGeeks\nLearning portal" }, { "code": null, "e": 30940, "s": 30511, "text": "Explanation: In this code, we used Scanner to read and load the content of the file, and here there is a flexibility of specifying the delimiter using the useDelimiter method so that we can separate strings based on delimiter and each of these strings separated based on delimiter are stored/added in ArrayList and we can check EOF by using hasNext method. Finally, we converted that ArrayList to Array using the toArray method." }, { "code": null, "e": 31129, "s": 30940, "text": "As we specified delimiter value as “,” (comma) we got 2 separated strings geeks and for. If we didn’t specify any delimiter method to Scanner then it will separate strings based on spaces." }, { "code": null, "e": 31247, "s": 31129, "text": "Note: There is another method called readAllLines present in Files class use to read the content of file line by line" }, { "code": null, "e": 31455, "s": 31247, "text": "To use this first we need to import Files and Paths classes from the file package. The benefit of using this method is it reduces the lines of code to fetch and store data. Syntax of this is mentioned below-" }, { "code": null, "e": 31493, "s": 31455, "text": "FIles.readAllLines(Paths(\"filename\"))" }, { "code": null, "e": 31595, "s": 31493, "text": "Below is the code to load the content of the file and store it in an array using readAllLines method." }, { "code": null, "e": 31604, "s": 31595, "text": "Example:" }, { "code": null, "e": 31609, "s": 31604, "text": "Java" }, { "code": "// import necessary packages and classesimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths;import java.util.ArrayList;import java.util.List; public class Box { // add throws to main method to handle exceptions public static void main(String[] args) throws IOException { List<String> listOfStrings = new ArrayList<String>(); // load the data from file listOfStrings = Files.readAllLines(Paths.get(\"file.txt\")); // convert arraylist to array String[] array = listOfStrings.toArray(new String[0]); // print each line of string in array for (String eachString : array) { System.out.println(eachString); } }}", "e": 32383, "s": 31609, "text": null }, { "code": null, "e": 32390, "s": 32383, "text": "Output" }, { "code": null, "e": 32422, "s": 32390, "text": "Geeks,for\nGeeks\nLearning portal" }, { "code": null, "e": 32587, "s": 32422, "text": "Explanation: Here we used readAllLines method to get each line in a file and return a list of strings. This list is converted to an array using the toArray method. " }, { "code": null, "e": 32791, "s": 32587, "text": "Using FileReader we can load the data in the file and can read character-wise data from the FileReader object. Before using FIleReader in a program we need to import FileReader class from the io package." }, { "code": null, "e": 32799, "s": 32791, "text": "Syntax:" }, { "code": null, "e": 32852, "s": 32799, "text": "FileReader filereaderObj=new FileReader(\"filename\");" }, { "code": null, "e": 32953, "s": 32852, "text": "Let’s see the below example code to read data from a file and store it in an array using FileReader." }, { "code": null, "e": 32962, "s": 32953, "text": "Example:" }, { "code": null, "e": 32967, "s": 32962, "text": "Java" }, { "code": "// import necessary packagesimport java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; class GFG { // to handle exceptions include throws public static void main(String[] args) throws IOException { // list that holds strings of a file List<String> listOfStrings = new ArrayList<String>(); // load data from file FileReader fr = new FileReader(\"file.txt\"); // Created a string to store each character // to form word String s = new String(); char ch; // checking for EOF while (fr.ready()) { ch = (char)fr.read(); // Used to specify the delimiters if (ch == '\\n' || ch == ' ' || ch == ',') { // Storing each string in arraylist listOfStrings.add(s.toString()); // clearing content in string s = new String(); } else { // appending each character to string if the // current character is not delimiter s += ch; } } if (s.length() > 0) { // appending last line of strings to list listOfStrings.add(s.toString()); } // storing the data in arraylist to array String[] array = listOfStrings.toArray(new String[0]); // printing each line of file which is stored in // array for (String str : array) { System.out.println(str); } }}", "e": 34597, "s": 32967, "text": null }, { "code": null, "e": 34605, "s": 34597, "text": " Output" }, { "code": null, "e": 34637, "s": 34605, "text": "Geeks\nfor\nGeeks\nLearning\nportal" }, { "code": null, "e": 35196, "s": 34637, "text": "Explanation: In this code, we used FileReader to load data from a file in its object. This object holds data as a stream of characters and we can fetch data from it as a character by character. So we store each character in a string and if the character fetched was any delimiter i.e., specified in if statement [\\n, (space) ‘ ‘, (comma) ‘,’] then we store that string in ArrayList and clear the content in the string if not then append that character to string. Like this, we store all the strings in a file into an ArrayList and this is converted to Array." }, { "code": null, "e": 35302, "s": 35196, "text": "These are all possible approaches that can be followed to read data from files and store it in the array." }, { "code": null, "e": 35319, "s": 35304, "text": "sagartomar9927" }, { "code": null, "e": 35331, "s": 35319, "text": "kk773572498" }, { "code": null, "e": 35341, "s": 35331, "text": "as5853535" }, { "code": null, "e": 35353, "s": 35341, "text": "Java-Arrays" }, { "code": null, "e": 35364, "s": 35353, "text": "Java-Files" }, { "code": null, "e": 35371, "s": 35364, "text": "Picked" }, { "code": null, "e": 35376, "s": 35371, "text": "Java" }, { "code": null, "e": 35381, "s": 35376, "text": "Java" }, { "code": null, "e": 35479, "s": 35381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35494, "s": 35479, "text": "Stream In Java" }, { "code": null, "e": 35515, "s": 35494, "text": "Constructors in Java" }, { "code": null, "e": 35534, "s": 35515, "text": "Exceptions in Java" }, { "code": null, "e": 35564, "s": 35534, "text": "Functional Interfaces in Java" }, { "code": null, "e": 35610, "s": 35564, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 35627, "s": 35610, "text": "Generics in Java" }, { "code": null, "e": 35648, "s": 35627, "text": "Introduction to Java" }, { "code": null, "e": 35684, "s": 35648, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 35727, "s": 35684, "text": "Comparator Interface in Java with Examples" } ]
Static and Dynamic Libraries | Set 1 - GeeksforGeeks
14 Oct, 2019 When a C program is compiled, the compiler generates object code. After generating the object code, the compiler also invokes linker. One of the main tasks for linker is to make code of library functions (eg printf(), scanf(), sqrt(), ..etc) available to your program. A linker can accomplish this task in two ways, by copying the code of library function to your object code, or by making some arrangements so that the complete code of library functions is not copied, but made available at run-time. Static Linking and Static Libraries is the result of the linker making copy of all used library functions to the executable file. Static Linking creates larger binary files, and need more space on disk and main memory. Examples of static libraries (libraries which are statically linked) are, .a files in Linux and .lib files in Windows. Steps to create a static library Let us create and use a Static Library in UNIX or UNIX like OS.1. Create a C file that contains functions in your library. /* Filename: lib_mylib.c */#include <stdio.h>void fun(void){ printf("fun() called from a static library");} We have created only one file for simplicity. We can also create multiple files in a library. 2. Create a header file for the library /* Filename: lib_mylib.h */void fun(void); 3. Compile library files. gcc -c lib_mylib.c -o lib_mylib.o 4. Create static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is static library. ar rcs lib_mylib.a lib_mylib.o 5. Now our static library is ready to use. At this point we could just copy lib_mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory. Let us create a driver program that uses above created static library.1. Create a C file with main function /* filename: driver.c */#include "lib_mylib.h"void main() { fun();} 2. Compile the driver program. gcc -c driver.c -o driver.o 3. Link the compiled driver program to the static library. Note that -L. is used to tell that the static library is in current folder (See this for details of -L and -l options). gcc -o driver driver.o -L. -l_mylib 4. Run the driver program ./driver fun() called from a static library Following are some important points about static libraries.1. For a static library, the actual code is extracted from the library by the linker and used to build the final executable at the point you compile/build your application. 2. Each process gets its own copy of the code and data. Where as in case of dynamic libraries it is only code shared, data is specific to each process. For static libraries memory footprints are larger. For example, if all the window system tools were statically linked, several tens of megabytes of RAM would be wasted for a typical user, and the user would be slowed down by a lot of paging. 3. Since library code is connected at compile time, the final executable has no dependencies on the library at run time i.e. no additional run-time loading costs, it means that you don’t need to carry along a copy of the library that is being used and you have everything under your control and there is no dependency. 4. In static libraries, once everything is bundled into your application, you don’t have to worry that the client will have the right library (and version) available on their system. 5. One drawback of static libraries is, for any change(up-gradation) in the static libraries, you have to recompile the main program every time. 6. One major advantage of static libraries being preferred even now “is speed”. There will be no dynamic querying of symbols in static libraries. Many production line software use static libraries even today. Dynamic linking and Dynamic Libraries Dynamic Linking doesn’t require the code to be copied, it is done by just placing name of the library in the binary file. The actual linking happens when the program is run, when both the binary file and the library are in memory. Examples of Dynamic libraries (libraries which are linked at run-time) are, .so in Linux and .dll in Windows. We will soon be covering more points on Dynamic Libraries and steps to create them. This article is compiled by Abhijit Saha and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. aakash nandi Akanksha_Rai memory-management system-programming Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Program for Round Robin scheduling | Set 1 Inter Process Communication (IPC) Introduction of Operating System - Set 1 Semaphores in Process Synchronization Disk Scheduling Algorithms CPU Scheduling in Operating Systems Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Difference between Process and Thread
[ { "code": null, "e": 25657, "s": 25629, "text": "\n14 Oct, 2019" }, { "code": null, "e": 26159, "s": 25657, "text": "When a C program is compiled, the compiler generates object code. After generating the object code, the compiler also invokes linker. One of the main tasks for linker is to make code of library functions (eg printf(), scanf(), sqrt(), ..etc) available to your program. A linker can accomplish this task in two ways, by copying the code of library function to your object code, or by making some arrangements so that the complete code of library functions is not copied, but made available at run-time." }, { "code": null, "e": 26497, "s": 26159, "text": "Static Linking and Static Libraries is the result of the linker making copy of all used library functions to the executable file. Static Linking creates larger binary files, and need more space on disk and main memory. Examples of static libraries (libraries which are statically linked) are, .a files in Linux and .lib files in Windows." }, { "code": null, "e": 26653, "s": 26497, "text": "Steps to create a static library Let us create and use a Static Library in UNIX or UNIX like OS.1. Create a C file that contains functions in your library." }, { "code": "/* Filename: lib_mylib.c */#include <stdio.h>void fun(void){ printf(\"fun() called from a static library\");}", "e": 26762, "s": 26653, "text": null }, { "code": null, "e": 26856, "s": 26762, "text": "We have created only one file for simplicity. We can also create multiple files in a library." }, { "code": null, "e": 26896, "s": 26856, "text": "2. Create a header file for the library" }, { "code": "/* Filename: lib_mylib.h */void fun(void);", "e": 26939, "s": 26896, "text": null }, { "code": null, "e": 26965, "s": 26939, "text": "3. Compile library files." }, { "code": null, "e": 27001, "s": 26965, "text": " gcc -c lib_mylib.c -o lib_mylib.o " }, { "code": null, "e": 27159, "s": 27001, "text": "4. Create static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is static library." }, { "code": null, "e": 27192, "s": 27159, "text": " ar rcs lib_mylib.a lib_mylib.o " }, { "code": null, "e": 27375, "s": 27192, "text": "5. Now our static library is ready to use. At this point we could just copy lib_mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory." }, { "code": null, "e": 27483, "s": 27375, "text": "Let us create a driver program that uses above created static library.1. Create a C file with main function" }, { "code": "/* filename: driver.c */#include \"lib_mylib.h\"void main() { fun();}", "e": 27553, "s": 27483, "text": null }, { "code": null, "e": 27584, "s": 27553, "text": "2. Compile the driver program." }, { "code": null, "e": 27612, "s": 27584, "text": "gcc -c driver.c -o driver.o" }, { "code": null, "e": 27791, "s": 27612, "text": "3. Link the compiled driver program to the static library. Note that -L. is used to tell that the static library is in current folder (See this for details of -L and -l options)." }, { "code": null, "e": 27827, "s": 27791, "text": "gcc -o driver driver.o -L. -l_mylib" }, { "code": null, "e": 27853, "s": 27827, "text": "4. Run the driver program" }, { "code": null, "e": 27898, "s": 27853, "text": "./driver \nfun() called from a static library" }, { "code": null, "e": 28130, "s": 27898, "text": "Following are some important points about static libraries.1. For a static library, the actual code is extracted from the library by the linker and used to build the final executable at the point you compile/build your application." }, { "code": null, "e": 28524, "s": 28130, "text": "2. Each process gets its own copy of the code and data. Where as in case of dynamic libraries it is only code shared, data is specific to each process. For static libraries memory footprints are larger. For example, if all the window system tools were statically linked, several tens of megabytes of RAM would be wasted for a typical user, and the user would be slowed down by a lot of paging." }, { "code": null, "e": 28843, "s": 28524, "text": "3. Since library code is connected at compile time, the final executable has no dependencies on the library at run time i.e. no additional run-time loading costs, it means that you don’t need to carry along a copy of the library that is being used and you have everything under your control and there is no dependency." }, { "code": null, "e": 29026, "s": 28843, "text": "4. In static libraries, once everything is bundled into your application, you don’t have to worry that the client will have the right library (and version) available on their system." }, { "code": null, "e": 29171, "s": 29026, "text": "5. One drawback of static libraries is, for any change(up-gradation) in the static libraries, you have to recompile the main program every time." }, { "code": null, "e": 29380, "s": 29171, "text": "6. One major advantage of static libraries being preferred even now “is speed”. There will be no dynamic querying of symbols in static libraries. Many production line software use static libraries even today." }, { "code": null, "e": 29759, "s": 29380, "text": "Dynamic linking and Dynamic Libraries Dynamic Linking doesn’t require the code to be copied, it is done by just placing name of the library in the binary file. The actual linking happens when the program is run, when both the binary file and the library are in memory. Examples of Dynamic libraries (libraries which are linked at run-time) are, .so in Linux and .dll in Windows." }, { "code": null, "e": 29843, "s": 29759, "text": "We will soon be covering more points on Dynamic Libraries and steps to create them." }, { "code": null, "e": 30045, "s": 29843, "text": "This article is compiled by Abhijit Saha and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30058, "s": 30045, "text": "aakash nandi" }, { "code": null, "e": 30071, "s": 30058, "text": "Akanksha_Rai" }, { "code": null, "e": 30089, "s": 30071, "text": "memory-management" }, { "code": null, "e": 30108, "s": 30089, "text": "system-programming" }, { "code": null, "e": 30126, "s": 30108, "text": "Operating Systems" }, { "code": null, "e": 30144, "s": 30126, "text": "Operating Systems" }, { "code": null, "e": 30242, "s": 30144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30282, "s": 30242, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 30309, "s": 30282, "text": "Paging in Operating System" }, { "code": null, "e": 30352, "s": 30309, "text": "Program for Round Robin scheduling | Set 1" }, { "code": null, "e": 30386, "s": 30352, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 30427, "s": 30386, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 30465, "s": 30427, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 30492, "s": 30465, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 30528, "s": 30492, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 30609, "s": 30528, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" } ]
Find missing elements of a range - GeeksforGeeks
20 Apr, 2022 Given an array, arr[0..n-1] of distinct elements and a range [low, high], find all numbers that are in a range, but not the array. The missing elements should be printed in sorted order. Examples: Input: arr[] = {10, 12, 11, 15}, low = 10, high = 15 Output: 13, 14 Input: arr[] = {1, 14, 11, 51, 15}, low = 50, high = 55 Output: 50, 52, 53, 54 There can be two approaches to solve the problem. Use Sorting: Sort the array, then do a binary search for ‘low’. Once the location of low is found, start traversing the array from that location and keep printing all missing numbers. C++ Java Python3 C# // A sorting based C++ program to find missing// elements from an array#include <bits/stdc++.h>using namespace std; // Print all elements of range [low, high] that// are not present in arr[0..n-1]void printMissing(int arr[], int n, int low, int high){ // Sort the array sort(arr, arr + n); // Do binary search for 'low' in sorted // array and find index of first element // which either equal to or greater than // low. int* ptr = lower_bound(arr, arr + n, low); int index = ptr - arr; // Start from the found index and linearly // search every range element x after this // index in arr[] int i = index, x = low; while (i < n && x <= high) { // If x doesn't match with current element // print it if (arr[i] != x) cout << x << " "; // If x matches, move to next element in arr[] else i++; // Move to next element in range [low, high] x++; } // Print range elements that are greater than the // last element of sorted array. while (x <= high) cout << x++ << " ";} // Driver programint main(){ int arr[] = { 1, 3, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int low = 1, high = 10; printMissing(arr, n, low, high); return 0;} // A sorting based Java program to find missing// elements from an array import java.util.Arrays; public class PrintMissing { // Print all elements of range [low, high] that // are not present in arr[0..n-1] static void printMissing(int ar[], int low, int high) { Arrays.sort(ar); // Do binary search for 'low' in sorted // array and find index of first element // which either equal to or greater than // low. int index = ceilindex(ar, low, 0, ar.length - 1); int x = low; // Start from the found index and linearly // search every range element x after this // index in arr[] while (index < ar.length && x <= high) { // If x doesn't match with current element // print it if (ar[index] != x) { System.out.print(x + " "); } // If x matches, move to next element in arr[] else index++; // Move to next element in range [low, high] x++; } // Print range elements that are greater than the // last element of sorted array. while (x <= high) { System.out.print(x + " "); x++; } } // Utility function to find ceil index of given element static int ceilindex(int ar[], int val, int low, int high) { if (val < ar[0]) return 0; if (val > ar[ar.length - 1]) return ar.length; int mid = (low + high) / 2; if (ar[mid] == val) return mid; if (ar[mid] < val) { if (mid + 1 < high && ar[mid + 1] >= val) return mid + 1; return ceilindex(ar, val, mid + 1, high); } else { if (mid - 1 >= low && ar[mid - 1] < val) return mid; return ceilindex(ar, val, low, mid - 1); } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed by Rishabh Mahrsee # Python library for binary searchfrom bisect import bisect_left # A sorting based C++ program to find missing# elements from an array # Print all elements of range [low, high] that# are not present in arr[0..n-1] def printMissing(arr, n, low, high): # Sort the array arr.sort() # Do binary search for 'low' in sorted # array and find index of first element # which either equal to or greater than # low. ptr = bisect_left(arr, low) index = ptr # Start from the found index and linearly # search every range element x after this # index in arr[] i = index x = low while (i < n and x <= high): # If x doesn't match with current element # print it if(arr[i] != x): print(x, end =" ") # If x matches, move to next element in arr[] else: i = i + 1 # Move to next element in range [low, high] x = x + 1 # Print range elements that are greater than the # last element of sorted array. while (x <= high): print(x, end =" ") x = x + 1 # Driver code arr = [1, 3, 5, 4]n = len(arr)low = 1high = 10printMissing(arr, n, low, high); # This code is contributed by YatinGupta // A sorting based Java program to// find missing elements from an arrayusing System; class GFG { // Print all elements of range // [low, high] that are not // present in arr[0..n-1] static void printMissing(int[] ar, int low, int high) { Array.Sort(ar); // Do binary search for 'low' in sorted // array and find index of first element // which either equal to or greater than // low. int index = ceilindex(ar, low, 0, ar.Length - 1); int x = low; // Start from the found index and linearly // search every range element x after this // index in arr[] while (index < ar.Length && x <= high) { // If x doesn't match with current // element print it if (ar[index] != x) { Console.Write(x + " "); } // If x matches, move to next // element in arr[] else index++; // Move to next element in // range [low, high] x++; } // Print range elements that // are greater than the // last element of sorted array. while (x <= high) { Console.Write(x + " "); x++; } } // Utility function to find // ceil index of given element static int ceilindex(int[] ar, int val, int low, int high) { if (val < ar[0]) return 0; if (val > ar[ar.Length - 1]) return ar.Length; int mid = (low + high) / 2; if (ar[mid] == val) return mid; if (ar[mid] < val) { if (mid + 1 < high && ar[mid + 1] >= val) return mid + 1; return ceilindex(ar, val, mid + 1, high); } else { if (mid - 1 >= low && ar[mid - 1] < val) return mid; return ceilindex(ar, val, low, mid - 1); } } // Driver Code static public void Main() { int[] arr = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed// by Sach_Code Output: 2 6 7 8 9 10 Time Complexity: O(n log n + k) where k is the number of missing elements Auxiliary Space: O(n) or O(1) depending on the type of the array. Using Arrays: Create a boolean array, where each index will represent whether the (i+low)th element is present in the array or not. Mark all those elements which are in the given range and are present in the array. Once all array items present in the given range have been marked true in the array, we traverse through the boolean array and print all elements whose value is false. C++14 Java Python3 C# Javascript // An array based C++ program// to find missing elements from// an array#include <bits/stdc++.h>using namespace std; // Print all elements of range// [low, high] that are not present// in arr[0..n-1]void printMissing( int arr[], int n, int low, int high){ // Create boolean array of size // high-low+1, each index i representing // whether (i+low)th element found or not. bool points_of_range[high - low + 1] = { false }; for (int i = 0; i < n; i++) { // if ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and // print all elements whose value // is false for (int x = 0; x <= high - low; x++) { if (points_of_range[x] == false) cout << low + x << " "; }} // Driver programint main(){ int arr[] = { 1, 3, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int low = 1, high = 10; printMissing(arr, n, low, high); return 0;} // This code is contributed by Shubh Bansal // An array based Java program// to find missing elements from// an array import java.util.Arrays; public class Print { // Print all elements of range // [low, high] that are not present // in arr[0..n-1] static void printMissing( int arr[], int low, int high) { // Create boolean array of // size high-low+1, each index i // representing whether (i+low)th // element found or not. boolean[] points_of_range = new boolean [high - low + 1]; for (int i = 0; i < arr.length; i++) { // if ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and print all // elements whose value is false for (int x = 0; x <= high - low; x++) { if (points_of_range[x] == false) System.out.print((low + x) + " "); } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed by Shubh Bansal # An array-based Python3 program to# find missing elements from an array # Print all elements of range# [low, high] that are not# present in arr[0..n-1]def printMissing(arr, n, low, high): # Create boolean list of size # high-low+1, each index i # representing whether (i+low)th # element found or not. points_of_range = [False] * (high-low+1) for i in range(n) : # if ith element of arr is in range # low to high then mark corresponding # index as true in array if ( low <= arr[i] and arr[i] <= high ) : points_of_range[arr[i]-low] = True # Traverse through the range # and print all elements whose value # is false for x in range(high-low+1) : if (points_of_range[x]==False) : print(low+x, end = " ") # Driver Codearr = [1, 3, 5, 4]n = len(arr)low, high = 1, 10printMissing(arr, n, low, high) # This code is contributed# by Shubh Bansal // An array based C# program// to find missing elements from// an arrayusing System; class GFG{ // Print all elements of range// [low, high] that are not present// in arr[0..n-1]static void printMissing(int[] arr, int n, int low, int high){ // Create boolean array of size // high-low+1, each index i representing // whether (i+low)th element found or not. bool[] points_of_range = new bool[high - low + 1]; for(int i = 0; i < high - low + 1; i++) points_of_range[i] = false; for(int i = 0; i < n; i++) { // If ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and // print all elements whose value // is false for(int x = 0; x <= high - low; x++) { if (points_of_range[x] == false) Console.Write("{0} ", low + x); }} // Driver codepublic static void Main(){ int[] arr = { 1, 3, 5, 4 }; int n = arr.Length; int low = 1, high = 10; printMissing(arr, n, low, high);}} // This code is contributed by subhammahato348 <script> // Javascript program to find missing elements from// an array // Print all elements of range // [low, high] that are not present // in arr[0..n-1] function printMissing( arr, low, high) { // Create boolean array of // size high-low+1, each index i // representing whether (i+low)th // element found or not. let points_of_range = Array(high - low + 1).fill(0); for (let i = 0; i < arr.length; i++) { // if ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and print all // elements whose value is false for (let x = 0; x <= high - low; x++) { if (points_of_range[x] == false) document.write((low + x) + " "); } } // Driver program let arr = [ 1, 3, 5, 4 ]; let low = 1, high = 10; printMissing(arr, low, high); </script> Output: 2 6 7 8 9 10 Time Complexity: O(n + (high-low+1)) Auxiliary Space: O(n) Use Hashing: Create a hash table and insert all array items into the hash table. Once all items are in hash table, traverse through the range and print all missing elements. C++ Java Python3 C# // A hashing based C++ program to find missing// elements from an array#include <bits/stdc++.h>using namespace std; // Print all elements of range [low, high] that// are not present in arr[0..n-1]void printMissing(int arr[], int n, int low, int high){ // Insert all elements of arr[] in set unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); // Traverse through the range an print all // missing elements for (int x = low; x <= high; x++) if (s.find(x) == s.end()) cout << x << " ";} // Driver programint main(){ int arr[] = { 1, 3, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int low = 1, high = 10; printMissing(arr, n, low, high); return 0;} // A hashing based Java program to find missing// elements from an array import java.util.Arrays;import java.util.HashSet; public class Print { // Print all elements of range [low, high] that // are not present in arr[0..n-1] static void printMissing(int ar[], int low, int high) { HashSet<Integer> hs = new HashSet<>(); // Insert all elements of arr[] in set for (int i = 0; i < ar.length; i++) hs.add(ar[i]); // Traverse through the range an print all // missing elements for (int i = low; i <= high; i++) { if (!hs.contains(i)) { System.out.print(i + " "); } } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed by Rishabh Mahrsee # A hashing based Python3 program to# find missing elements from an array # Print all elements of range# [low, high] that are not# present in arr[0..n-1]def printMissing(arr, n, low, high): # Insert all elements of # arr[] in set s = set(arr) # Traverse through the range # and print all missing elements for x in range(low, high + 1): if x not in s: print(x, end = ' ') # Driver Codearr = [1, 3, 5, 4]n = len(arr)low, high = 1, 10printMissing(arr, n, low, high) # This code is contributed# by SamyuktaSHegde // A hashing based C# program to// find missing elements from an arrayusing System;using System.Collections.Generic; class GFG { // Print all elements of range // [low, high] that are not // present in arr[0..n-1] static void printMissing(int[] arr, int n, int low, int high) { // Insert all elements of arr[] in set HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { s.Add(arr[i]); } // Traverse through the range // an print all missing elements for (int x = low; x <= high; x++) if (!s.Contains(x)) Console.Write(x + " "); } // Driver Code public static void Main() { int[] arr = { 1, 3, 5, 4 }; int n = arr.Length; int low = 1, high = 10; printMissing(arr, n, low, high); }} // This code is contributed by ihritik Output: 2 6 7 8 9 10 Time Complexity: O(n + (high-low+1)) Auxiliary Space: O(n) Which approach is better? The time complexity of the first approach is O(nLogn + k) where k is the number of missing elements (Note that k may be more than n Log n if the array is small and the range is big)The time complexity of the second and third solutions is O(n + (high-low+1)). If the given array has almost all elements of the range, i.e., n is close to the value of (high-low+1), then the second and third approaches are definitely better as there is no Log n factor. But if n is much smaller than the range, then the first approach is better as it doesn’t require extra space for hashing. We can also modify the first approach to print adjacent missing elements as range to save time. For example, if 50, 51, 52, 53, 54, 59 are missing, we can print them as 50-54, 59 in the first method. And if printing this way is allowed, the first approach takes only O(n Log n) time. Out of the Second and Third Solutions, the second solution is better because the worst-case time complexity of the second solution is better than the third. This article is contributed by Piyush Gupta and Shubh Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ihritik Sach_Code SamyuktaSHegde YatinGupta 00shubhbansal subhammahato348 ManasChhabra2 target_2 clintra simranarora5sos amartyaniel20 arorakashish0911 prophet1999 simmytarika5 limited-range-elements Hash Sorting Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Counting frequencies of array elements Most frequent element in an array Sorting a Map by value in C++ STL Longest Consecutive Subsequence
[ { "code": null, "e": 26745, "s": 26717, "text": "\n20 Apr, 2022" }, { "code": null, "e": 26932, "s": 26745, "text": "Given an array, arr[0..n-1] of distinct elements and a range [low, high], find all numbers that are in a range, but not the array. The missing elements should be printed in sorted order." }, { "code": null, "e": 26944, "s": 26932, "text": "Examples: " }, { "code": null, "e": 27108, "s": 26944, "text": "Input: arr[] = {10, 12, 11, 15}, \n low = 10, high = 15\nOutput: 13, 14\n\nInput: arr[] = {1, 14, 11, 51, 15}, \n low = 50, high = 55\nOutput: 50, 52, 53, 54" }, { "code": null, "e": 27159, "s": 27108, "text": "There can be two approaches to solve the problem. " }, { "code": null, "e": 27343, "s": 27159, "text": "Use Sorting: Sort the array, then do a binary search for ‘low’. Once the location of low is found, start traversing the array from that location and keep printing all missing numbers." }, { "code": null, "e": 27347, "s": 27343, "text": "C++" }, { "code": null, "e": 27352, "s": 27347, "text": "Java" }, { "code": null, "e": 27360, "s": 27352, "text": "Python3" }, { "code": null, "e": 27363, "s": 27360, "text": "C#" }, { "code": "// A sorting based C++ program to find missing// elements from an array#include <bits/stdc++.h>using namespace std; // Print all elements of range [low, high] that// are not present in arr[0..n-1]void printMissing(int arr[], int n, int low, int high){ // Sort the array sort(arr, arr + n); // Do binary search for 'low' in sorted // array and find index of first element // which either equal to or greater than // low. int* ptr = lower_bound(arr, arr + n, low); int index = ptr - arr; // Start from the found index and linearly // search every range element x after this // index in arr[] int i = index, x = low; while (i < n && x <= high) { // If x doesn't match with current element // print it if (arr[i] != x) cout << x << \" \"; // If x matches, move to next element in arr[] else i++; // Move to next element in range [low, high] x++; } // Print range elements that are greater than the // last element of sorted array. while (x <= high) cout << x++ << \" \";} // Driver programint main(){ int arr[] = { 1, 3, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int low = 1, high = 10; printMissing(arr, n, low, high); return 0;}", "e": 28656, "s": 27363, "text": null }, { "code": "// A sorting based Java program to find missing// elements from an array import java.util.Arrays; public class PrintMissing { // Print all elements of range [low, high] that // are not present in arr[0..n-1] static void printMissing(int ar[], int low, int high) { Arrays.sort(ar); // Do binary search for 'low' in sorted // array and find index of first element // which either equal to or greater than // low. int index = ceilindex(ar, low, 0, ar.length - 1); int x = low; // Start from the found index and linearly // search every range element x after this // index in arr[] while (index < ar.length && x <= high) { // If x doesn't match with current element // print it if (ar[index] != x) { System.out.print(x + \" \"); } // If x matches, move to next element in arr[] else index++; // Move to next element in range [low, high] x++; } // Print range elements that are greater than the // last element of sorted array. while (x <= high) { System.out.print(x + \" \"); x++; } } // Utility function to find ceil index of given element static int ceilindex(int ar[], int val, int low, int high) { if (val < ar[0]) return 0; if (val > ar[ar.length - 1]) return ar.length; int mid = (low + high) / 2; if (ar[mid] == val) return mid; if (ar[mid] < val) { if (mid + 1 < high && ar[mid + 1] >= val) return mid + 1; return ceilindex(ar, val, mid + 1, high); } else { if (mid - 1 >= low && ar[mid - 1] < val) return mid; return ceilindex(ar, val, low, mid - 1); } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed by Rishabh Mahrsee", "e": 30808, "s": 28656, "text": null }, { "code": "# Python library for binary searchfrom bisect import bisect_left # A sorting based C++ program to find missing# elements from an array # Print all elements of range [low, high] that# are not present in arr[0..n-1] def printMissing(arr, n, low, high): # Sort the array arr.sort() # Do binary search for 'low' in sorted # array and find index of first element # which either equal to or greater than # low. ptr = bisect_left(arr, low) index = ptr # Start from the found index and linearly # search every range element x after this # index in arr[] i = index x = low while (i < n and x <= high): # If x doesn't match with current element # print it if(arr[i] != x): print(x, end =\" \") # If x matches, move to next element in arr[] else: i = i + 1 # Move to next element in range [low, high] x = x + 1 # Print range elements that are greater than the # last element of sorted array. while (x <= high): print(x, end =\" \") x = x + 1 # Driver code arr = [1, 3, 5, 4]n = len(arr)low = 1high = 10printMissing(arr, n, low, high); # This code is contributed by YatinGupta", "e": 32007, "s": 30808, "text": null }, { "code": "// A sorting based Java program to// find missing elements from an arrayusing System; class GFG { // Print all elements of range // [low, high] that are not // present in arr[0..n-1] static void printMissing(int[] ar, int low, int high) { Array.Sort(ar); // Do binary search for 'low' in sorted // array and find index of first element // which either equal to or greater than // low. int index = ceilindex(ar, low, 0, ar.Length - 1); int x = low; // Start from the found index and linearly // search every range element x after this // index in arr[] while (index < ar.Length && x <= high) { // If x doesn't match with current // element print it if (ar[index] != x) { Console.Write(x + \" \"); } // If x matches, move to next // element in arr[] else index++; // Move to next element in // range [low, high] x++; } // Print range elements that // are greater than the // last element of sorted array. while (x <= high) { Console.Write(x + \" \"); x++; } } // Utility function to find // ceil index of given element static int ceilindex(int[] ar, int val, int low, int high) { if (val < ar[0]) return 0; if (val > ar[ar.Length - 1]) return ar.Length; int mid = (low + high) / 2; if (ar[mid] == val) return mid; if (ar[mid] < val) { if (mid + 1 < high && ar[mid + 1] >= val) return mid + 1; return ceilindex(ar, val, mid + 1, high); } else { if (mid - 1 >= low && ar[mid - 1] < val) return mid; return ceilindex(ar, val, low, mid - 1); } } // Driver Code static public void Main() { int[] arr = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed// by Sach_Code", "e": 34214, "s": 32007, "text": null }, { "code": null, "e": 34223, "s": 34214, "text": "Output: " }, { "code": null, "e": 34236, "s": 34223, "text": "2 6 7 8 9 10" }, { "code": null, "e": 34310, "s": 34236, "text": "Time Complexity: O(n log n + k) where k is the number of missing elements" }, { "code": null, "e": 34377, "s": 34310, "text": "Auxiliary Space: O(n) or O(1) depending on the type of the array. " }, { "code": null, "e": 34759, "s": 34377, "text": "Using Arrays: Create a boolean array, where each index will represent whether the (i+low)th element is present in the array or not. Mark all those elements which are in the given range and are present in the array. Once all array items present in the given range have been marked true in the array, we traverse through the boolean array and print all elements whose value is false." }, { "code": null, "e": 34765, "s": 34759, "text": "C++14" }, { "code": null, "e": 34770, "s": 34765, "text": "Java" }, { "code": null, "e": 34778, "s": 34770, "text": "Python3" }, { "code": null, "e": 34781, "s": 34778, "text": "C#" }, { "code": null, "e": 34792, "s": 34781, "text": "Javascript" }, { "code": "// An array based C++ program// to find missing elements from// an array#include <bits/stdc++.h>using namespace std; // Print all elements of range// [low, high] that are not present// in arr[0..n-1]void printMissing( int arr[], int n, int low, int high){ // Create boolean array of size // high-low+1, each index i representing // whether (i+low)th element found or not. bool points_of_range[high - low + 1] = { false }; for (int i = 0; i < n; i++) { // if ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and // print all elements whose value // is false for (int x = 0; x <= high - low; x++) { if (points_of_range[x] == false) cout << low + x << \" \"; }} // Driver programint main(){ int arr[] = { 1, 3, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int low = 1, high = 10; printMissing(arr, n, low, high); return 0;} // This code is contributed by Shubh Bansal", "e": 35924, "s": 34792, "text": null }, { "code": "// An array based Java program// to find missing elements from// an array import java.util.Arrays; public class Print { // Print all elements of range // [low, high] that are not present // in arr[0..n-1] static void printMissing( int arr[], int low, int high) { // Create boolean array of // size high-low+1, each index i // representing whether (i+low)th // element found or not. boolean[] points_of_range = new boolean [high - low + 1]; for (int i = 0; i < arr.length; i++) { // if ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and print all // elements whose value is false for (int x = 0; x <= high - low; x++) { if (points_of_range[x] == false) System.out.print((low + x) + \" \"); } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed by Shubh Bansal", "e": 37223, "s": 35924, "text": null }, { "code": "# An array-based Python3 program to# find missing elements from an array # Print all elements of range# [low, high] that are not# present in arr[0..n-1]def printMissing(arr, n, low, high): # Create boolean list of size # high-low+1, each index i # representing whether (i+low)th # element found or not. points_of_range = [False] * (high-low+1) for i in range(n) : # if ith element of arr is in range # low to high then mark corresponding # index as true in array if ( low <= arr[i] and arr[i] <= high ) : points_of_range[arr[i]-low] = True # Traverse through the range # and print all elements whose value # is false for x in range(high-low+1) : if (points_of_range[x]==False) : print(low+x, end = \" \") # Driver Codearr = [1, 3, 5, 4]n = len(arr)low, high = 1, 10printMissing(arr, n, low, high) # This code is contributed# by Shubh Bansal", "e": 38157, "s": 37223, "text": null }, { "code": "// An array based C# program// to find missing elements from// an arrayusing System; class GFG{ // Print all elements of range// [low, high] that are not present// in arr[0..n-1]static void printMissing(int[] arr, int n, int low, int high){ // Create boolean array of size // high-low+1, each index i representing // whether (i+low)th element found or not. bool[] points_of_range = new bool[high - low + 1]; for(int i = 0; i < high - low + 1; i++) points_of_range[i] = false; for(int i = 0; i < n; i++) { // If ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and // print all elements whose value // is false for(int x = 0; x <= high - low; x++) { if (points_of_range[x] == false) Console.Write(\"{0} \", low + x); }} // Driver codepublic static void Main(){ int[] arr = { 1, 3, 5, 4 }; int n = arr.Length; int low = 1, high = 10; printMissing(arr, n, low, high);}} // This code is contributed by subhammahato348", "e": 39400, "s": 38157, "text": null }, { "code": "<script> // Javascript program to find missing elements from// an array // Print all elements of range // [low, high] that are not present // in arr[0..n-1] function printMissing( arr, low, high) { // Create boolean array of // size high-low+1, each index i // representing whether (i+low)th // element found or not. let points_of_range = Array(high - low + 1).fill(0); for (let i = 0; i < arr.length; i++) { // if ith element of arr is in // range low to high then mark // corresponding index as true in array if (low <= arr[i] && arr[i] <= high) points_of_range[arr[i] - low] = true; } // Traverse through the range and print all // elements whose value is false for (let x = 0; x <= high - low; x++) { if (points_of_range[x] == false) document.write((low + x) + \" \"); } } // Driver program let arr = [ 1, 3, 5, 4 ]; let low = 1, high = 10; printMissing(arr, low, high); </script>", "e": 40512, "s": 39400, "text": null }, { "code": null, "e": 40520, "s": 40512, "text": "Output:" }, { "code": null, "e": 40533, "s": 40520, "text": "2 6 7 8 9 10" }, { "code": null, "e": 40570, "s": 40533, "text": "Time Complexity: O(n + (high-low+1))" }, { "code": null, "e": 40593, "s": 40570, "text": "Auxiliary Space: O(n) " }, { "code": null, "e": 40767, "s": 40593, "text": "Use Hashing: Create a hash table and insert all array items into the hash table. Once all items are in hash table, traverse through the range and print all missing elements." }, { "code": null, "e": 40771, "s": 40767, "text": "C++" }, { "code": null, "e": 40776, "s": 40771, "text": "Java" }, { "code": null, "e": 40784, "s": 40776, "text": "Python3" }, { "code": null, "e": 40787, "s": 40784, "text": "C#" }, { "code": "// A hashing based C++ program to find missing// elements from an array#include <bits/stdc++.h>using namespace std; // Print all elements of range [low, high] that// are not present in arr[0..n-1]void printMissing(int arr[], int n, int low, int high){ // Insert all elements of arr[] in set unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); // Traverse through the range an print all // missing elements for (int x = low; x <= high; x++) if (s.find(x) == s.end()) cout << x << \" \";} // Driver programint main(){ int arr[] = { 1, 3, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int low = 1, high = 10; printMissing(arr, n, low, high); return 0;}", "e": 41527, "s": 40787, "text": null }, { "code": "// A hashing based Java program to find missing// elements from an array import java.util.Arrays;import java.util.HashSet; public class Print { // Print all elements of range [low, high] that // are not present in arr[0..n-1] static void printMissing(int ar[], int low, int high) { HashSet<Integer> hs = new HashSet<>(); // Insert all elements of arr[] in set for (int i = 0; i < ar.length; i++) hs.add(ar[i]); // Traverse through the range an print all // missing elements for (int i = low; i <= high; i++) { if (!hs.contains(i)) { System.out.print(i + \" \"); } } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 3, 5, 4 }; int low = 1, high = 10; printMissing(arr, low, high); }} // This code is contributed by Rishabh Mahrsee", "e": 42455, "s": 41527, "text": null }, { "code": "# A hashing based Python3 program to# find missing elements from an array # Print all elements of range# [low, high] that are not# present in arr[0..n-1]def printMissing(arr, n, low, high): # Insert all elements of # arr[] in set s = set(arr) # Traverse through the range # and print all missing elements for x in range(low, high + 1): if x not in s: print(x, end = ' ') # Driver Codearr = [1, 3, 5, 4]n = len(arr)low, high = 1, 10printMissing(arr, n, low, high) # This code is contributed# by SamyuktaSHegde", "e": 43002, "s": 42455, "text": null }, { "code": "// A hashing based C# program to// find missing elements from an arrayusing System;using System.Collections.Generic; class GFG { // Print all elements of range // [low, high] that are not // present in arr[0..n-1] static void printMissing(int[] arr, int n, int low, int high) { // Insert all elements of arr[] in set HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { s.Add(arr[i]); } // Traverse through the range // an print all missing elements for (int x = low; x <= high; x++) if (!s.Contains(x)) Console.Write(x + \" \"); } // Driver Code public static void Main() { int[] arr = { 1, 3, 5, 4 }; int n = arr.Length; int low = 1, high = 10; printMissing(arr, n, low, high); }} // This code is contributed by ihritik", "e": 43911, "s": 43002, "text": null }, { "code": null, "e": 43919, "s": 43911, "text": "Output:" }, { "code": null, "e": 43932, "s": 43919, "text": "2 6 7 8 9 10" }, { "code": null, "e": 43969, "s": 43932, "text": "Time Complexity: O(n + (high-low+1))" }, { "code": null, "e": 43991, "s": 43969, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 44277, "s": 43991, "text": "Which approach is better? The time complexity of the first approach is O(nLogn + k) where k is the number of missing elements (Note that k may be more than n Log n if the array is small and the range is big)The time complexity of the second and third solutions is O(n + (high-low+1)). " }, { "code": null, "e": 45032, "s": 44277, "text": "If the given array has almost all elements of the range, i.e., n is close to the value of (high-low+1), then the second and third approaches are definitely better as there is no Log n factor. But if n is much smaller than the range, then the first approach is better as it doesn’t require extra space for hashing. We can also modify the first approach to print adjacent missing elements as range to save time. For example, if 50, 51, 52, 53, 54, 59 are missing, we can print them as 50-54, 59 in the first method. And if printing this way is allowed, the first approach takes only O(n Log n) time. Out of the Second and Third Solutions, the second solution is better because the worst-case time complexity of the second solution is better than the third." }, { "code": null, "e": 45219, "s": 45032, "text": "This article is contributed by Piyush Gupta and Shubh Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 45229, "s": 45221, "text": "ihritik" }, { "code": null, "e": 45239, "s": 45229, "text": "Sach_Code" }, { "code": null, "e": 45254, "s": 45239, "text": "SamyuktaSHegde" }, { "code": null, "e": 45265, "s": 45254, "text": "YatinGupta" }, { "code": null, "e": 45279, "s": 45265, "text": "00shubhbansal" }, { "code": null, "e": 45295, "s": 45279, "text": "subhammahato348" }, { "code": null, "e": 45309, "s": 45295, "text": "ManasChhabra2" }, { "code": null, "e": 45318, "s": 45309, "text": "target_2" }, { "code": null, "e": 45326, "s": 45318, "text": "clintra" }, { "code": null, "e": 45342, "s": 45326, "text": "simranarora5sos" }, { "code": null, "e": 45356, "s": 45342, "text": "amartyaniel20" }, { "code": null, "e": 45373, "s": 45356, "text": "arorakashish0911" }, { "code": null, "e": 45385, "s": 45373, "text": "prophet1999" }, { "code": null, "e": 45398, "s": 45385, "text": "simmytarika5" }, { "code": null, "e": 45421, "s": 45398, "text": "limited-range-elements" }, { "code": null, "e": 45426, "s": 45421, "text": "Hash" }, { "code": null, "e": 45434, "s": 45426, "text": "Sorting" }, { "code": null, "e": 45439, "s": 45434, "text": "Hash" }, { "code": null, "e": 45447, "s": 45439, "text": "Sorting" }, { "code": null, "e": 45545, "s": 45447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45584, "s": 45545, "text": "Counting frequencies of array elements" }, { "code": null, "e": 45618, "s": 45584, "text": "Most frequent element in an array" }, { "code": null, "e": 45652, "s": 45618, "text": "Sorting a Map by value in C++ STL" } ]
MongoDB updateOne() Method - db.Collection.updateOne() - GeeksforGeeks
28 Jan, 2021 In MongoDB, updateOne() method updates a first matched document within the collection based on the given query. When you update your document the value of the _id field remains unchanged. This method updates one document at a time and can also add new fields in the given document. It takes three parameters, the first one is the selection criteria to update the document, the second one is the new data to be updated, and the remaining are optional. This method can accept a document that only holds update operator expressions. This method can also accept aggregation pipeline. In this method, if the value of upsert is set to true for the shared collection, then you must include the full shared key in the filter/selection criteria. Or if the value of upsert is not set to true, then you must include an exact match on the _id field. The update operation will fail if this operation changes the size of the document. You can also use this method inside multi-document transactions. Syntax: db.Collection_name.updateOne( {Selection_Criteria}, {$set:{Update_data}}, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [<filterdocument1>, ... ], hint: <document|string> }) Parameters: The first parameter is the Older value in the form of Documents. Documents are a structure created of file and value pairs, similar to JSON objects. The second parameter must contain a $set keyword to update the following specify document value. The third parameter is optional. Optional Parameters: upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method. writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document. collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document. arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array. hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error. Return: This method returns a document that contains the following fields: nMatched: This field contains the number of matched documents. modifiedCount: This field contains the number of modified documents. upsertedId: This field contains the _id for the upserted document. acknowledged: The value of this field is true if write concern was enabled or false if write concern was disabled. Examples: In the following examples, we are working with: Database: gfg Collection: student Document: Four documents contains name and age of the students Example 1: Update the age of the student whose name is Annu db.student.updateOne({name: "Annu"}, {$set:{age:25}}) Here, the first parameter is the document whose value to be changed {name:”Annu”} and the second parameter is set keyword means to set(update) the following first matched key value with the older key value, i.e., from 20 to 24. Example 2: Update the name of the first matched document whose name is Bhannu to Babita db.student.updateOne({name:"Bhannu"},{$set:{name:"Babita"}}) Here, the first parameter is the document whose value to be changed {name:”Bhannu”} and the second parameter is set keyword means to set(update) the following first matched key value with the older key value. Note: Here, the value of the key must be of the same datatype that was defined in the collection. Example 3: Insert a new field in the document using the updateOne method db.student.updateOne({name: "Bhannu"}, {$set:{class: 3}}) Here, a new field is added, i.e., class: 3 in the document of a student whose name is Bhannu. MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Aggregation in MongoDB Mongoose Populate() Method MongoDB - Check the existence of the fields in the specified collection How to build a basic CRUD app with Node.js and ReactJS ? MongoDB - db.collection.Find() Method How to connect MongoDB with ReactJS ? Upsert in MongoDB MongoDB - limit() Method MongoDB - Distinct() Method
[ { "code": null, "e": 25231, "s": 25203, "text": "\n28 Jan, 2021" }, { "code": null, "e": 25682, "s": 25231, "text": "In MongoDB, updateOne() method updates a first matched document within the collection based on the given query. When you update your document the value of the _id field remains unchanged. This method updates one document at a time and can also add new fields in the given document. It takes three parameters, the first one is the selection criteria to update the document, the second one is the new data to be updated, and the remaining are optional." }, { "code": null, "e": 25761, "s": 25682, "text": "This method can accept a document that only holds update operator expressions." }, { "code": null, "e": 25811, "s": 25761, "text": "This method can also accept aggregation pipeline." }, { "code": null, "e": 26069, "s": 25811, "text": "In this method, if the value of upsert is set to true for the shared collection, then you must include the full shared key in the filter/selection criteria. Or if the value of upsert is not set to true, then you must include an exact match on the _id field." }, { "code": null, "e": 26152, "s": 26069, "text": "The update operation will fail if this operation changes the size of the document." }, { "code": null, "e": 26217, "s": 26152, "text": "You can also use this method inside multi-document transactions." }, { "code": null, "e": 26225, "s": 26217, "text": "Syntax:" }, { "code": null, "e": 26255, "s": 26225, "text": "db.Collection_name.updateOne(" }, { "code": null, "e": 26300, "s": 26255, "text": "{Selection_Criteria}, {$set:{Update_data}}, " }, { "code": null, "e": 26302, "s": 26300, "text": "{" }, { "code": null, "e": 26325, "s": 26302, "text": " upsert: <boolean>," }, { "code": null, "e": 26355, "s": 26325, "text": " writeConcern: <document>," }, { "code": null, "e": 26382, "s": 26355, "text": " collation: <document>," }, { "code": null, "e": 26427, "s": 26382, "text": " arrayFilters: [<filterdocument1>, ... ]," }, { "code": null, "e": 26463, "s": 26427, "text": " hint: <document|string> " }, { "code": null, "e": 26466, "s": 26463, "text": "})" }, { "code": null, "e": 26478, "s": 26466, "text": "Parameters:" }, { "code": null, "e": 26627, "s": 26478, "text": "The first parameter is the Older value in the form of Documents. Documents are a structure created of file and value pairs, similar to JSON objects." }, { "code": null, "e": 26724, "s": 26627, "text": "The second parameter must contain a $set keyword to update the following specify document value." }, { "code": null, "e": 26757, "s": 26724, "text": "The third parameter is optional." }, { "code": null, "e": 26778, "s": 26757, "text": "Optional Parameters:" }, { "code": null, "e": 26961, "s": 26778, "text": "upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method." }, { "code": null, "e": 27088, "s": 26961, "text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document." }, { "code": null, "e": 27316, "s": 27088, "text": "collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document." }, { "code": null, "e": 27494, "s": 27316, "text": "arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array." }, { "code": null, "e": 27727, "s": 27494, "text": "hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error." }, { "code": null, "e": 27735, "s": 27727, "text": "Return:" }, { "code": null, "e": 27802, "s": 27735, "text": "This method returns a document that contains the following fields:" }, { "code": null, "e": 27865, "s": 27802, "text": "nMatched: This field contains the number of matched documents." }, { "code": null, "e": 27934, "s": 27865, "text": "modifiedCount: This field contains the number of modified documents." }, { "code": null, "e": 28001, "s": 27934, "text": "upsertedId: This field contains the _id for the upserted document." }, { "code": null, "e": 28116, "s": 28001, "text": "acknowledged: The value of this field is true if write concern was enabled or false if write concern was disabled." }, { "code": null, "e": 28126, "s": 28116, "text": "Examples:" }, { "code": null, "e": 28174, "s": 28126, "text": "In the following examples, we are working with:" }, { "code": null, "e": 28188, "s": 28174, "text": "Database: gfg" }, { "code": null, "e": 28208, "s": 28188, "text": "Collection: student" }, { "code": null, "e": 28271, "s": 28208, "text": "Document: Four documents contains name and age of the students" }, { "code": null, "e": 28331, "s": 28271, "text": "Example 1: Update the age of the student whose name is Annu" }, { "code": null, "e": 28385, "s": 28331, "text": "db.student.updateOne({name: \"Annu\"}, {$set:{age:25}})" }, { "code": null, "e": 28613, "s": 28385, "text": "Here, the first parameter is the document whose value to be changed {name:”Annu”} and the second parameter is set keyword means to set(update) the following first matched key value with the older key value, i.e., from 20 to 24." }, { "code": null, "e": 28701, "s": 28613, "text": "Example 2: Update the name of the first matched document whose name is Bhannu to Babita" }, { "code": null, "e": 28762, "s": 28701, "text": "db.student.updateOne({name:\"Bhannu\"},{$set:{name:\"Babita\"}})" }, { "code": null, "e": 28971, "s": 28762, "text": "Here, the first parameter is the document whose value to be changed {name:”Bhannu”} and the second parameter is set keyword means to set(update) the following first matched key value with the older key value." }, { "code": null, "e": 29069, "s": 28971, "text": "Note: Here, the value of the key must be of the same datatype that was defined in the collection." }, { "code": null, "e": 29142, "s": 29069, "text": "Example 3: Insert a new field in the document using the updateOne method" }, { "code": null, "e": 29200, "s": 29142, "text": "db.student.updateOne({name: \"Bhannu\"}, {$set:{class: 3}})" }, { "code": null, "e": 29294, "s": 29200, "text": "Here, a new field is added, i.e., class: 3 in the document of a student whose name is Bhannu." }, { "code": null, "e": 29309, "s": 29294, "text": "MongoDB-method" }, { "code": null, "e": 29316, "s": 29309, "text": "Picked" }, { "code": null, "e": 29324, "s": 29316, "text": "MongoDB" }, { "code": null, "e": 29422, "s": 29324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29461, "s": 29422, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 29484, "s": 29461, "text": "Aggregation in MongoDB" }, { "code": null, "e": 29511, "s": 29484, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29583, "s": 29511, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 29640, "s": 29583, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 29678, "s": 29640, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 29716, "s": 29678, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 29734, "s": 29716, "text": "Upsert in MongoDB" }, { "code": null, "e": 29759, "s": 29734, "text": "MongoDB - limit() Method" } ]
Minimum number of adjacent swaps to convert a string into its given anagram - GeeksforGeeks
08 Jun, 2021 Given two strings s1 and s2, the task is to find the minimum number of steps required to convert s1 into s2. The only operation allowed is to swap adjacent elements in the first string. Every swap is counted as a single step.Examples: Input: s1 = “abcd”, s2 = “cdab” Output: 4 Swap 2nd and 3rd element, abcd => acbd Swap 1st and 2nd element, acbd => cabd Swap 3rd and 4th element, cabd => cadb Swap 2nd and 3rd element, cadb => cdab Minimum 4 swaps are required.Input: s1 = “abcfdegji”, s2 = “fjiacbdge” Output:17 Approach: Use two pointers i and j for first and second strings respectively. Initialise i and j to 0. Iterate over the first string and find the position j such that s1[j] = s2[i] by incrementing the value to j. Keep on swapping the adjacent elements j and j – 1 and decrement j until it is greater than i. Now the ith element of the first string is equal to the second string, hence increment the value of i. This technique will give the minimum number of steps as there are zero unnecessary swaps.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function that returns true if s1// and s2 are anagrams of each otherbool isAnagram(string s1, string s2){ sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); if (s1 == s2) return 1; return 0;} // Function to return the minimum swaps requiredint CountSteps(string s1, string s2, int size){ int i = 0, j = 0; int result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable char temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result;} // Driver codeint main(){ string s1 = "abcd"; string s2 = "cdab"; int size = s2.size(); // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) cout << CountSteps(s1, s2, size); else cout << -1; return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ // Function that returns true if s1// and s2 are anagrams of each otherstatic boolean isAnagram(String s1, String s2){ s1 = sortString(s1); s2 = sortString(s2); return (s1.equals(s2));} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray);} // Function to return the minimum swaps requiredstatic int CountSteps(char []s1, char[] s2, int size){ int i = 0, j = 0; int result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable char temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result;} // Driver codepublic static void main(String[] args){ String s1 = "abcd"; String s2 = "cdab"; int size = s2.length(); // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) System.out.println(CountSteps(s1.toCharArray(), s2.toCharArray(), size)); else System.out.println(-1);}} // This code is contributed by Rajput-Ji # Python3 implementation of the above approach # Function that returns true if s1# and s2 are anagrams of each otherdef isAnagram(s1, s2) : s1 = list(s1); s2 = list(s2); s1 = s1.sort(); s2 = s2.sort(); if (s1 == s2) : return 1; return 0; # Function to return the minimum swaps requireddef CountSteps(s1, s2, size) : s1 = list(s1); s2 = list(s2); i = 0; j = 0; result = 0; # Iterate over the first string and convert # every element equal to the second string while (i < size) : j = i; # Find index element of first string which # is equal to the ith element of second string while (s1[j] != s2[i]) : j += 1; # Swap adjacent elements in first string so # that element at ith position becomes equal while (i < j) : # Swap elements using temporary variable temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; i += 1; return result; # Driver codeif __name__ == "__main__": s1 = "abcd"; s2 = "cdab"; size = len(s2); # If both the strings are anagrams # of each other then only they # can be made equal if (isAnagram(s1, s2)) : print(CountSteps(s1, s2, size)); else : print(-1); # This code is contributed by AnkitRai01 // C# implementation of the above approachusing System;using System.Linq; class GFG{ // Function that returns true if s1// and s2 are anagrams of each otherstatic Boolean isAnagram(String s1, String s2){ s1 = sortString(s1); s2 = sortString(s2); return (s1.Equals(s2));} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new String(tempArray);} // Function to return the minimum swaps requiredstatic int CountSteps(char []s1, char[] s2, int size){ int i = 0, j = 0; int result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable char temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result;} // Driver codepublic static void Main(String[] args){ String s1 = "abcd"; String s2 = "cdab"; int size = s2.Length; // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) Console.WriteLine(CountSteps(s1.ToCharArray(), s2.ToCharArray(), size)); else Console.WriteLine(-1);}} /* This code is contributed by PrinciRaj1992 */ <script> // Javascript implementation of the above approach // Function that returns true if s1 // and s2 are anagrams of each other function isAnagram(s1, s2) { s1 = sortString(s1); s2 = sortString(s2); return (s1 == s2); } // Method to sort a string alphabetically function sortString(inputString) { // convert input string to char array let tempArray = inputString.split(''); // sort tempArray tempArray.sort(); // return new sorted string return tempArray.join(""); } // Function to return the minimum swaps required function CountSteps(s1, s2, size) { let i = 0, j = 0; let result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable let temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result; } let s1 = "abcd"; let s2 = "cdab"; let size = s2.length; // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) document.write(CountSteps(s1.split(''), s2.split(''), size) + "</br>"); else document.write(-1 + "</br>"); </script> 4 Rajput-Ji ankthon princiraj1992 divyeshrabadiya07 anagram Constructive Algorithms Strings Strings anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Array of Strings in C++ (5 Different Ways to Create) Different methods to reverse a string in C/C++ Convert string to char array in C++ Caesar Cipher in Cryptography Check whether two strings are anagram of each other Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26201, "s": 26173, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26438, "s": 26201, "text": "Given two strings s1 and s2, the task is to find the minimum number of steps required to convert s1 into s2. The only operation allowed is to swap adjacent elements in the first string. Every swap is counted as a single step.Examples: " }, { "code": null, "e": 26719, "s": 26438, "text": "Input: s1 = “abcd”, s2 = “cdab” Output: 4 Swap 2nd and 3rd element, abcd => acbd Swap 1st and 2nd element, acbd => cabd Swap 3rd and 4th element, cabd => cadb Swap 2nd and 3rd element, cadb => cdab Minimum 4 swaps are required.Input: s1 = “abcfdegji”, s2 = “fjiacbdge” Output:17 " }, { "code": null, "e": 27274, "s": 26721, "text": "Approach: Use two pointers i and j for first and second strings respectively. Initialise i and j to 0. Iterate over the first string and find the position j such that s1[j] = s2[i] by incrementing the value to j. Keep on swapping the adjacent elements j and j – 1 and decrement j until it is greater than i. Now the ith element of the first string is equal to the second string, hence increment the value of i. This technique will give the minimum number of steps as there are zero unnecessary swaps.Below is the implementation of the above approach: " }, { "code": null, "e": 27278, "s": 27274, "text": "C++" }, { "code": null, "e": 27283, "s": 27278, "text": "Java" }, { "code": null, "e": 27291, "s": 27283, "text": "Python3" }, { "code": null, "e": 27294, "s": 27291, "text": "C#" }, { "code": null, "e": 27305, "s": 27294, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function that returns true if s1// and s2 are anagrams of each otherbool isAnagram(string s1, string s2){ sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); if (s1 == s2) return 1; return 0;} // Function to return the minimum swaps requiredint CountSteps(string s1, string s2, int size){ int i = 0, j = 0; int result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable char temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result;} // Driver codeint main(){ string s1 = \"abcd\"; string s2 = \"cdab\"; int size = s2.size(); // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) cout << CountSteps(s1, s2, size); else cout << -1; return 0;}", "e": 28716, "s": 27305, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function that returns true if s1// and s2 are anagrams of each otherstatic boolean isAnagram(String s1, String s2){ s1 = sortString(s1); s2 = sortString(s2); return (s1.equals(s2));} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray);} // Function to return the minimum swaps requiredstatic int CountSteps(char []s1, char[] s2, int size){ int i = 0, j = 0; int result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable char temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result;} // Driver codepublic static void main(String[] args){ String s1 = \"abcd\"; String s2 = \"cdab\"; int size = s2.length(); // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) System.out.println(CountSteps(s1.toCharArray(), s2.toCharArray(), size)); else System.out.println(-1);}} // This code is contributed by Rajput-Ji", "e": 30531, "s": 28716, "text": null }, { "code": "# Python3 implementation of the above approach # Function that returns true if s1# and s2 are anagrams of each otherdef isAnagram(s1, s2) : s1 = list(s1); s2 = list(s2); s1 = s1.sort(); s2 = s2.sort(); if (s1 == s2) : return 1; return 0; # Function to return the minimum swaps requireddef CountSteps(s1, s2, size) : s1 = list(s1); s2 = list(s2); i = 0; j = 0; result = 0; # Iterate over the first string and convert # every element equal to the second string while (i < size) : j = i; # Find index element of first string which # is equal to the ith element of second string while (s1[j] != s2[i]) : j += 1; # Swap adjacent elements in first string so # that element at ith position becomes equal while (i < j) : # Swap elements using temporary variable temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; i += 1; return result; # Driver codeif __name__ == \"__main__\": s1 = \"abcd\"; s2 = \"cdab\"; size = len(s2); # If both the strings are anagrams # of each other then only they # can be made equal if (isAnagram(s1, s2)) : print(CountSteps(s1, s2, size)); else : print(-1); # This code is contributed by AnkitRai01", "e": 31972, "s": 30531, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Linq; class GFG{ // Function that returns true if s1// and s2 are anagrams of each otherstatic Boolean isAnagram(String s1, String s2){ s1 = sortString(s1); s2 = sortString(s2); return (s1.Equals(s2));} // Method to sort a string alphabeticallypublic static String sortString(String inputString){ // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new String(tempArray);} // Function to return the minimum swaps requiredstatic int CountSteps(char []s1, char[] s2, int size){ int i = 0, j = 0; int result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable char temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result;} // Driver codepublic static void Main(String[] args){ String s1 = \"abcd\"; String s2 = \"cdab\"; int size = s2.Length; // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) Console.WriteLine(CountSteps(s1.ToCharArray(), s2.ToCharArray(), size)); else Console.WriteLine(-1);}} /* This code is contributed by PrinciRaj1992 */", "e": 33799, "s": 31972, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function that returns true if s1 // and s2 are anagrams of each other function isAnagram(s1, s2) { s1 = sortString(s1); s2 = sortString(s2); return (s1 == s2); } // Method to sort a string alphabetically function sortString(inputString) { // convert input string to char array let tempArray = inputString.split(''); // sort tempArray tempArray.sort(); // return new sorted string return tempArray.join(\"\"); } // Function to return the minimum swaps required function CountSteps(s1, s2, size) { let i = 0, j = 0; let result = 0; // Iterate over the first string and convert // every element equal to the second string while (i < size) { j = i; // Find index element of first string which // is equal to the ith element of second string while (s1[j] != s2[i]) { j += 1; } // Swap adjacent elements in first string so // that element at ith position becomes equal while (i < j) { // Swap elements using temporary variable let temp = s1[j]; s1[j] = s1[j - 1]; s1[j - 1] = temp; j -= 1; result += 1; } i += 1; } return result; } let s1 = \"abcd\"; let s2 = \"cdab\"; let size = s2.length; // If both the strings are anagrams // of each other then only they // can be made equal if (isAnagram(s1, s2)) document.write(CountSteps(s1.split(''), s2.split(''), size) + \"</br>\"); else document.write(-1 + \"</br>\"); </script>", "e": 35635, "s": 33799, "text": null }, { "code": null, "e": 35637, "s": 35635, "text": "4" }, { "code": null, "e": 35649, "s": 35639, "text": "Rajput-Ji" }, { "code": null, "e": 35657, "s": 35649, "text": "ankthon" }, { "code": null, "e": 35671, "s": 35657, "text": "princiraj1992" }, { "code": null, "e": 35689, "s": 35671, "text": "divyeshrabadiya07" }, { "code": null, "e": 35697, "s": 35689, "text": "anagram" }, { "code": null, "e": 35721, "s": 35697, "text": "Constructive Algorithms" }, { "code": null, "e": 35729, "s": 35721, "text": "Strings" }, { "code": null, "e": 35737, "s": 35729, "text": "Strings" }, { "code": null, "e": 35745, "s": 35737, "text": "anagram" }, { "code": null, "e": 35843, "s": 35745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35918, "s": 35843, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 35975, "s": 35918, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 36011, "s": 35975, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 36064, "s": 36011, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 36111, "s": 36064, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 36147, "s": 36111, "text": "Convert string to char array in C++" }, { "code": null, "e": 36177, "s": 36147, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 36229, "s": 36177, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 36290, "s": 36229, "text": "Length of the longest substring without repeating characters" } ]
Intersection of two dataframe in Pandas - Python - GeeksforGeeks
26 Jul, 2020 Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them. Syntax: pd.merge(df1, df2, how) Example 1: import pandas as pd # Creating Data framesdf1 = {'A': [1, 2, 3, 4], 'B': ['abc', 'def', 'efg', 'ghi']} df2 = {'A': [1, 2, 3, 4 ], 'B': ['Geeks', 'For', 'efg', 'ghi'], 'C':['Nikhil', 'Rishabh', 'Rahul', 'Shubham']} d1 = pd.DataFrame(df1)d2 = pd.DataFrame(df2) # Calling merge() functionint_df = pd.merge(d1, d2, how ='inner', on =['A', 'B'])print(int_df) Output: A B C 0 3 efg Rahul 1 4 ghi Shubham Example 2: import pandas as pd # Creating Data framesdf1 = {'A': [1, 2, 3, 4], 'B': ['Geeks', 'For', 'efg', 'ghi']} df2 = {'A': [1, 2, 3, 4 ], 'B': ['Geeks', 'For', 'abc', 'cde'], 'C':['Nikhil', 'Rishabh', 'Rahul', 'Shubham']} d1 = pd.DataFrame(df1)d2 = pd.DataFrame(df2) # Calling merge() functionint_df = pd.merge(d1, d2, how='inner', on=['A', 'B'])print(int_df) Output: A B C 0 1 Geeks Nikhil 1 2 For Rishabh Python pandas-dataFrame Python-pandas 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": 25603, "s": 25575, "text": "\n26 Jul, 2020" }, { "code": null, "e": 25809, "s": 25603, "text": "Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them." }, { "code": null, "e": 25817, "s": 25809, "text": "Syntax:" }, { "code": null, "e": 25841, "s": 25817, "text": "pd.merge(df1, df2, how)" }, { "code": null, "e": 25852, "s": 25841, "text": "Example 1:" }, { "code": "import pandas as pd # Creating Data framesdf1 = {'A': [1, 2, 3, 4], 'B': ['abc', 'def', 'efg', 'ghi']} df2 = {'A': [1, 2, 3, 4 ], 'B': ['Geeks', 'For', 'efg', 'ghi'], 'C':['Nikhil', 'Rishabh', 'Rahul', 'Shubham']} d1 = pd.DataFrame(df1)d2 = pd.DataFrame(df2) # Calling merge() functionint_df = pd.merge(d1, d2, how ='inner', on =['A', 'B'])print(int_df)", "e": 26244, "s": 25852, "text": null }, { "code": null, "e": 26252, "s": 26244, "text": "Output:" }, { "code": null, "e": 26310, "s": 26252, "text": " A B C\n0 3 efg Rahul\n1 4 ghi Shubham\n" }, { "code": null, "e": 26321, "s": 26310, "text": "Example 2:" }, { "code": "import pandas as pd # Creating Data framesdf1 = {'A': [1, 2, 3, 4], 'B': ['Geeks', 'For', 'efg', 'ghi']} df2 = {'A': [1, 2, 3, 4 ], 'B': ['Geeks', 'For', 'abc', 'cde'], 'C':['Nikhil', 'Rishabh', 'Rahul', 'Shubham']} d1 = pd.DataFrame(df1)d2 = pd.DataFrame(df2) # Calling merge() functionint_df = pd.merge(d1, d2, how='inner', on=['A', 'B'])print(int_df)", "e": 26713, "s": 26321, "text": null }, { "code": null, "e": 26721, "s": 26713, "text": "Output:" }, { "code": null, "e": 26785, "s": 26721, "text": " A B C\n0 1 Geeks Nikhil\n1 2 For Rishabh\n" }, { "code": null, "e": 26809, "s": 26785, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26823, "s": 26809, "text": "Python-pandas" }, { "code": null, "e": 26830, "s": 26823, "text": "Python" }, { "code": null, "e": 26928, "s": 26830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26946, "s": 26928, "text": "Python Dictionary" }, { "code": null, "e": 26981, "s": 26946, "text": "Read a file line by line in Python" }, { "code": null, "e": 27013, "s": 26981, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27035, "s": 27013, "text": "Enumerate() in Python" }, { "code": null, "e": 27077, "s": 27035, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27107, "s": 27077, "text": "Iterate over a list in Python" }, { "code": null, "e": 27133, "s": 27107, "text": "Python String | replace()" }, { "code": null, "e": 27162, "s": 27133, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27206, "s": 27162, "text": "Reading and Writing to text files in Python" } ]
What is the difference between fopen modes “r+”, "rw+" and “w+” in PHP? - GeeksforGeeks
07 May, 2020 File handling is a very important part of programming when it comes to making applications. We might require reading input from a file or writing output into a file. File handling in PHP is similar to other programming languages. There are predefined functions that can be used to accomplish the specified task. Check out the Basics of File Handling to know about the functions. Syntax: $<variable_name> = fopen(<file source path>,<access mode>) Difference in the fopen modes r+, rw+ and w+ in PHP r+: Opens a file in read and write mode. File pointer starts at the beginning of the file. w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning. rw+: Opens a file in read and write mode. File pointer starts at the beginning of the file. This mode does not exists in the PHP documentation but it works well. Example: For a better understanding, let us observe the parsing function for fopen. It checks for the first character of the argument, i.e. mode[0]. Depending upon it being r,w,a or x, corresponding mode is identified. It looks for the presence of ‘+’ in the mode argument. If present, it sets the appropriate flags. Therefore, “r+” and “w+” has a difference in the mode of opening the file and placing the file pointer. The “r+” and “rw+” are the same. PHP only cares that the string starts with “r” and has a “+”. The “w” is ignored in “rw+”. Hence, they work the same. PHPAPI int php_stream_parse_fopen_modes(const char *mode, int *open_flags){ int flags; switch (mode[0]) { case 'r': flags = 0; break; case 'w': flags = O_TRUNC|O_CREAT; break; case 'a': flags = O_CREAT|O_APPEND; break; case 'x': flags = O_CREAT|O_EXCL; break; case 'c': flags = O_CREAT; break; default: /* unknown mode */ return FAILURE; } if (strchr(mode, '+')) { flags |= O_RDWR; } else if (flags) { flags |= O_WRONLY; } else { flags |= O_RDONLY; } #if defined(O_CLOEXEC) if (strchr(mode, 'e')) { flags |= O_CLOEXEC; }#endif #if defined(O_NONBLOCK) if (strchr(mode, 'n')) { flags |= O_NONBLOCK; }#endif #if defined(_O_TEXT) && defined(O_BINARY) if (strchr(mode, 't')) { flags |= _O_TEXT; } else { flags |= O_BINARY; }#endif *open_flags = flags; return SUCCESS;} Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26217, "s": 26189, "text": "\n07 May, 2020" }, { "code": null, "e": 26596, "s": 26217, "text": "File handling is a very important part of programming when it comes to making applications. We might require reading input from a file or writing output into a file. File handling in PHP is similar to other programming languages. There are predefined functions that can be used to accomplish the specified task. Check out the Basics of File Handling to know about the functions." }, { "code": null, "e": 26604, "s": 26596, "text": "Syntax:" }, { "code": null, "e": 26663, "s": 26604, "text": "$<variable_name> = fopen(<file source path>,<access mode>)" }, { "code": null, "e": 26715, "s": 26663, "text": "Difference in the fopen modes r+, rw+ and w+ in PHP" }, { "code": null, "e": 26806, "s": 26715, "text": "r+: Opens a file in read and write mode. File pointer starts at the beginning of the file." }, { "code": null, "e": 26988, "s": 26806, "text": "w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning." }, { "code": null, "e": 27150, "s": 26988, "text": "rw+: Opens a file in read and write mode. File pointer starts at the beginning of the file. This mode does not exists in the PHP documentation but it works well." }, { "code": null, "e": 27234, "s": 27150, "text": "Example: For a better understanding, let us observe the parsing function for fopen." }, { "code": null, "e": 27369, "s": 27234, "text": "It checks for the first character of the argument, i.e. mode[0]. Depending upon it being r,w,a or x, corresponding mode is identified." }, { "code": null, "e": 27467, "s": 27369, "text": "It looks for the presence of ‘+’ in the mode argument. If present, it sets the appropriate flags." }, { "code": null, "e": 27722, "s": 27467, "text": "Therefore, “r+” and “w+” has a difference in the mode of opening the file and placing the file pointer. The “r+” and “rw+” are the same. PHP only cares that the string starts with “r” and has a “+”. The “w” is ignored in “rw+”. Hence, they work the same." }, { "code": "PHPAPI int php_stream_parse_fopen_modes(const char *mode, int *open_flags){ int flags; switch (mode[0]) { case 'r': flags = 0; break; case 'w': flags = O_TRUNC|O_CREAT; break; case 'a': flags = O_CREAT|O_APPEND; break; case 'x': flags = O_CREAT|O_EXCL; break; case 'c': flags = O_CREAT; break; default: /* unknown mode */ return FAILURE; } if (strchr(mode, '+')) { flags |= O_RDWR; } else if (flags) { flags |= O_WRONLY; } else { flags |= O_RDONLY; } #if defined(O_CLOEXEC) if (strchr(mode, 'e')) { flags |= O_CLOEXEC; }#endif #if defined(O_NONBLOCK) if (strchr(mode, 'n')) { flags |= O_NONBLOCK; }#endif #if defined(_O_TEXT) && defined(O_BINARY) if (strchr(mode, 't')) { flags |= _O_TEXT; } else { flags |= O_BINARY; }#endif *open_flags = flags; return SUCCESS;}", "e": 28766, "s": 27722, "text": null }, { "code": null, "e": 28773, "s": 28766, "text": "Picked" }, { "code": null, "e": 28777, "s": 28773, "text": "PHP" }, { "code": null, "e": 28794, "s": 28777, "text": "Web Technologies" }, { "code": null, "e": 28821, "s": 28794, "text": "Web technologies Questions" }, { "code": null, "e": 28825, "s": 28821, "text": "PHP" }, { "code": null, "e": 28923, "s": 28825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29005, "s": 28923, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 29047, "s": 29005, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 29074, "s": 29047, "text": "PHP str_replace() Function" }, { "code": null, "e": 29138, "s": 29074, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 29189, "s": 29138, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 29229, "s": 29189, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29262, "s": 29229, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29307, "s": 29262, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29350, "s": 29307, "text": "How to fetch data from an API in ReactJS ?" } ]
Ways of transforming one string to other by removing 0 or more characters - GeeksforGeeks
14 Mar, 2022 Given two sequences A, B, find out number of unique ways in sequence A, to form a subsequence of A that is identical to sequence B. Transformation is meant by converting string A (by removing 0 or more characters) to string B. Examples: Input : A = "abcccdf", B = "abccdf" Output : 3 Explanation : Three ways will be -> "ab.ccdf", "abc.cdf" & "abcc.df" . "." is where character is removed. Input : A = "aabba", B = "ab" Output : 4 Explanation : Four ways will be -> "a.b..", "a..b.", ".ab.." & ".a.b." . "." is where characters are removed. Asked in : Google The idea to solve this problem is using Dynamic Programming. Construct a 2D DP matrix of m*n size, where m is size of string B and n is size of string A. dp[i][j] gives the number of ways of transforming string A[0...j] to B[0...i]. Case 1 : dp[0][j] = 1, since placing B = “” with any substring of A would have only 1 solution which is to delete all characters in A. Case 2 : when i > 0, dp[i][j] can be derived by two cases:Case 2.a : if B[i] != A[j], then the solution would be to ignore the character A[j] and align substring B[0..i] with A[0..(j-1)]. Therefore, dp[i][j] = dp[i][j-1].Case 2.b : if B[i] == A[j], then first we could have the solution in case a), but also we could match the characters B[i] and A[j] and place the rest of them (i.e. B[0..(i-1)] and A[0..(j-1)]. As a result, dp[i][j] = dp[i][j-1] + dp[i-1][j-1]. Case 2.a : if B[i] != A[j], then the solution would be to ignore the character A[j] and align substring B[0..i] with A[0..(j-1)]. Therefore, dp[i][j] = dp[i][j-1]. Case 2.b : if B[i] == A[j], then first we could have the solution in case a), but also we could match the characters B[i] and A[j] and place the rest of them (i.e. B[0..(i-1)] and A[0..(j-1)]. As a result, dp[i][j] = dp[i][j-1] + dp[i-1][j-1]. C++ Java Python3 C# Javascript // C++ program to count the distinct transformation// of one string to other.#include <bits/stdc++.h>using namespace std; int countTransformation(string a, string b){ int n = a.size(), m = b.size(); // If b = "" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) return 1; int dp[m][n]; memset(dp, 0, sizeof(dp)); // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) dp[i][j] = (a[j] == b[i]) ? 1 : 0; else if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + 1; else dp[i][j] = dp[i][j - 1]; } // Filling other rows. else { if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; else dp[i][j] = dp[i][j - 1]; } } } return dp[m - 1][n - 1];} // Driver codeint main(){ string a = "abcccdf", b = "abccdf"; cout << countTransformation(a, b) << endl; return 0;} // Java program to count the// distinct transformation// of one string to other.class GFG { static int countTransformation(String a, String b) { int n = a.length(), m = b.length(); // If b = "" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) { return 1; } int dp[][] = new int[m][n]; // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) { dp[i][j] = (a.charAt(j) == b.charAt(i)) ? 1 : 0; } else if (a.charAt(j) == b.charAt(i)) { dp[i][j] = dp[i][j - 1] + 1; } else { dp[i][j] = dp[i][j - 1]; } } // Filling other rows. else if (a.charAt(j) == b.charAt(i)) { dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; } else { dp[i][j] = dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } // Driver code public static void main(String[] args) { String a = "abcccdf", b = "abccdf"; System.out.println(countTransformation(a, b)); }} // This code is contributed by// PrinciRaj1992 # Python3 program to count the distinct# transformation of one string to other. def countTransformation(a, b): n = len(a) m = len(b) # If b = "" i.e., an empty string. There # is only one way to transform (remove all # characters) if m == 0: return 1 dp = [[0] * (n) for _ in range(m)] # Fill dp[][] in bottom up manner # Traverse all character of b[] for i in range(m): # Traverse all characters of a[] for b[i] for j in range(i, n): # Filling the first row of the dp # matrix. if i == 0: if j == 0: if a[j] == b[i]: dp[i][j] = 1 else: dp[i][j] = 0 else if a[j] == b[i]: dp[i][j] = dp[i][j - 1] + 1 else: dp[i][j] = dp[i][j - 1] # Filling other rows else: if a[j] == b[i]: dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1]) else: dp[i][j] = dp[i][j - 1] return dp[m - 1][n - 1] # Driver Codeif __name__ == "__main__": a = "abcccdf" b = "abccdf" print(countTransformation(a, b)) # This code is contributed by vibhu4agarwal // C# program to count the distinct transformation// of one string to other.using System; class GFG { static int countTransformation(string a, string b) { int n = a.Length, m = b.Length; // If b = "" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) return 1; int[, ] dp = new int[m, n]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) dp[i, j] = 0; // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) dp[i, j] = (a[j] == b[i]) ? 1 : 0; else if (a[j] == b[i]) dp[i, j] = dp[i, j - 1] + 1; else dp[i, j] = dp[i, j - 1]; } // Filling other rows. else { if (a[j] == b[i]) dp[i, j] = dp[i, j - 1] + dp[i - 1, j - 1]; else dp[i, j] = dp[i, j - 1]; } } } return dp[m - 1, n - 1]; } // Driver code static void Main() { string a = "abcccdf", b = "abccdf"; Console.Write(countTransformation(a, b)); }} // This code is contributed by DrRoot_ <script> // JavaScript program to count the// distinct transformation// of one string to other.function countTransformation(a,b) { var n = a.length, m = b.length; // If b = "" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) { return 1; } var dp = new Array (m,n); // Fill dp[][] in bottom up manner // Traverse all character of b[] for (var i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (var j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 1) { if (j == 1) { dp[i,j] = (a[j] == b[i]) ? 1 : 0; } else if (a[j] == b[i]) { dp[i,j] = dp[i,j - 1] + 1; } else { dp[i,j] = dp[i,j - 1]; } } // Filling other rows. else if (a[j] == b[j]) { dp[i,j] = dp[i,j - 1] + dp[i - 1,j - 1]; } else { dp[i,j] = dp[i,j - 1]; } } } return dp[m - 1,n - 1]; } // Driver code var a = "abcccdf", b = "abccdf"; document.write(countTransformation(a, b)); // This code is contributed by shivanisinghss2110</script> Output: 3 Time Complexity: O(n^2) This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. DrRoot_ princiraj1992 gfg_sal_gfg vibhu4agarwal priyanja singh s_madaan25 singghakshay shivanisinghss2110 anikaseth98 gulshankumarar231 simmytarika5 Google Dynamic Programming Strings Google Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Longest Palindromic Substring | Set 1 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26587, "s": 26559, "text": "\n14 Mar, 2022" }, { "code": null, "e": 26814, "s": 26587, "text": "Given two sequences A, B, find out number of unique ways in sequence A, to form a subsequence of A that is identical to sequence B. Transformation is meant by converting string A (by removing 0 or more characters) to string B." }, { "code": null, "e": 26824, "s": 26814, "text": "Examples:" }, { "code": null, "e": 27132, "s": 26824, "text": "Input : A = \"abcccdf\", B = \"abccdf\"\nOutput : 3\nExplanation : Three ways will be -> \"ab.ccdf\", \n\"abc.cdf\" & \"abcc.df\" .\n\".\" is where character is removed. \n\nInput : A = \"aabba\", B = \"ab\"\nOutput : 4\nExplanation : Four ways will be -> \"a.b..\",\n \"a..b.\", \".ab..\" & \".a.b.\" .\n\".\" is where characters are removed." }, { "code": null, "e": 27150, "s": 27132, "text": "Asked in : Google" }, { "code": null, "e": 27304, "s": 27150, "text": "The idea to solve this problem is using Dynamic Programming. Construct a 2D DP matrix of m*n size, where m is size of string B and n is size of string A." }, { "code": null, "e": 27383, "s": 27304, "text": "dp[i][j] gives the number of ways of transforming string A[0...j] to B[0...i]." }, { "code": null, "e": 27518, "s": 27383, "text": "Case 1 : dp[0][j] = 1, since placing B = “” with any substring of A would have only 1 solution which is to delete all characters in A." }, { "code": null, "e": 27983, "s": 27518, "text": "Case 2 : when i > 0, dp[i][j] can be derived by two cases:Case 2.a : if B[i] != A[j], then the solution would be to ignore the character A[j] and align substring B[0..i] with A[0..(j-1)]. Therefore, dp[i][j] = dp[i][j-1].Case 2.b : if B[i] == A[j], then first we could have the solution in case a), but also we could match the characters B[i] and A[j] and place the rest of them (i.e. B[0..(i-1)] and A[0..(j-1)]. As a result, dp[i][j] = dp[i][j-1] + dp[i-1][j-1]." }, { "code": null, "e": 28147, "s": 27983, "text": "Case 2.a : if B[i] != A[j], then the solution would be to ignore the character A[j] and align substring B[0..i] with A[0..(j-1)]. Therefore, dp[i][j] = dp[i][j-1]." }, { "code": null, "e": 28391, "s": 28147, "text": "Case 2.b : if B[i] == A[j], then first we could have the solution in case a), but also we could match the characters B[i] and A[j] and place the rest of them (i.e. B[0..(i-1)] and A[0..(j-1)]. As a result, dp[i][j] = dp[i][j-1] + dp[i-1][j-1]." }, { "code": null, "e": 28395, "s": 28391, "text": "C++" }, { "code": null, "e": 28400, "s": 28395, "text": "Java" }, { "code": null, "e": 28408, "s": 28400, "text": "Python3" }, { "code": null, "e": 28411, "s": 28408, "text": "C#" }, { "code": null, "e": 28422, "s": 28411, "text": "Javascript" }, { "code": "// C++ program to count the distinct transformation// of one string to other.#include <bits/stdc++.h>using namespace std; int countTransformation(string a, string b){ int n = a.size(), m = b.size(); // If b = \"\" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) return 1; int dp[m][n]; memset(dp, 0, sizeof(dp)); // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) dp[i][j] = (a[j] == b[i]) ? 1 : 0; else if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + 1; else dp[i][j] = dp[i][j - 1]; } // Filling other rows. else { if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; else dp[i][j] = dp[i][j - 1]; } } } return dp[m - 1][n - 1];} // Driver codeint main(){ string a = \"abcccdf\", b = \"abccdf\"; cout << countTransformation(a, b) << endl; return 0;}", "e": 29744, "s": 28422, "text": null }, { "code": "// Java program to count the// distinct transformation// of one string to other.class GFG { static int countTransformation(String a, String b) { int n = a.length(), m = b.length(); // If b = \"\" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) { return 1; } int dp[][] = new int[m][n]; // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) { dp[i][j] = (a.charAt(j) == b.charAt(i)) ? 1 : 0; } else if (a.charAt(j) == b.charAt(i)) { dp[i][j] = dp[i][j - 1] + 1; } else { dp[i][j] = dp[i][j - 1]; } } // Filling other rows. else if (a.charAt(j) == b.charAt(i)) { dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; } else { dp[i][j] = dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } // Driver code public static void main(String[] args) { String a = \"abcccdf\", b = \"abccdf\"; System.out.println(countTransformation(a, b)); }} // This code is contributed by// PrinciRaj1992", "e": 31435, "s": 29744, "text": null }, { "code": "# Python3 program to count the distinct# transformation of one string to other. def countTransformation(a, b): n = len(a) m = len(b) # If b = \"\" i.e., an empty string. There # is only one way to transform (remove all # characters) if m == 0: return 1 dp = [[0] * (n) for _ in range(m)] # Fill dp[][] in bottom up manner # Traverse all character of b[] for i in range(m): # Traverse all characters of a[] for b[i] for j in range(i, n): # Filling the first row of the dp # matrix. if i == 0: if j == 0: if a[j] == b[i]: dp[i][j] = 1 else: dp[i][j] = 0 else if a[j] == b[i]: dp[i][j] = dp[i][j - 1] + 1 else: dp[i][j] = dp[i][j - 1] # Filling other rows else: if a[j] == b[i]: dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1]) else: dp[i][j] = dp[i][j - 1] return dp[m - 1][n - 1] # Driver Codeif __name__ == \"__main__\": a = \"abcccdf\" b = \"abccdf\" print(countTransformation(a, b)) # This code is contributed by vibhu4agarwal", "e": 32742, "s": 31435, "text": null }, { "code": "// C# program to count the distinct transformation// of one string to other.using System; class GFG { static int countTransformation(string a, string b) { int n = a.Length, m = b.Length; // If b = \"\" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) return 1; int[, ] dp = new int[m, n]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) dp[i, j] = 0; // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) dp[i, j] = (a[j] == b[i]) ? 1 : 0; else if (a[j] == b[i]) dp[i, j] = dp[i, j - 1] + 1; else dp[i, j] = dp[i, j - 1]; } // Filling other rows. else { if (a[j] == b[i]) dp[i, j] = dp[i, j - 1] + dp[i - 1, j - 1]; else dp[i, j] = dp[i, j - 1]; } } } return dp[m - 1, n - 1]; } // Driver code static void Main() { string a = \"abcccdf\", b = \"abccdf\"; Console.Write(countTransformation(a, b)); }} // This code is contributed by DrRoot_", "e": 34334, "s": 32742, "text": null }, { "code": "<script> // JavaScript program to count the// distinct transformation// of one string to other.function countTransformation(a,b) { var n = a.length, m = b.length; // If b = \"\" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) { return 1; } var dp = new Array (m,n); // Fill dp[][] in bottom up manner // Traverse all character of b[] for (var i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (var j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 1) { if (j == 1) { dp[i,j] = (a[j] == b[i]) ? 1 : 0; } else if (a[j] == b[i]) { dp[i,j] = dp[i,j - 1] + 1; } else { dp[i,j] = dp[i,j - 1]; } } // Filling other rows. else if (a[j] == b[j]) { dp[i,j] = dp[i,j - 1] + dp[i - 1,j - 1]; } else { dp[i,j] = dp[i,j - 1]; } } } return dp[m - 1,n - 1]; } // Driver code var a = \"abcccdf\", b = \"abccdf\"; document.write(countTransformation(a, b)); // This code is contributed by shivanisinghss2110</script>", "e": 35866, "s": 34334, "text": null }, { "code": null, "e": 35874, "s": 35866, "text": "Output:" }, { "code": null, "e": 35876, "s": 35874, "text": "3" }, { "code": null, "e": 35900, "s": 35876, "text": "Time Complexity: O(n^2)" }, { "code": null, "e": 36320, "s": 35900, "text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 36328, "s": 36320, "text": "DrRoot_" }, { "code": null, "e": 36342, "s": 36328, "text": "princiraj1992" }, { "code": null, "e": 36354, "s": 36342, "text": "gfg_sal_gfg" }, { "code": null, "e": 36368, "s": 36354, "text": "vibhu4agarwal" }, { "code": null, "e": 36383, "s": 36368, "text": "priyanja singh" }, { "code": null, "e": 36394, "s": 36383, "text": "s_madaan25" }, { "code": null, "e": 36407, "s": 36394, "text": "singghakshay" }, { "code": null, "e": 36426, "s": 36407, "text": "shivanisinghss2110" }, { "code": null, "e": 36438, "s": 36426, "text": "anikaseth98" }, { "code": null, "e": 36456, "s": 36438, "text": "gulshankumarar231" }, { "code": null, "e": 36469, "s": 36456, "text": "simmytarika5" }, { "code": null, "e": 36476, "s": 36469, "text": "Google" }, { "code": null, "e": 36496, "s": 36476, "text": "Dynamic Programming" }, { "code": null, "e": 36504, "s": 36496, "text": "Strings" }, { "code": null, "e": 36511, "s": 36504, "text": "Google" }, { "code": null, "e": 36519, "s": 36511, "text": "Strings" }, { "code": null, "e": 36539, "s": 36519, "text": "Dynamic Programming" }, { "code": null, "e": 36637, "s": 36539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36668, "s": 36637, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 36701, "s": 36668, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 36728, "s": 36701, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 36747, "s": 36728, "text": "Coin Change | DP-7" }, { "code": null, "e": 36785, "s": 36747, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 36831, "s": 36785, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 36856, "s": 36831, "text": "Reverse a string in Java" }, { "code": null, "e": 36916, "s": 36856, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36931, "s": 36916, "text": "C++ Data Types" } ]
How to find the minimum and maximum element of a Vector using STL in C++? - GeeksforGeeks
20 Mar, 2019 Given a vector, find the minimum and maximum element of this vector using STL in C++. Example: Input: {1, 45, 54, 71, 76, 12} Output: min = 1, max = 76 Input: {10, 7, 5, 4, 6, 12} Output: min = 1, max = 76 Approach: Min or Minimum element can be found with the help of *min_element() function provided in STL. Max or Maximum element can be found with the help of *max_element() function provided in STL. Syntax: *min_element (first_index, last_index); *max_element (first_index, last_index); Below is the implementation of the above approach: // C++ program to find the min and max element// of Vector using *min_element() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; // Find the min element cout << "\nMin Element = " << *min_element(a.begin(), a.end()); // Find the max element cout << "\nMax Element = " << *max_element(a.begin(), a.end()); return 0;} Vector: 1 45 54 71 76 12 Min Element = 1 Max Element = 76 cpp-vector STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++ Bitwise Operators in C/C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25669, "s": 25641, "text": "\n20 Mar, 2019" }, { "code": null, "e": 25755, "s": 25669, "text": "Given a vector, find the minimum and maximum element of this vector using STL in C++." }, { "code": null, "e": 25764, "s": 25755, "text": "Example:" }, { "code": null, "e": 25877, "s": 25764, "text": "Input: {1, 45, 54, 71, 76, 12}\nOutput: min = 1, max = 76\n\nInput: {10, 7, 5, 4, 6, 12}\nOutput: min = 1, max = 76\n" }, { "code": null, "e": 25887, "s": 25877, "text": "Approach:" }, { "code": null, "e": 25981, "s": 25887, "text": "Min or Minimum element can be found with the help of *min_element() function provided in STL." }, { "code": null, "e": 26075, "s": 25981, "text": "Max or Maximum element can be found with the help of *max_element() function provided in STL." }, { "code": null, "e": 26083, "s": 26075, "text": "Syntax:" }, { "code": null, "e": 26165, "s": 26083, "text": "*min_element (first_index, last_index);\n\n*max_element (first_index, last_index);\n" }, { "code": null, "e": 26216, "s": 26165, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to find the min and max element// of Vector using *min_element() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << \"Vector: \"; for (int i = 0; i < a.size(); i++) cout << a[i] << \" \"; cout << endl; // Find the min element cout << \"\\nMin Element = \" << *min_element(a.begin(), a.end()); // Find the max element cout << \"\\nMax Element = \" << *max_element(a.begin(), a.end()); return 0;}", "e": 26782, "s": 26216, "text": null }, { "code": null, "e": 26843, "s": 26782, "text": "Vector: 1 45 54 71 76 12 \n\nMin Element = 1\nMax Element = 76\n" }, { "code": null, "e": 26854, "s": 26843, "text": "cpp-vector" }, { "code": null, "e": 26858, "s": 26854, "text": "STL" }, { "code": null, "e": 26862, "s": 26858, "text": "C++" }, { "code": null, "e": 26875, "s": 26862, "text": "C++ Programs" }, { "code": null, "e": 26879, "s": 26875, "text": "STL" }, { "code": null, "e": 26883, "s": 26879, "text": "CPP" }, { "code": null, "e": 26981, "s": 26883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27000, "s": 26981, "text": "Inheritance in C++" }, { "code": null, "e": 27043, "s": 27000, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27067, "s": 27043, "text": "C++ Classes and Objects" }, { "code": null, "e": 27091, "s": 27067, "text": "Virtual Function in C++" }, { "code": null, "e": 27118, "s": 27091, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27153, "s": 27118, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27197, "s": 27153, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27256, "s": 27197, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27282, "s": 27256, "text": "C++ Program for QuickSort" } ]
Find all combinations of k-bit numbers with n bits set where 1 <= n <= k in sorted order - GeeksforGeeks
21 Mar, 2017 Given a number k, find all the possible combinations of k-bit numbers with n-bits set where 1 <= n <= k. The solution should print all numbers with one set bit first, followed by numbers with two bits set,.. up to the numbers whose all k-bits are set. If two numbers have the same number of set bits, then smaller number should come first. Examples: Input: K = 3 Output: 001 010 100 011 101 110 111 Input: K = 4 Output: 0001 0010 0100 1000 0011 0101 0110 1001 1010 1100 0111 1011 1101 1110 1111 Input: K = 5 Output: 00001 00010 00100 01000 10000 00011 00101 00110 01001 01010 01100 10001 10010 10100 11000 00111 01011 01101 01110 10011 10101 10110 11001 11010 11100 01111 10111 11011 11101 11110 11111 We need to find all the possible combinations of k-bit numbers with n set bits where 1 <= n <= k. If we carefully analyze, we see that problem can further be divided into sub-problems. We can find all combinations of length k with n ones by prefixing 0 to all combinations of length k-1 with n ones and 1 to all combinations of length k-1 with n-1 ones. We can use Dynamic Programming to save solutions of sub-problems. Below is C++ implementation of above idea – // C++ program find all the possible combinations of // k-bit numbers with n-bits set where 1 <= n <= k#include <iostream>#include <vector>using namespace std;// maximum allowed value of K#define K 16 // DP lookup tablevector<string> DP[K][K]; // Function to find all combinations k-bit numbers with // n-bits set where 1 <= n <= kvoid findBitCombinations(int k){ string str = ""; // DP[k][0] will store all k-bit numbers // with 0 bits set (All bits are 0's) for (int len = 0; len <= k; len++) { DP[len][0].push_back(str); str = str + "0"; } // fill DP lookup table in bottom-up manner // DP[k][n] will store all k-bit numbers // with n-bits set for (int len = 1; len <= k; len++) { for (int n = 1; n <= len; n++) { // prefix 0 to all combinations of length len-1 // with n ones for (string str : DP[len - 1][n]) DP[len][n].push_back("0" + str); // prefix 1 to all combinations of length len-1 // with n-1 ones for (string str : DP[len - 1][n - 1]) DP[len][n].push_back("1" + str); } } // print all k-bit binary strings with // n-bit set for (int n = 1; n <= k; n++) { for (string str : DP[k][n]) cout << str << " "; cout << endl; }} // Driver codeint main(){ int k = 5; findBitCombinations(k); return 0;} Output: 00000 00001 00010 00100 01000 10000 00011 00101 00110 01001 01010 01100 10001 10010 10100 11000 00111 01011 01101 01110 10011 10101 10110 11001 11010 11100 01111 10111 11011 11101 11110 11111 This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. ps_gotnochill Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Substructure Property in Dynamic Programming | DP-2 Optimal Binary Search Tree | DP-24 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Greedy approach vs Dynamic programming 3 Different ways to print Fibonacci series in Java Maximum sum such that no two elements are adjacent Word Break Problem | DP-32 Top 50 Dynamic Programming Coding Problems for Interviews How to solve a Dynamic Programming Problem ?
[ { "code": null, "e": 25941, "s": 25913, "text": "\n21 Mar, 2017" }, { "code": null, "e": 26281, "s": 25941, "text": "Given a number k, find all the possible combinations of k-bit numbers with n-bits set where 1 <= n <= k. The solution should print all numbers with one set bit first, followed by numbers with two bits set,.. up to the numbers whose all k-bits are set. If two numbers have the same number of set bits, then smaller number should come first." }, { "code": null, "e": 26291, "s": 26281, "text": "Examples:" }, { "code": null, "e": 26664, "s": 26291, "text": "Input: K = 3\nOutput: \n001 010 100 \n011 101 110 \n111 \n\nInput: K = 4\nOutput: \n0001 0010 0100 1000 \n0011 0101 0110 1001 1010 1100 \n0111 1011 1101 1110 \n1111 \n\nInput: K = 5\nOutput: \n00001 00010 00100 01000 10000 \n00011 00101 00110 01001 01010 01100 10001 10010 10100 11000 \n00111 01011 01101 01110 10011 10101 10110 11001 11010 11100 \n01111 10111 11011 11101 11110 \n11111 \n" }, { "code": null, "e": 27084, "s": 26664, "text": "We need to find all the possible combinations of k-bit numbers with n set bits where 1 <= n <= k. If we carefully analyze, we see that problem can further be divided into sub-problems. We can find all combinations of length k with n ones by prefixing 0 to all combinations of length k-1 with n ones and 1 to all combinations of length k-1 with n-1 ones. We can use Dynamic Programming to save solutions of sub-problems." }, { "code": null, "e": 27128, "s": 27084, "text": "Below is C++ implementation of above idea –" }, { "code": "// C++ program find all the possible combinations of // k-bit numbers with n-bits set where 1 <= n <= k#include <iostream>#include <vector>using namespace std;// maximum allowed value of K#define K 16 // DP lookup tablevector<string> DP[K][K]; // Function to find all combinations k-bit numbers with // n-bits set where 1 <= n <= kvoid findBitCombinations(int k){ string str = \"\"; // DP[k][0] will store all k-bit numbers // with 0 bits set (All bits are 0's) for (int len = 0; len <= k; len++) { DP[len][0].push_back(str); str = str + \"0\"; } // fill DP lookup table in bottom-up manner // DP[k][n] will store all k-bit numbers // with n-bits set for (int len = 1; len <= k; len++) { for (int n = 1; n <= len; n++) { // prefix 0 to all combinations of length len-1 // with n ones for (string str : DP[len - 1][n]) DP[len][n].push_back(\"0\" + str); // prefix 1 to all combinations of length len-1 // with n-1 ones for (string str : DP[len - 1][n - 1]) DP[len][n].push_back(\"1\" + str); } } // print all k-bit binary strings with // n-bit set for (int n = 1; n <= k; n++) { for (string str : DP[k][n]) cout << str << \" \"; cout << endl; }} // Driver codeint main(){ int k = 5; findBitCombinations(k); return 0;}", "e": 28586, "s": 27128, "text": null }, { "code": null, "e": 28594, "s": 28586, "text": "Output:" }, { "code": null, "e": 28792, "s": 28594, "text": "00000 \n00001 00010 00100 01000 10000 \n00011 00101 00110 01001 01010 01100 10001 10010 10100 11000 \n00111 01011 01101 01110 10011 10101 10110 11001 11010 11100 \n01111 10111 11011 11101 11110 \n11111\n" }, { "code": null, "e": 29091, "s": 28792, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29216, "s": 29091, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29230, "s": 29216, "text": "ps_gotnochill" }, { "code": null, "e": 29250, "s": 29230, "text": "Dynamic Programming" }, { "code": null, "e": 29270, "s": 29250, "text": "Dynamic Programming" }, { "code": null, "e": 29368, "s": 29270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29428, "s": 29368, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 29463, "s": 29428, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 29484, "s": 29463, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 29540, "s": 29484, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 29579, "s": 29540, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 29630, "s": 29579, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 29681, "s": 29630, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 29708, "s": 29681, "text": "Word Break Problem | DP-32" }, { "code": null, "e": 29766, "s": 29708, "text": "Top 50 Dynamic Programming Coding Problems for Interviews" } ]
How to maintain dictionary in a heap in Python ? - GeeksforGeeks
07 Sep, 2021 Prerequisites: Binary heap data structure heapq module in Python Dictionary in Python. The dictionary can be maintained in heap either based on the key or on the value. The conventions to be maintained are listed below: The key-value pair at index ‘i‘ is considered to be the parent of key-value pair at the indices 2k+1 and 2k+2. For a min-heap, the parent key/value must be smaller than its children. For a max-heap, the parent key/value must be larger than its children. Examples: Normal dictionary : {11:2, 0:4, 5:9, 22:7} Heap based on keys of the dictionary : {0: 4, 1: 1, 5: 9, 22: 7, 11: 2} Heap based on values of the dictionary : {11: 2, 0: 4, 5: 9, 22: 7} This article shows how to maintain a dictionary in a min-heap using the heapq module. The normal dictionary with integers/strings as the key can be maintained in a heap structure with the help of the heapq module. But this module expects a list to be passed. So the approach used here is : Convert the key-value pairs into a list of tuples.Pass the list of tuples to heapify() function.Convert the resulting list into a dictionary again. Convert the key-value pairs into a list of tuples. Pass the list of tuples to heapify() function. Convert the resulting list into a dictionary again. Note: The heapify() on tuples considers the first element in the tuple for the process. Thus, by default, the dictionaries are maintained in heap, based on the key only. Example 1: Based on the Key for integers Consider a dictionary where the keys are positive integers and the values are their squares. Now, this should be maintained in a heap. Python3 # import modulesimport heapq as hq # dictionary to be heapifieddict_1 = {11: 121, 2: 4, 5: 25, 3: 9} # convert dictionary to list of tuplesdi = list(dict_1.items()) print("dictionary into list :", di) # converting into heaphq.heapify(di) print("Heapified list of tuples :", di) # converting heap to dictionarydi = dict(di) print("Dictionary as heap :", di) dictionary into list : [(11, 121), (2, 4), (5, 25), (3, 9)] Heapified list of tuples : [(2, 4), (3, 9), (5, 25), (11, 121)] Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121} Example 2: Based on key for String Consider a dictionary which has a combination of alphabets as key and their numbering as values. For example: “abc” : 123. This has to be maintained in heap. Python3 # import modulesimport heapq as hq # dictionary to be heapifieddict_1 = {"yz": 2526, "ab": 12, "cd": 34, "ij": 910, "fg": 67} # convert dictionary to list of tuplesdi = list(dict_1.items()) print("dictionary into list :", di) # converting into heaphq.heapify(di) print("Heapified list of tuples :", di) # converting heap to dictionarydi = dict(di) print("Dictionary as heap :", di) Output: dictionary into list : [(‘yz’, 2526), (‘ab’, 12), (‘cd’, 34), (‘ij’, 910), (‘fg’, 67)] Heapified list of tuples : [(‘ab’, 12), (‘fg’, 67), (‘cd’, 34), (‘ij’, 910), (‘yz’, 2526)] Dictionary as heap : {‘ab’: 12, ‘fg’: 67, ‘cd’: 34, ‘ij’: 910, ‘yz’: 2526} Example 3: Based on the value The approach slightly differs here. The steps to be carried out are: Extract the values in the dictionary and append to a list.Pass the list to heapify().Based on the heapified list values, reconstruct a new dictionary from the original one by iterating through it. Extract the values in the dictionary and append to a list. Pass the list to heapify(). Based on the heapified list values, reconstruct a new dictionary from the original one by iterating through it. Here only the values satisfy the heap property and not necessarily the keys. Example: Python3 # import the moduleimport heapq as hq # dictionary to be heapifiedli_dict={11:121,2:4,5:25,3:9} # List to hold values from dictionaryheap_dict=[] # extract the values from dictionaryfor i in li_dict.values(): heap_dict.append(i) # heapify the valueshq.heapify(heap_dict) print("Values of the dict after heapification :",heap_dict) # list to hold final heapified dictionarynew_dict=[] # mapping and reconstructing final dictionaryfor i in range(0,len(heap_dict)): # Iterating the oringinal dictionary for k,v in li_dict.items(): if v==heap_dict[i] and (k,v) not in new_dict: new_dict.append((k,v)) new_dict=dict(new_dict) print("Final dictionary :",new_dict) Values of the dict after heapification : [4, 9, 25, 121] Final dictionary : {2: 4, 3: 9, 5: 25, 11: 121} The examples seen above are based on a single dictionary. Consider a list of dictionaries which has to be maintained as a heap. The approach used is: Convert each dictionary into a tuple using list comprehension. Pass the list to heapify(). Convert the resulting list of heapified tuples into the dictionary. Note: The heapify() on tuples considers the first element in the tuple for the process. Thus, by default, the dictionaries are maintained in heap, based on the key only. Example : Python3 # import modulesimport heapq as hq # list of dictionariesli_dict=[{11:121},{2:4},{5:25},{3:9}] #temporary list to hold tuple of key-value pairsheap_dict=[] # convert each dict to tupleheap_dict=[(k,v) for i in li_dict for k,v in i.items() ] print("After extraction :",heap_dict) # heapify the list of tupleshq.heapify(heap_dict) print("Heapified key-value pairs :",heap_dict) # reconvert to dictionaryfinal=dict(heap_dict)print("Heapified dictionaries :",final) After extraction : [(11, 121), (2, 4), (5, 25), (3, 9)] Heapified key-value pairs : [(2, 4), (3, 9), (5, 25), (11, 121)] Heapified dictionaries : {2: 4, 3: 9, 5: 25, 11: 121} In the case of nested dictionaries, the task takes more steps to maintain the dictionary in heap. If the dictionary has to be maintained based on the key in a inner dictionary, then the following approach can be used. Convert the dictionary into list of tuples where the key of the outer dictionary is tuple[0] and the inner dictionary is tuple[1]. Extract the values of the key in inner dictionaries into a list. Apply heapify() on that list. Re-construct a new dictionary by ordering them based on the heapified results. For example, consider a record of employees as a nested dictionary. The record appears as given below: { “emp01”:{ “name”:”Kate”, “age”:22, “designation”: “Analyst”, “Salary”:30000 }, “emp02”:{ “name”:”Rina”, “age”:20, “designation”:”Programmer”, “Salary”:25000 }, “emp03”:{ “name”:”Vikas”, “age”:42, “designation”:”Manager”, “Salary”:35000 }, “emp04”:{ “name”:”manish”, “age”:42, “designation”:”Manager”, “Salary”:15000 } } Now let us maintain this in a min-heap based on the salary values. Thus, the employee with minimum salary appears as the first record. For better readability and understanding we can split the code into functions. Step 1: Define the function to convert the dictionary into a list Python3 def get_list(d): list_li=list(d.items()) print("Dictionary as list",list_li,"\n") return(list_li) Step 2: Define the function that performs heapification. Takes the list of tuples as parameter. Python3 def convert_heap(list_li): # list to hold salary values sal_li=[] # extract salary values for i in range(0,len(list_li)): sal_li.append(list_li[i][1]['Salary']) print("Before heapify :",sal_li,"\n") # heapify the salary values hq.heapify(sal_li) print("After salary :",sal_li,"\n") # list to hold the final dictionary as heap final=[] # reconstruction of dictionary as heap # yields a list of tuples of key-value pairs for i in range(0,len(sal_li)): for j in range(0,len(sal_li)): if list_li[j][1]['Salary']==sal_li[i]: final.append(list_li[j]) # list of tuples to dictionary final=dict(final) return final Step 3: Define the dictionary and call the functions appropriately. Python3 nested_dict={ "emp01":{ "name":"Kate", "age":22, "designation": "Analyst", "Salary":30000 }, "emp02":{ "name":"Rina", "age":20, "designation":"Programmer", "Salary":25000 }, "emp03":{ "name":"Vikas", "age":42, "designation":"Manager", "Salary":35000 }, "emp04":{ "name":"manish", "age":42, "designation":"Manager", "Salary":15000 }} list_li=get_list(nested_dict) final=convert_heap(list_li) print("Dictionary as heap :",final) Now putting all the code together we get a nested dictionary maintained in heap, based on the values of the salary. Python3 import heapq as hq def get_list(d): list_li=list(d.items()) print("Dictionary as list",list_li,"\n") return(list_li) def convert_heap(list_li): # list to hold salary values sal_li=[] # extract salary values for i in range(0,len(list_li)): sal_li.append(list_li[i][1]['Salary']) print("Before heapify :",sal_li,"\n") # heapify the salary values hq.heapify(sal_li) print("After heapify :",sal_li,"\n") # list to hold the final dictionary as heap final=[] # reconstruction of dictionary as heap # yields a list of tuples of key-value pairs for i in range(0,len(sal_li)): for j in range(0,len(sal_li)): if list_li[j][1]['Salary']==sal_li[i]: final.append(list_li[j]) # list of tuples to dictionary final=dict(final) return final nested_dict={ "emp01":{ "name":"Kate", "age":22, "designation": "Analyst", "Salary":30000 }, "emp02":{ "name":"Rina", "age":20, "designation":"Programmer", "Salary":25000 }, "emp03":{ "name":"Vikas", "age":42, "designation":"Manager", "Salary":35000 }, "emp04":{ "name":"manish", "age":42, "designation":"Manager", "Salary":15000 }} list_li=get_list(nested_dict) final=convert_heap(list_li) print("Dictionary as heap :",final) Output Dictionary as list [(’emp01′, {‘name’: ‘Kate’, ‘age’: 22, ‘designation’: ‘Analyst’, ‘Salary’: 30000}), (’emp02′, {‘name’: ‘Rina’, ‘age’: 20, ‘designation’: ‘Programmer’, ‘Salary’: 25000}), (’emp03′, {‘name’: ‘Vikas’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 35000}), (’emp04′, {‘name’: ‘manish’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 15000})] Before heapify : [30000, 25000, 35000, 15000] After heapify : [15000, 25000, 35000, 30000] Dictionary as heap : {’emp04′: {‘name’: ‘manish’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 15000}, ’emp02′: {‘name’: ‘Rina’, ‘age’: 20, ‘designation’: ‘Programmer’, ‘Salary’: 25000}, ’emp03′: {‘name’: ‘Vikas’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 35000}, ’emp01′: {‘name’: ‘Kate’, ‘age’: 22, ‘designation’: ‘Analyst’, ‘Salary’: 30000}} The insertion of new values can be done directly using heappush() method in the heapq module. Its syntax is as follows. heapq . heappush ( list , new_value ) Now the list of tuples along with a new tuple can be passed to this function to add the new-key value pair. Example : Python3 import heapq as hq # list of dictionariesli_dict=[{11:121},{2:4},{5:25},{3:9}] # list to hold tuplesheap_dict=[] # convert each dict to tuple of (key,value)heap_dict=[(k,v) for i in li_dict for k,v in i.items() ] print("List of tuples :",heap_dict) # applying heapify()hq.heapify(heap_dict) print("After heapification :",heap_dict) # reconvert to dictfinal=dict(heap_dict) print("Dictionary as heap :",final) # add new value (1,1)hq.heappush(heap_dict,(1,1)) print("After insertion & heapification",heap_dict) #reconvert the resultfinal=dict(heap_dict) print("New dictionary :",final) Output: List of tuples : [(11, 121), (2, 4), (5, 25), (3, 9)] After heapification : [(2, 4), (3, 9), (5, 25), (11, 121)] Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121} After insertion & heapification [(1, 1), (2, 4), (5, 25), (11, 121), (3, 9)] New dictionary : {1: 1, 2: 4, 5: 25, 11: 121, 3: 9} Another method that can be done is to have a function that heapify the dictionary and calling it after updating the dictionary. Example : Python3 import heapq as hq def heapify_dict(d): # convert to list of tuples li=list(dict1.items()) hq.heapify(li) li=dict(li) print("Dictionary as heap :",li) dict1={11:121,2:4,5:25,3:9} print("Before adding new values")heapify_dict(dict1) # add new values to dictionarydict1[4]=16dict1[1]=1 print("Updated dictionary :",dict1) print("After adding new values")heapify_dict(dict1) Before adding new values Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121} Updated dictionary : {11: 121, 2: 4, 5: 25, 3: 9, 4: 16, 1: 1} After adding new values Dictionary as heap : {1: 1, 2: 4, 5: 25, 3: 9, 4: 16, 11: 121} clintra varshagumber28 Data Structures-Heap python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n07 Sep, 2021" }, { "code": null, "e": 25552, "s": 25537, "text": "Prerequisites:" }, { "code": null, "e": 25579, "s": 25552, "text": "Binary heap data structure" }, { "code": null, "e": 25602, "s": 25579, "text": "heapq module in Python" }, { "code": null, "e": 25624, "s": 25602, "text": "Dictionary in Python." }, { "code": null, "e": 25757, "s": 25624, "text": "The dictionary can be maintained in heap either based on the key or on the value. The conventions to be maintained are listed below:" }, { "code": null, "e": 25868, "s": 25757, "text": "The key-value pair at index ‘i‘ is considered to be the parent of key-value pair at the indices 2k+1 and 2k+2." }, { "code": null, "e": 25940, "s": 25868, "text": "For a min-heap, the parent key/value must be smaller than its children." }, { "code": null, "e": 26011, "s": 25940, "text": "For a max-heap, the parent key/value must be larger than its children." }, { "code": null, "e": 26021, "s": 26011, "text": "Examples:" }, { "code": null, "e": 26064, "s": 26021, "text": "Normal dictionary : {11:2, 0:4, 5:9, 22:7}" }, { "code": null, "e": 26136, "s": 26064, "text": "Heap based on keys of the dictionary : {0: 4, 1: 1, 5: 9, 22: 7, 11: 2}" }, { "code": null, "e": 26204, "s": 26136, "text": "Heap based on values of the dictionary : {11: 2, 0: 4, 5: 9, 22: 7}" }, { "code": null, "e": 26290, "s": 26204, "text": "This article shows how to maintain a dictionary in a min-heap using the heapq module." }, { "code": null, "e": 26494, "s": 26290, "text": "The normal dictionary with integers/strings as the key can be maintained in a heap structure with the help of the heapq module. But this module expects a list to be passed. So the approach used here is :" }, { "code": null, "e": 26642, "s": 26494, "text": "Convert the key-value pairs into a list of tuples.Pass the list of tuples to heapify() function.Convert the resulting list into a dictionary again." }, { "code": null, "e": 26693, "s": 26642, "text": "Convert the key-value pairs into a list of tuples." }, { "code": null, "e": 26740, "s": 26693, "text": "Pass the list of tuples to heapify() function." }, { "code": null, "e": 26792, "s": 26740, "text": "Convert the resulting list into a dictionary again." }, { "code": null, "e": 26962, "s": 26792, "text": "Note: The heapify() on tuples considers the first element in the tuple for the process. Thus, by default, the dictionaries are maintained in heap, based on the key only." }, { "code": null, "e": 27003, "s": 26962, "text": "Example 1: Based on the Key for integers" }, { "code": null, "e": 27138, "s": 27003, "text": "Consider a dictionary where the keys are positive integers and the values are their squares. Now, this should be maintained in a heap." }, { "code": null, "e": 27146, "s": 27138, "text": "Python3" }, { "code": "# import modulesimport heapq as hq # dictionary to be heapifieddict_1 = {11: 121, 2: 4, 5: 25, 3: 9} # convert dictionary to list of tuplesdi = list(dict_1.items()) print(\"dictionary into list :\", di) # converting into heaphq.heapify(di) print(\"Heapified list of tuples :\", di) # converting heap to dictionarydi = dict(di) print(\"Dictionary as heap :\", di)", "e": 27503, "s": 27146, "text": null }, { "code": null, "e": 27677, "s": 27503, "text": "dictionary into list : [(11, 121), (2, 4), (5, 25), (3, 9)]\nHeapified list of tuples : [(2, 4), (3, 9), (5, 25), (11, 121)]\nDictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121}" }, { "code": null, "e": 27713, "s": 27677, "text": "Example 2: Based on key for String " }, { "code": null, "e": 27872, "s": 27713, "text": "Consider a dictionary which has a combination of alphabets as key and their numbering as values. For example: “abc” : 123. This has to be maintained in heap. " }, { "code": null, "e": 27880, "s": 27872, "text": "Python3" }, { "code": "# import modulesimport heapq as hq # dictionary to be heapifieddict_1 = {\"yz\": 2526, \"ab\": 12, \"cd\": 34, \"ij\": 910, \"fg\": 67} # convert dictionary to list of tuplesdi = list(dict_1.items()) print(\"dictionary into list :\", di) # converting into heaphq.heapify(di) print(\"Heapified list of tuples :\", di) # converting heap to dictionarydi = dict(di) print(\"Dictionary as heap :\", di)", "e": 28262, "s": 27880, "text": null }, { "code": null, "e": 28270, "s": 28262, "text": "Output:" }, { "code": null, "e": 28523, "s": 28270, "text": "dictionary into list : [(‘yz’, 2526), (‘ab’, 12), (‘cd’, 34), (‘ij’, 910), (‘fg’, 67)] Heapified list of tuples : [(‘ab’, 12), (‘fg’, 67), (‘cd’, 34), (‘ij’, 910), (‘yz’, 2526)] Dictionary as heap : {‘ab’: 12, ‘fg’: 67, ‘cd’: 34, ‘ij’: 910, ‘yz’: 2526}" }, { "code": null, "e": 28553, "s": 28523, "text": "Example 3: Based on the value" }, { "code": null, "e": 28622, "s": 28553, "text": "The approach slightly differs here. The steps to be carried out are:" }, { "code": null, "e": 28819, "s": 28622, "text": "Extract the values in the dictionary and append to a list.Pass the list to heapify().Based on the heapified list values, reconstruct a new dictionary from the original one by iterating through it." }, { "code": null, "e": 28878, "s": 28819, "text": "Extract the values in the dictionary and append to a list." }, { "code": null, "e": 28906, "s": 28878, "text": "Pass the list to heapify()." }, { "code": null, "e": 29018, "s": 28906, "text": "Based on the heapified list values, reconstruct a new dictionary from the original one by iterating through it." }, { "code": null, "e": 29095, "s": 29018, "text": "Here only the values satisfy the heap property and not necessarily the keys." }, { "code": null, "e": 29104, "s": 29095, "text": "Example:" }, { "code": null, "e": 29112, "s": 29104, "text": "Python3" }, { "code": "# import the moduleimport heapq as hq # dictionary to be heapifiedli_dict={11:121,2:4,5:25,3:9} # List to hold values from dictionaryheap_dict=[] # extract the values from dictionaryfor i in li_dict.values(): heap_dict.append(i) # heapify the valueshq.heapify(heap_dict) print(\"Values of the dict after heapification :\",heap_dict) # list to hold final heapified dictionarynew_dict=[] # mapping and reconstructing final dictionaryfor i in range(0,len(heap_dict)): # Iterating the oringinal dictionary for k,v in li_dict.items(): if v==heap_dict[i] and (k,v) not in new_dict: new_dict.append((k,v)) new_dict=dict(new_dict) print(\"Final dictionary :\",new_dict)", "e": 29826, "s": 29112, "text": null }, { "code": null, "e": 29931, "s": 29826, "text": "Values of the dict after heapification : [4, 9, 25, 121]\nFinal dictionary : {2: 4, 3: 9, 5: 25, 11: 121}" }, { "code": null, "e": 30082, "s": 29931, "text": "The examples seen above are based on a single dictionary. Consider a list of dictionaries which has to be maintained as a heap. The approach used is: " }, { "code": null, "e": 30145, "s": 30082, "text": "Convert each dictionary into a tuple using list comprehension." }, { "code": null, "e": 30173, "s": 30145, "text": "Pass the list to heapify()." }, { "code": null, "e": 30241, "s": 30173, "text": "Convert the resulting list of heapified tuples into the dictionary." }, { "code": null, "e": 30411, "s": 30241, "text": "Note: The heapify() on tuples considers the first element in the tuple for the process. Thus, by default, the dictionaries are maintained in heap, based on the key only." }, { "code": null, "e": 30422, "s": 30411, "text": "Example : " }, { "code": null, "e": 30430, "s": 30422, "text": "Python3" }, { "code": "# import modulesimport heapq as hq # list of dictionariesli_dict=[{11:121},{2:4},{5:25},{3:9}] #temporary list to hold tuple of key-value pairsheap_dict=[] # convert each dict to tupleheap_dict=[(k,v) for i in li_dict for k,v in i.items() ] print(\"After extraction :\",heap_dict) # heapify the list of tupleshq.heapify(heap_dict) print(\"Heapified key-value pairs :\",heap_dict) # reconvert to dictionaryfinal=dict(heap_dict)print(\"Heapified dictionaries :\",final)", "e": 30894, "s": 30430, "text": null }, { "code": null, "e": 31069, "s": 30894, "text": "After extraction : [(11, 121), (2, 4), (5, 25), (3, 9)]\nHeapified key-value pairs : [(2, 4), (3, 9), (5, 25), (11, 121)]\nHeapified dictionaries : {2: 4, 3: 9, 5: 25, 11: 121}" }, { "code": null, "e": 31287, "s": 31069, "text": "In the case of nested dictionaries, the task takes more steps to maintain the dictionary in heap. If the dictionary has to be maintained based on the key in a inner dictionary, then the following approach can be used." }, { "code": null, "e": 31418, "s": 31287, "text": "Convert the dictionary into list of tuples where the key of the outer dictionary is tuple[0] and the inner dictionary is tuple[1]." }, { "code": null, "e": 31483, "s": 31418, "text": "Extract the values of the key in inner dictionaries into a list." }, { "code": null, "e": 31513, "s": 31483, "text": "Apply heapify() on that list." }, { "code": null, "e": 31592, "s": 31513, "text": "Re-construct a new dictionary by ordering them based on the heapified results." }, { "code": null, "e": 31696, "s": 31592, "text": "For example, consider a record of employees as a nested dictionary. The record appears as given below: " }, { "code": null, "e": 31698, "s": 31696, "text": "{" }, { "code": null, "e": 31711, "s": 31698, "text": " “emp01”:{" }, { "code": null, "e": 31733, "s": 31711, "text": " “name”:”Kate”," }, { "code": null, "e": 31750, "s": 31733, "text": " “age”:22," }, { "code": null, "e": 31783, "s": 31750, "text": " “designation”: “Analyst”," }, { "code": null, "e": 31805, "s": 31783, "text": " “Salary”:30000" }, { "code": null, "e": 31811, "s": 31805, "text": " }," }, { "code": null, "e": 31824, "s": 31811, "text": " “emp02”:{" }, { "code": null, "e": 31846, "s": 31824, "text": " “name”:”Rina”," }, { "code": null, "e": 31863, "s": 31846, "text": " “age”:20," }, { "code": null, "e": 31898, "s": 31863, "text": " “designation”:”Programmer”," }, { "code": null, "e": 31920, "s": 31898, "text": " “Salary”:25000" }, { "code": null, "e": 31926, "s": 31920, "text": " }," }, { "code": null, "e": 31939, "s": 31926, "text": " “emp03”:{" }, { "code": null, "e": 31962, "s": 31939, "text": " “name”:”Vikas”," }, { "code": null, "e": 31979, "s": 31962, "text": " “age”:42," }, { "code": null, "e": 32011, "s": 31979, "text": " “designation”:”Manager”," }, { "code": null, "e": 32033, "s": 32011, "text": " “Salary”:35000" }, { "code": null, "e": 32039, "s": 32033, "text": " }," }, { "code": null, "e": 32052, "s": 32039, "text": " “emp04”:{" }, { "code": null, "e": 32076, "s": 32052, "text": " “name”:”manish”," }, { "code": null, "e": 32093, "s": 32076, "text": " “age”:42," }, { "code": null, "e": 32125, "s": 32093, "text": " “designation”:”Manager”," }, { "code": null, "e": 32147, "s": 32125, "text": " “Salary”:15000" }, { "code": null, "e": 32152, "s": 32147, "text": " }" }, { "code": null, "e": 32154, "s": 32152, "text": "}" }, { "code": null, "e": 32368, "s": 32154, "text": "Now let us maintain this in a min-heap based on the salary values. Thus, the employee with minimum salary appears as the first record. For better readability and understanding we can split the code into functions." }, { "code": null, "e": 32436, "s": 32368, "text": "Step 1: Define the function to convert the dictionary into a list " }, { "code": null, "e": 32444, "s": 32436, "text": "Python3" }, { "code": "def get_list(d): list_li=list(d.items()) print(\"Dictionary as list\",list_li,\"\\n\") return(list_li)", "e": 32566, "s": 32444, "text": null }, { "code": null, "e": 32664, "s": 32566, "text": " Step 2: Define the function that performs heapification. Takes the list of tuples as parameter. " }, { "code": null, "e": 32672, "s": 32664, "text": "Python3" }, { "code": "def convert_heap(list_li): # list to hold salary values sal_li=[] # extract salary values for i in range(0,len(list_li)): sal_li.append(list_li[i][1]['Salary']) print(\"Before heapify :\",sal_li,\"\\n\") # heapify the salary values hq.heapify(sal_li) print(\"After salary :\",sal_li,\"\\n\") # list to hold the final dictionary as heap final=[] # reconstruction of dictionary as heap # yields a list of tuples of key-value pairs for i in range(0,len(sal_li)): for j in range(0,len(sal_li)): if list_li[j][1]['Salary']==sal_li[i]: final.append(list_li[j]) # list of tuples to dictionary final=dict(final) return final", "e": 33420, "s": 32672, "text": null }, { "code": null, "e": 33488, "s": 33420, "text": "Step 3: Define the dictionary and call the functions appropriately." }, { "code": null, "e": 33496, "s": 33488, "text": "Python3" }, { "code": "nested_dict={ \"emp01\":{ \"name\":\"Kate\", \"age\":22, \"designation\": \"Analyst\", \"Salary\":30000 }, \"emp02\":{ \"name\":\"Rina\", \"age\":20, \"designation\":\"Programmer\", \"Salary\":25000 }, \"emp03\":{ \"name\":\"Vikas\", \"age\":42, \"designation\":\"Manager\", \"Salary\":35000 }, \"emp04\":{ \"name\":\"manish\", \"age\":42, \"designation\":\"Manager\", \"Salary\":15000 }} list_li=get_list(nested_dict) final=convert_heap(list_li) print(\"Dictionary as heap :\",final)", "e": 34059, "s": 33496, "text": null }, { "code": null, "e": 34175, "s": 34059, "text": "Now putting all the code together we get a nested dictionary maintained in heap, based on the values of the salary." }, { "code": null, "e": 34183, "s": 34175, "text": "Python3" }, { "code": "import heapq as hq def get_list(d): list_li=list(d.items()) print(\"Dictionary as list\",list_li,\"\\n\") return(list_li) def convert_heap(list_li): # list to hold salary values sal_li=[] # extract salary values for i in range(0,len(list_li)): sal_li.append(list_li[i][1]['Salary']) print(\"Before heapify :\",sal_li,\"\\n\") # heapify the salary values hq.heapify(sal_li) print(\"After heapify :\",sal_li,\"\\n\") # list to hold the final dictionary as heap final=[] # reconstruction of dictionary as heap # yields a list of tuples of key-value pairs for i in range(0,len(sal_li)): for j in range(0,len(sal_li)): if list_li[j][1]['Salary']==sal_li[i]: final.append(list_li[j]) # list of tuples to dictionary final=dict(final) return final nested_dict={ \"emp01\":{ \"name\":\"Kate\", \"age\":22, \"designation\": \"Analyst\", \"Salary\":30000 }, \"emp02\":{ \"name\":\"Rina\", \"age\":20, \"designation\":\"Programmer\", \"Salary\":25000 }, \"emp03\":{ \"name\":\"Vikas\", \"age\":42, \"designation\":\"Manager\", \"Salary\":35000 }, \"emp04\":{ \"name\":\"manish\", \"age\":42, \"designation\":\"Manager\", \"Salary\":15000 }} list_li=get_list(nested_dict) final=convert_heap(list_li) print(\"Dictionary as heap :\",final)", "e": 35640, "s": 34183, "text": null }, { "code": null, "e": 35647, "s": 35640, "text": "Output" }, { "code": null, "e": 36005, "s": 35647, "text": "Dictionary as list [(’emp01′, {‘name’: ‘Kate’, ‘age’: 22, ‘designation’: ‘Analyst’, ‘Salary’: 30000}), (’emp02′, {‘name’: ‘Rina’, ‘age’: 20, ‘designation’: ‘Programmer’, ‘Salary’: 25000}), (’emp03′, {‘name’: ‘Vikas’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 35000}), (’emp04′, {‘name’: ‘manish’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 15000})]" }, { "code": null, "e": 36053, "s": 36005, "text": " Before heapify : [30000, 25000, 35000, 15000] " }, { "code": null, "e": 36100, "s": 36053, "text": " After heapify : [15000, 25000, 35000, 30000] " }, { "code": null, "e": 36452, "s": 36100, "text": "Dictionary as heap : {’emp04′: {‘name’: ‘manish’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 15000}, ’emp02′: {‘name’: ‘Rina’, ‘age’: 20, ‘designation’: ‘Programmer’, ‘Salary’: 25000}, ’emp03′: {‘name’: ‘Vikas’, ‘age’: 42, ‘designation’: ‘Manager’, ‘Salary’: 35000}, ’emp01′: {‘name’: ‘Kate’, ‘age’: 22, ‘designation’: ‘Analyst’, ‘Salary’: 30000}}" }, { "code": null, "e": 36572, "s": 36452, "text": "The insertion of new values can be done directly using heappush() method in the heapq module. Its syntax is as follows." }, { "code": null, "e": 36610, "s": 36572, "text": "heapq . heappush ( list , new_value )" }, { "code": null, "e": 36718, "s": 36610, "text": "Now the list of tuples along with a new tuple can be passed to this function to add the new-key value pair." }, { "code": null, "e": 36728, "s": 36718, "text": "Example :" }, { "code": null, "e": 36736, "s": 36728, "text": "Python3" }, { "code": "import heapq as hq # list of dictionariesli_dict=[{11:121},{2:4},{5:25},{3:9}] # list to hold tuplesheap_dict=[] # convert each dict to tuple of (key,value)heap_dict=[(k,v) for i in li_dict for k,v in i.items() ] print(\"List of tuples :\",heap_dict) # applying heapify()hq.heapify(heap_dict) print(\"After heapification :\",heap_dict) # reconvert to dictfinal=dict(heap_dict) print(\"Dictionary as heap :\",final) # add new value (1,1)hq.heappush(heap_dict,(1,1)) print(\"After insertion & heapification\",heap_dict) #reconvert the resultfinal=dict(heap_dict) print(\"New dictionary :\",final)", "e": 37323, "s": 36736, "text": null }, { "code": null, "e": 37331, "s": 37323, "text": "Output:" }, { "code": null, "e": 37623, "s": 37331, "text": "List of tuples : [(11, 121), (2, 4), (5, 25), (3, 9)] After heapification : [(2, 4), (3, 9), (5, 25), (11, 121)] Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121} After insertion & heapification [(1, 1), (2, 4), (5, 25), (11, 121), (3, 9)] New dictionary : {1: 1, 2: 4, 5: 25, 11: 121, 3: 9}" }, { "code": null, "e": 37752, "s": 37623, "text": "Another method that can be done is to have a function that heapify the dictionary and calling it after updating the dictionary. " }, { "code": null, "e": 37762, "s": 37752, "text": "Example :" }, { "code": null, "e": 37770, "s": 37762, "text": "Python3" }, { "code": "import heapq as hq def heapify_dict(d): # convert to list of tuples li=list(dict1.items()) hq.heapify(li) li=dict(li) print(\"Dictionary as heap :\",li) dict1={11:121,2:4,5:25,3:9} print(\"Before adding new values\")heapify_dict(dict1) # add new values to dictionarydict1[4]=16dict1[1]=1 print(\"Updated dictionary :\",dict1) print(\"After adding new values\")heapify_dict(dict1)", "e": 38181, "s": 37770, "text": null }, { "code": null, "e": 38406, "s": 38181, "text": "Before adding new values\nDictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121}\nUpdated dictionary : {11: 121, 2: 4, 5: 25, 3: 9, 4: 16, 1: 1}\nAfter adding new values\nDictionary as heap : {1: 1, 2: 4, 5: 25, 3: 9, 4: 16, 11: 121}" }, { "code": null, "e": 38416, "s": 38408, "text": "clintra" }, { "code": null, "e": 38431, "s": 38416, "text": "varshagumber28" }, { "code": null, "e": 38452, "s": 38431, "text": "Data Structures-Heap" }, { "code": null, "e": 38464, "s": 38452, "text": "python-dict" }, { "code": null, "e": 38471, "s": 38464, "text": "Python" }, { "code": null, "e": 38483, "s": 38471, "text": "python-dict" }, { "code": null, "e": 38581, "s": 38483, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38613, "s": 38581, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 38655, "s": 38613, "text": "Check if element exists in list in Python" }, { "code": null, "e": 38697, "s": 38655, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 38724, "s": 38697, "text": "Python Classes and Objects" }, { "code": null, "e": 38780, "s": 38724, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 38802, "s": 38780, "text": "Defaultdict in Python" }, { "code": null, "e": 38841, "s": 38802, "text": "Python | Get unique values from a list" }, { "code": null, "e": 38872, "s": 38841, "text": "Python | os.path.join() method" }, { "code": null, "e": 38901, "s": 38872, "text": "Create a directory in Python" } ]
Java Program to Display All Prime Numbers from 1 to N - GeeksforGeeks
21 May, 2021 For a given number N, the purpose is to find all the prime numbers from 1 to N. Examples: Input: N = 11 Output: 2, 3, 5, 7, 11 Input: N = 7 Output: 2, 3, 5, 7 Approach 1: Firstly, consider the given number N as input. Then apply a for loop in order to iterate the numbers from 1 to N. At last, check if each number is a prime number and if it’s a prime number then print it using brute-force method. Java // Java program to find all the// prime numbers from 1 to Nclass gfg { // Function to print all the // prime numbers till N static void prime_N(int N) { // Declaring the variables int x, y, flg; // Printing display message System.out.println( "All the Prime numbers within 1 and " + N + " are:"); // Using for loop for traversing all // the numbers from 1 to N for (x = 1; x <= N; x++) { // Omit 0 and 1 as they are // neither prime nor composite if (x == 1 || x == 0) continue; // Using flag variable to check // if x is prime or not flg = 1; for (y = 2; y <= x / 2; ++y) { if (x % y == 0) { flg = 0; break; } } // If flag is 1 then x is prime but // if flag is 0 then x is not prime if (flg == 1) System.out.print(x + " "); } } // The Driver code public static void main(String[] args) { int N = 45; prime_N(N); }} All the Prime numbers within 1 and 45 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 Time Complexity: O(N2) Approach 2: Firstly, consider the given number N as input. Then apply a for loop in order to iterate the numbers from 1 to N. At last, check if each number is a prime number and if it’s a prime number then print it using the square root method. Java // Java program to find all the// prime numbers from 1 to Nclass gfg { // Function to print all the // prime numbers till N static void prime_N(int N) { // Declaring the variables int x, y, flg; // Printing display message System.out.println( "All the Prime numbers within 1 and " + N + " are:"); // Using for loop for traversing all // the numbers from 1 to N for (x = 2; x <= N; x++) { // Using flag variable to check // if x is prime or not flg = 1; for (y = 2; y * y <= x; y++) { if (x % y == 0) { flg = 0; break; } } // If flag is 1 then x is prime but // if flag is 0 then x is not prime if (flg == 1) System.out.print(x + " "); } } // The Driver code public static void main(String[] args) { int N = 45; prime_N(N); }} All the Prime numbers within 1 and 45 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 Time Complexity: O(N3/2) Approach 3: Firstly, consider the given number N as input. Use Sieve of Eratosthenes. Java // Java program to print all// primes smaller than or equal to// n using Sieve of Eratosthenes class SieveOfEratosthenes { void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) System.out.print(i + " "); } } // Driver Code public static void main(String args[]) { int N = 45; System.out.println( "All the Prime numbers within 1 and " + N + " are:"); SieveOfEratosthenes g = new SieveOfEratosthenes(); g.sieveOfEratosthenes(N); }} All the Prime numbers within 1 and 45 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 Time complexity : O(n*log(log(n))) gabaa406 java-basics Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 26126, "s": 26098, "text": "\n21 May, 2021" }, { "code": null, "e": 26206, "s": 26126, "text": "For a given number N, the purpose is to find all the prime numbers from 1 to N." }, { "code": null, "e": 26218, "s": 26206, "text": "Examples: " }, { "code": null, "e": 26255, "s": 26218, "text": "Input: N = 11\nOutput: 2, 3, 5, 7, 11" }, { "code": null, "e": 26288, "s": 26255, "text": "Input: N = 7\nOutput: 2, 3, 5, 7 " }, { "code": null, "e": 26300, "s": 26288, "text": "Approach 1:" }, { "code": null, "e": 26347, "s": 26300, "text": "Firstly, consider the given number N as input." }, { "code": null, "e": 26414, "s": 26347, "text": "Then apply a for loop in order to iterate the numbers from 1 to N." }, { "code": null, "e": 26529, "s": 26414, "text": "At last, check if each number is a prime number and if it’s a prime number then print it using brute-force method." }, { "code": null, "e": 26534, "s": 26529, "text": "Java" }, { "code": "// Java program to find all the// prime numbers from 1 to Nclass gfg { // Function to print all the // prime numbers till N static void prime_N(int N) { // Declaring the variables int x, y, flg; // Printing display message System.out.println( \"All the Prime numbers within 1 and \" + N + \" are:\"); // Using for loop for traversing all // the numbers from 1 to N for (x = 1; x <= N; x++) { // Omit 0 and 1 as they are // neither prime nor composite if (x == 1 || x == 0) continue; // Using flag variable to check // if x is prime or not flg = 1; for (y = 2; y <= x / 2; ++y) { if (x % y == 0) { flg = 0; break; } } // If flag is 1 then x is prime but // if flag is 0 then x is not prime if (flg == 1) System.out.print(x + \" \"); } } // The Driver code public static void main(String[] args) { int N = 45; prime_N(N); }}", "e": 27698, "s": 26534, "text": null }, { "code": null, "e": 27783, "s": 27701, "text": "All the Prime numbers within 1 and 45 are:\n2 3 5 7 11 13 17 19 23 29 31 37 41 43 " }, { "code": null, "e": 27806, "s": 27783, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 27820, "s": 27808, "text": "Approach 2:" }, { "code": null, "e": 27869, "s": 27822, "text": "Firstly, consider the given number N as input." }, { "code": null, "e": 27936, "s": 27869, "text": "Then apply a for loop in order to iterate the numbers from 1 to N." }, { "code": null, "e": 28055, "s": 27936, "text": "At last, check if each number is a prime number and if it’s a prime number then print it using the square root method." }, { "code": null, "e": 28062, "s": 28057, "text": "Java" }, { "code": "// Java program to find all the// prime numbers from 1 to Nclass gfg { // Function to print all the // prime numbers till N static void prime_N(int N) { // Declaring the variables int x, y, flg; // Printing display message System.out.println( \"All the Prime numbers within 1 and \" + N + \" are:\"); // Using for loop for traversing all // the numbers from 1 to N for (x = 2; x <= N; x++) { // Using flag variable to check // if x is prime or not flg = 1; for (y = 2; y * y <= x; y++) { if (x % y == 0) { flg = 0; break; } } // If flag is 1 then x is prime but // if flag is 0 then x is not prime if (flg == 1) System.out.print(x + \" \"); } } // The Driver code public static void main(String[] args) { int N = 45; prime_N(N); }}", "e": 29086, "s": 28062, "text": null }, { "code": null, "e": 29171, "s": 29089, "text": "All the Prime numbers within 1 and 45 are:\n2 3 5 7 11 13 17 19 23 29 31 37 41 43 " }, { "code": null, "e": 29196, "s": 29171, "text": "Time Complexity: O(N3/2)" }, { "code": null, "e": 29210, "s": 29198, "text": "Approach 3:" }, { "code": null, "e": 29259, "s": 29212, "text": "Firstly, consider the given number N as input." }, { "code": null, "e": 29286, "s": 29259, "text": "Use Sieve of Eratosthenes." }, { "code": null, "e": 29293, "s": 29288, "text": "Java" }, { "code": "// Java program to print all// primes smaller than or equal to// n using Sieve of Eratosthenes class SieveOfEratosthenes { void sieveOfEratosthenes(int n) { // Create a boolean array // \"prime[0..n]\" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) System.out.print(i + \" \"); } } // Driver Code public static void main(String args[]) { int N = 45; System.out.println( \"All the Prime numbers within 1 and \" + N + \" are:\"); SieveOfEratosthenes g = new SieveOfEratosthenes(); g.sieveOfEratosthenes(N); }}", "e": 30539, "s": 29293, "text": null }, { "code": null, "e": 30624, "s": 30542, "text": "All the Prime numbers within 1 and 45 are:\n2 3 5 7 11 13 17 19 23 29 31 37 41 43 " }, { "code": null, "e": 30662, "s": 30626, "text": "Time complexity : O(n*log(log(n))) " }, { "code": null, "e": 30673, "s": 30664, "text": "gabaa406" }, { "code": null, "e": 30685, "s": 30673, "text": "java-basics" }, { "code": null, "e": 30690, "s": 30685, "text": "Java" }, { "code": null, "e": 30704, "s": 30690, "text": "Java Programs" }, { "code": null, "e": 30709, "s": 30704, "text": "Java" }, { "code": null, "e": 30807, "s": 30709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30858, "s": 30807, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30888, "s": 30858, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30903, "s": 30888, "text": "Stream In Java" }, { "code": null, "e": 30922, "s": 30903, "text": "Interfaces in Java" }, { "code": null, "e": 30953, "s": 30922, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30981, "s": 30953, "text": "Initializing a List in Java" }, { "code": null, "e": 31025, "s": 30981, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 31059, "s": 31025, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 31106, "s": 31059, "text": "Implementing a Linked List in Java using Class" } ]
Difference Between Lock and Monitor in Java Concurrency - GeeksforGeeks
24 Feb, 2022 Java Concurrency basically deals with concepts like multithreading and other concurrent operations. This is done to ensure maximum and efficient utilization of CPU performance thereby reducing its idle time in general. Locks have been in existence to implement multithreading much before the monitors have come to usage. Back then locks (or mutex) were parts of threads inside the program that worked on flag mechanisms to synchronize with other threads. They have always been working as a tool to provide synchronous access control over resources and shared objects. With further advancements, the use of monitors started as a mechanism to handle access and coordinate threads which proved to be more efficient, error-free, and compatible in object-oriented programs. Before we move on to find the differences between the two let’s have a closer look into each of them. Overview of Lock (or Mutex) Lock originally has been used in the logical section of the threads that were used to provide synchronized access control between the threads. Threads checked the availability of access control over shared objects through flags attached to the object that indicated whether or not the shared resource is free (unlocked) or busy (locked). Now the concurrency API provides support of using locks explicitly using Lock Interface in java. The explicit method has a finer control mechanism as compared to the implicit implementation of locks using monitors. Before we move on to discuss monitors let us look at an illustration that demonstrates the functioning of basic locks. Monitor – Overview Monitor in Java Concurrency is a synchronization mechanism that provides the fundamental requirements of multithreading namely mutual exclusion between various threads and cooperation among threads working at common tasks. Monitors basically ‘monitor’ the access control of shared resources and objects among threads. Using this construct only one thread at a time gets access control over the critical section at the resource while other threads are blocked and made to wait until certain conditions. In Java, monitors are implemented using synchronized keyword (synchronized blocks, synchronized methods or classes). For example, let’s see how two threads t1 and t2 are synchronized to use a shared data printer object. Java // Java Program to Illustrate Monitoe in Java Concurrency // Importing input output classesimport java.io.*; // Class 1// Helper classclass SharedDataPrinter { // Monitor implementation is carried on by // Using synchronous method // Method (synchronised) synchronized public void display(String str) { for (int i = 0; i < str.length(); i++) { System.out.print(str.charAt(i)); // Try-catch bloc kfor exceptions as we are // using sleep() method try { // Making thread to sleep for very // nanoseconds as passed in the arguments Thread.sleep(100); } catch (Exception e) { } } }} // Class 2// Helper class extending the Thread classclass Thread1 extends Thread { SharedDataPrinter p; // Thread public Thread1(SharedDataPrinter p) { // This keyword refers to current instance itself this.p = p; } // run() method for this thread invoked as // start() method is called in the main() method public void run() { // Print statement p.display("Geeks"); }} // Class 2 (similar to class 1)// Helper class extending the Thread classclass Thread2 extends Thread { SharedDataPrinter p; public Thread2(SharedDataPrinter p) { this.p = p; } public void run() { // Print statement p.display(" for Geeks"); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Instance of a shared resource used to print // strings (single character at a time) SharedDataPrinter printer = new SharedDataPrinter(); // Thread objects sharing data printer Thread1 t1 = new Thread1(printer); Thread2 t2 = new Thread2(printer); // Calling start methods for both threads // using the start() method t1.start(); t2.start(); }} Output: Finally wrapping off with the article let us discuss the major differences between Lock and Monitor in concurrency in java that is pictorially depicted in the image below shown as follows: Lock (Mutex) Monitor Note: As we see monitors themselves are implemented with the necessary support of locks, it is often said that they are not different but complementary in the nature of their existence are operating simmytarika5 surinderdawra388 as5853535 Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26120, "s": 25249, "text": "Java Concurrency basically deals with concepts like multithreading and other concurrent operations. This is done to ensure maximum and efficient utilization of CPU performance thereby reducing its idle time in general. Locks have been in existence to implement multithreading much before the monitors have come to usage. Back then locks (or mutex) were parts of threads inside the program that worked on flag mechanisms to synchronize with other threads. They have always been working as a tool to provide synchronous access control over resources and shared objects. With further advancements, the use of monitors started as a mechanism to handle access and coordinate threads which proved to be more efficient, error-free, and compatible in object-oriented programs. Before we move on to find the differences between the two let’s have a closer look into each of them." }, { "code": null, "e": 26148, "s": 26120, "text": "Overview of Lock (or Mutex)" }, { "code": null, "e": 26820, "s": 26148, "text": "Lock originally has been used in the logical section of the threads that were used to provide synchronized access control between the threads. Threads checked the availability of access control over shared objects through flags attached to the object that indicated whether or not the shared resource is free (unlocked) or busy (locked). Now the concurrency API provides support of using locks explicitly using Lock Interface in java. The explicit method has a finer control mechanism as compared to the implicit implementation of locks using monitors. Before we move on to discuss monitors let us look at an illustration that demonstrates the functioning of basic locks." }, { "code": null, "e": 26839, "s": 26820, "text": "Monitor – Overview" }, { "code": null, "e": 27562, "s": 26839, "text": "Monitor in Java Concurrency is a synchronization mechanism that provides the fundamental requirements of multithreading namely mutual exclusion between various threads and cooperation among threads working at common tasks. Monitors basically ‘monitor’ the access control of shared resources and objects among threads. Using this construct only one thread at a time gets access control over the critical section at the resource while other threads are blocked and made to wait until certain conditions. In Java, monitors are implemented using synchronized keyword (synchronized blocks, synchronized methods or classes). For example, let’s see how two threads t1 and t2 are synchronized to use a shared data printer object. " }, { "code": null, "e": 27567, "s": 27562, "text": "Java" }, { "code": "// Java Program to Illustrate Monitoe in Java Concurrency // Importing input output classesimport java.io.*; // Class 1// Helper classclass SharedDataPrinter { // Monitor implementation is carried on by // Using synchronous method // Method (synchronised) synchronized public void display(String str) { for (int i = 0; i < str.length(); i++) { System.out.print(str.charAt(i)); // Try-catch bloc kfor exceptions as we are // using sleep() method try { // Making thread to sleep for very // nanoseconds as passed in the arguments Thread.sleep(100); } catch (Exception e) { } } }} // Class 2// Helper class extending the Thread classclass Thread1 extends Thread { SharedDataPrinter p; // Thread public Thread1(SharedDataPrinter p) { // This keyword refers to current instance itself this.p = p; } // run() method for this thread invoked as // start() method is called in the main() method public void run() { // Print statement p.display(\"Geeks\"); }} // Class 2 (similar to class 1)// Helper class extending the Thread classclass Thread2 extends Thread { SharedDataPrinter p; public Thread2(SharedDataPrinter p) { this.p = p; } public void run() { // Print statement p.display(\" for Geeks\"); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Instance of a shared resource used to print // strings (single character at a time) SharedDataPrinter printer = new SharedDataPrinter(); // Thread objects sharing data printer Thread1 t1 = new Thread1(printer); Thread2 t2 = new Thread2(printer); // Calling start methods for both threads // using the start() method t1.start(); t2.start(); }}", "e": 29544, "s": 27567, "text": null }, { "code": null, "e": 29552, "s": 29544, "text": "Output:" }, { "code": null, "e": 29742, "s": 29552, "text": "Finally wrapping off with the article let us discuss the major differences between Lock and Monitor in concurrency in java that is pictorially depicted in the image below shown as follows: " }, { "code": null, "e": 29755, "s": 29742, "text": "Lock (Mutex)" }, { "code": null, "e": 29763, "s": 29755, "text": "Monitor" }, { "code": null, "e": 29770, "s": 29763, "text": "Note: " }, { "code": null, "e": 29963, "s": 29770, "text": "As we see monitors themselves are implemented with the necessary support of locks, it is often said that they are not different but complementary in the nature of their existence are operating" }, { "code": null, "e": 29978, "s": 29965, "text": "simmytarika5" }, { "code": null, "e": 29995, "s": 29978, "text": "surinderdawra388" }, { "code": null, "e": 30005, "s": 29995, "text": "as5853535" }, { "code": null, "e": 30012, "s": 30005, "text": "Picked" }, { "code": null, "e": 30017, "s": 30012, "text": "Java" }, { "code": null, "e": 30022, "s": 30017, "text": "Java" }, { "code": null, "e": 30120, "s": 30022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30135, "s": 30120, "text": "Stream In Java" }, { "code": null, "e": 30156, "s": 30135, "text": "Constructors in Java" }, { "code": null, "e": 30175, "s": 30156, "text": "Exceptions in Java" }, { "code": null, "e": 30205, "s": 30175, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30251, "s": 30205, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30268, "s": 30251, "text": "Generics in Java" }, { "code": null, "e": 30289, "s": 30268, "text": "Introduction to Java" }, { "code": null, "e": 30332, "s": 30289, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30368, "s": 30332, "text": "Internal Working of HashMap in Java" } ]
Algorithms | Misc | Question 11 - GeeksforGeeks
28 Jun, 2021 Given 8 identical coins out of which one coin is heavy and a pan balance. How many minimum number of measurements are needed to find the heavy coin?(A) 2(B) 3(C) 4(D) 7Answer: (A)Explanation: Divide the coins into three groups and name the coins according to there group: A: A1, A2, A3 B: B1, B2, B3 C: C1, C2 Measure group A and group B. Two cases arise: 1. They are equal. One more measurement is needed to find the heavy coin in group C. Total two measurements needed in this case. 2. They are not equal. Find the heavy group, say A. Pick any two coins from this group, say A1 and A3. Measure A1 and A3 in the pan balance. Two cases arise: 2.1 They are equal. A2 is the heavy coin. Total two measurements needed. 2.2 They are not equal. It is known which of A1 or A3 is heavy. Total two measurements needed. So, the above observations says that in any case, 2 measurements are enough to find the heavy coin. Follow up: Generalize the minimum number of measurements for n coins with one coin heavy. Quiz of this Question Algorithms-Misc Misc Algorithms Quiz Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithms | Graph Traversals | Question 2 Algorithms | Graph Traversals | Question 12 Algorithms | Analysis of Algorithms | Question 17 Algorithms | Recursion | Question 2 Algorithms | Recursion | Question 5 Algorithms | Backtracking | Question 1 Algorithms | Recursion | Question 3 Algorithms | Recursion | Question 4 Algorithms | NP Complete | Question 2 Algorithms | NP Complete | Question 1
[ { "code": null, "e": 26031, "s": 26003, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26223, "s": 26031, "text": "Given 8 identical coins out of which one coin is heavy and a pan balance. How many minimum number of measurements are needed to find the heavy coin?(A) 2(B) 3(C) 4(D) 7Answer: (A)Explanation:" }, { "code": null, "e": 27070, "s": 26223, "text": "Divide the coins into three groups and name the coins according to there group:\nA: A1, A2, A3\nB: B1, B2, B3\nC: C1, C2\n\nMeasure group A and group B. Two cases arise:\n1. They are equal. One more measurement is needed to find the heavy \n coin in group C. Total two measurements needed in this case.\n2. They are not equal. Find the heavy group, say A. Pick any two coins\n from this group, say A1 and A3. Measure A1 and A3 in the pan balance. \n Two cases arise:\n 2.1 They are equal. A2 is the heavy coin. Total two measurements \n needed.\n 2.2 They are not equal. It is known which of A1 or A3 is heavy. \n Total two measurements needed.\nSo, the above observations says that in any case, 2 measurements are enough\nto find the heavy coin.\n\nFollow up:\nGeneralize the minimum number of measurements for n coins \nwith one coin heavy.\n" }, { "code": null, "e": 27092, "s": 27070, "text": "Quiz of this Question" }, { "code": null, "e": 27108, "s": 27092, "text": "Algorithms-Misc" }, { "code": null, "e": 27113, "s": 27108, "text": "Misc" }, { "code": null, "e": 27129, "s": 27113, "text": "Algorithms Quiz" }, { "code": null, "e": 27134, "s": 27129, "text": "Misc" }, { "code": null, "e": 27139, "s": 27134, "text": "Misc" }, { "code": null, "e": 27237, "s": 27139, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27280, "s": 27237, "text": "Algorithms | Graph Traversals | Question 2" }, { "code": null, "e": 27324, "s": 27280, "text": "Algorithms | Graph Traversals | Question 12" }, { "code": null, "e": 27374, "s": 27324, "text": "Algorithms | Analysis of Algorithms | Question 17" }, { "code": null, "e": 27410, "s": 27374, "text": "Algorithms | Recursion | Question 2" }, { "code": null, "e": 27446, "s": 27410, "text": "Algorithms | Recursion | Question 5" }, { "code": null, "e": 27485, "s": 27446, "text": "Algorithms | Backtracking | Question 1" }, { "code": null, "e": 27521, "s": 27485, "text": "Algorithms | Recursion | Question 3" }, { "code": null, "e": 27557, "s": 27521, "text": "Algorithms | Recursion | Question 4" }, { "code": null, "e": 27595, "s": 27557, "text": "Algorithms | NP Complete | Question 2" } ]
Node.js http2session.ping() Method - GeeksforGeeks
11 Feb, 2022 The http2session.ping() is an inbuilt application programming interface of class http2session within http2 module which is used to sends a PING frame to the connected HTTP/2 peer. Syntax: const http2session.ping([payload, ]callback) Parameters: This method takes the optional ping payload buffer as a parameter. Return Value: This method return true if and only if the PING was sent otherwise false. How to generate the private key and public certificate? Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY----- Now save the file as private-key.pemPublic certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE----- Now save the file as public-cert.pem Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY----- Now save the file as private-key.pem -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY----- Now save the file as private-key.pem Public certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE----- Now save the file as public-cert.pem -----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE----- Now save the file as public-cert.pem Example 1: Filename: index.js javascript // Node.js program to demonstrate the// http2session.ping() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); const http2session = stream.session; // Sending ping to http2 peer // by using ping method const status = http2session.ping( Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); if(status) stream.end("ping is sent") else stream.end("ping is not sent") // Stopping the server // by using the close() method server.close(() => { console.log("server localSettings"); })}); server.listen(8000); // Creating and initializing client// by using tls.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request( { ':method': 'GET', ':path': '/' }); req.on('response', (responseHeaders) => { console.log("status : " + responseHeaders[":status"]);}); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\n)/gm, ""));}); req.on('end', () => { client.close(() => { console.log("client localSettings"); })}); Run the index.js file using the following command: node index.js Output: status : 200 Received: hello Received: ping is sent client localSettings server localSettings Example 2: Filename: index.js javascript // Node.js program to demonstrate the// http2session.ping() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { // Getting session object // by using session method const http2session = stream.session; // Sending ping to http2 peer // by using ping method const status = http2session.ping( Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); if(status) stream.end("ping is sent") else stream.end("ping is not sent") // Stopping the server // by using the close() method server.close(() => { console.log("server destroyed"); })}); server.listen(8000); // Creating and initializing client// by using tls.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request( { ':method': 'GET', ':path': '/' }); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\n)/gm, ""));}); req.on('end', () => { client.close(() => { console.log("client destroyed"); })}); Run the index.js file using the following command: node index.js Output: Received: ping is sent client destroyed server destroyed Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http2.html#http2_http2session_ping_payload_callback adnanirshad158 Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies How to connect Node.js with React.js ? Node.js Export Module Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript 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": 26267, "s": 26239, "text": "\n11 Feb, 2022" }, { "code": null, "e": 26447, "s": 26267, "text": "The http2session.ping() is an inbuilt application programming interface of class http2session within http2 module which is used to sends a PING frame to the connected HTTP/2 peer." }, { "code": null, "e": 26455, "s": 26447, "text": "Syntax:" }, { "code": null, "e": 26501, "s": 26455, "text": "const http2session.ping([payload, ]callback)\n" }, { "code": null, "e": 26580, "s": 26501, "text": "Parameters: This method takes the optional ping payload buffer as a parameter." }, { "code": null, "e": 26668, "s": 26580, "text": "Return Value: This method return true if and only if the PING was sent otherwise false." }, { "code": null, "e": 26724, "s": 26668, "text": "How to generate the private key and public certificate?" }, { "code": null, "e": 28737, "s": 26724, "text": "Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----\nNow save the file as private-key.pemPublic certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----\nNow save the file as public-cert.pem" }, { "code": null, "e": 29720, "s": 28737, "text": "Private key: Open notepad and copy paste the following key:-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----\nNow save the file as private-key.pem" }, { "code": null, "e": 30608, "s": 29720, "text": "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----\n" }, { "code": null, "e": 30645, "s": 30608, "text": "Now save the file as private-key.pem" }, { "code": null, "e": 31676, "s": 30645, "text": "Public certificate: Open notepad and copy paste the following key:-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----\nNow save the file as public-cert.pem" }, { "code": null, "e": 32605, "s": 31676, "text": "-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----\n" }, { "code": null, "e": 32642, "s": 32605, "text": "Now save the file as public-cert.pem" }, { "code": null, "e": 32672, "s": 32642, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 32683, "s": 32672, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// http2session.ping() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); const http2session = stream.session; // Sending ping to http2 peer // by using ping method const status = http2session.ping( Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); if(status) stream.end(\"ping is sent\") else stream.end(\"ping is not sent\") // Stopping the server // by using the close() method server.close(() => { console.log(\"server localSettings\"); })}); server.listen(8000); // Creating and initializing client// by using tls.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request( { ':method': 'GET', ':path': '/' }); req.on('response', (responseHeaders) => { console.log(\"status : \" + responseHeaders[\":status\"]);}); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\\n)/gm, \"\"));}); req.on('end', () => { client.close(() => { console.log(\"client localSettings\"); })});", "e": 34304, "s": 32683, "text": null }, { "code": null, "e": 34355, "s": 34304, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 34370, "s": 34355, "text": "node index.js\n" }, { "code": null, "e": 34378, "s": 34370, "text": "Output:" }, { "code": null, "e": 34473, "s": 34378, "text": "status : 200\nReceived: hello\nReceived: ping is sent\nclient localSettings\nserver localSettings\n" }, { "code": null, "e": 34503, "s": 34473, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 34514, "s": 34503, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// http2session.ping() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { // Getting session object // by using session method const http2session = stream.session; // Sending ping to http2 peer // by using ping method const status = http2session.ping( Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); if(status) stream.end(\"ping is sent\") else stream.end(\"ping is not sent\") // Stopping the server // by using the close() method server.close(() => { console.log(\"server destroyed\"); })}); server.listen(8000); // Creating and initializing client// by using tls.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request( { ':method': 'GET', ':path': '/' }); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\\n)/gm, \"\"));}); req.on('end', () => { client.close(() => { console.log(\"client destroyed\"); })});", "e": 35986, "s": 34514, "text": null }, { "code": null, "e": 36037, "s": 35986, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 36052, "s": 36037, "text": "node index.js\n" }, { "code": null, "e": 36060, "s": 36052, "text": "Output:" }, { "code": null, "e": 36118, "s": 36060, "text": "Received: ping is sent\nclient destroyed\nserver destroyed\n" }, { "code": null, "e": 36227, "s": 36118, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http2.html#http2_http2session_ping_payload_callback" }, { "code": null, "e": 36242, "s": 36227, "text": "adnanirshad158" }, { "code": null, "e": 36258, "s": 36242, "text": "Node.js-Methods" }, { "code": null, "e": 36266, "s": 36258, "text": "Node.js" }, { "code": null, "e": 36283, "s": 36266, "text": "Web Technologies" }, { "code": null, "e": 36381, "s": 36283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36451, "s": 36381, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 36490, "s": 36451, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 36512, "s": 36490, "text": "Node.js Export Module" }, { "code": null, "e": 36539, "s": 36512, "text": "Mongoose Populate() Method" }, { "code": null, "e": 36564, "s": 36539, "text": "Mongoose find() Function" }, { "code": null, "e": 36604, "s": 36564, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 36649, "s": 36604, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 36692, "s": 36649, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36742, "s": 36692, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to design a responsive website?
A responsive website is a website that looks good and amazing on all devices i.e. desktops, tablets, and cell phones. A website should have a responsive design to make it responsive. It’s all about playing around with HTML and CSS for changing the size, hiding, or enlarging the screen. Let’s see an example and what does responsive means while resizing a website, The website design on Desktop − The website design looks like this on a tablet. You can easily compare the changes with the above shown desktop screenshot − The website design looks like this on Mobile − To develop a responsive website, which looks good irrespective of the device size, you need to work on the following concepts − A viewport is used to control layout on mobile browsers. It is used inside the <meta> tag to give the browser instructions on how to work for controlling the web page’s dimensions and scaling. <meta name="viewport" content="width=device-width, initial-scale=1.0"> Here, The width=device-width sets the width of the page in order to follow the screen-width of the device. The initial-scale=1.0 is to set the initial zoom level. This helps when the page gets loaded by the web browser for the first time. With Media queries, add a breakpoint where some parts of the design behave differently on each side of the breakpoint. For images to be responsive, you need to set the width property to 100% and height to auto.
[ { "code": null, "e": 1349, "s": 1062, "text": "A responsive website is a website that looks good and amazing on all devices i.e. desktops, tablets, and cell phones. A website should have a responsive design to make it responsive. It’s all about playing around with HTML and CSS for changing the size, hiding, or enlarging the screen." }, { "code": null, "e": 1427, "s": 1349, "text": "Let’s see an example and what does responsive means while resizing a website," }, { "code": null, "e": 1459, "s": 1427, "text": "The website design on Desktop −" }, { "code": null, "e": 1584, "s": 1459, "text": "The website design looks like this on a tablet. You can easily compare the changes with the above shown desktop screenshot −" }, { "code": null, "e": 1631, "s": 1584, "text": "The website design looks like this on Mobile −" }, { "code": null, "e": 1759, "s": 1631, "text": "To develop a responsive website, which looks good irrespective of the device size, you need to work on the following concepts −" }, { "code": null, "e": 1952, "s": 1759, "text": "A viewport is used to control layout on mobile browsers. It is used inside the <meta> tag to give the browser instructions on how to work for controlling the web page’s dimensions and scaling." }, { "code": null, "e": 2023, "s": 1952, "text": "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" }, { "code": null, "e": 2030, "s": 2023, "text": "Here, " }, { "code": null, "e": 2263, "s": 2030, "text": "The width=device-width sets the width of the page in order to follow the screen-width of the device. The initial-scale=1.0 is to set the initial zoom level. This helps when the page gets loaded by the web browser for the first time." }, { "code": null, "e": 2383, "s": 2263, "text": "With Media queries, add a breakpoint where some parts of the design behave differently on each side of the breakpoint. " }, { "code": null, "e": 2475, "s": 2383, "text": "For images to be responsive, you need to set the width property to 100% and height to auto." } ]
Groovy - Exception Handling
Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application. Exceptions are broadly classified into the following categories − Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. One classical case is the FileNotFoundException. Suppose you had the following codein your application which reads from a file in E drive. class Example { static void main(String[] args) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } } if the File (file.txt) is not there in the E drive then the following exception will be raised. Caught: java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified). java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified). Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake. class Example { static void main(String[] args) { def arr = new int[3]; arr[5] = 5; } } When the above code is executed the following exception will be raised. Caught: java.lang.ArrayIndexOutOfBoundsException: 5 java.lang.ArrayIndexOutOfBoundsException: 5 Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. These are errors which the program can never recover from and will cause the program to crash. The following diagram shows how the hierarchy of exceptions in Groovy is organized. It’s all based on the hierarchy defined in Java. A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. try { //Protected code } catch(ExceptionName e1) { //Catch block } All of your code which could raise an exception is placed in the Protected code block. In the catch block, you can write custom code to handle your exception so that the application can recover from the exception. Let’s look at an example of the similar code we saw above for accessing an array with an index value which is greater than the size of the array. But this time let’s wrap our code in a try/catch block. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; } catch(Exception ex) { println("Catching the exception"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − Catching the exception Let's move on after the exception From the above code, we wrap out faulty code in the try block. In the catch block we are just catching our exception and outputting a message that an exception has occurred. One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly. Let’s modify our above code to catch the ArrayIndexOutOfBoundsException specifically. Following is the code snippet. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; }catch(ArrayIndexOutOfBoundsException ex) { println("Catching the Array out of Bounds exception"); }catch(Exception ex) { println("Catching the exception"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − Catching the Aray out of Bounds exception Let's move on after the exception From the above code you can see that the ArrayIndexOutOfBoundsException catch block is caught first because it means the criteria of the exception. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. The syntax for this block is given below. try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } finally { //The finally block always executes. } Let’s modify our above code and add the finally block of code. Following is the code snippet. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; } catch(ArrayIndexOutOfBoundsException ex) { println("Catching the Array out of Bounds exception"); }catch(Exception ex) { println("Catching the exception"); } finally { println("The final block"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − Catching the Array out of Bounds exception The final block Let's move on after the exception Following are the Exception methods available in Groovy − Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. Returns the cause of the exception as represented by a Throwable object. Returns the name of the class concatenated with the result of getMessage() Prints the result of toString() along with the stack trace to System.err, the error output stream. Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. Following is the code example using some of the methods given above − class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; }catch(ArrayIndexOutOfBoundsException ex) { println(ex.toString()); println(ex.getMessage()); println(ex.getStackTrace()); } catch(Exception ex) { println("Catching the exception"); }finally { println("The final block"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − java.lang.ArrayIndexOutOfBoundsException: 5 5 [org.codehaus.groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod$MyPojoMetaMet hodSite.call(IntegerArrayPutAtMetaMethod.java:75), org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) , org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) , org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) , Example.main(Sample:8), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) , java.lang.reflect.Method.invoke(Method.java:606), org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93), groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325), groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1443), org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:893), groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:287), groovy.lang.GroovyShell.run(GroovyShell.java:524), groovy.lang.GroovyShell.run(GroovyShell.java:513), groovy.ui.GroovyMain.processOnce(GroovyMain.java:652), groovy.ui.GroovyMain.run(GroovyMain.java:384), groovy.ui.GroovyMain.process(GroovyMain.java:370), groovy.ui.GroovyMain.processArgs(GroovyMain.java:129), groovy.ui.GroovyMain.main(GroovyMain.java:109), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) , java.lang.reflect.Method.invoke(Method.java:606), org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109), org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) , java.lang.reflect.Method.invoke(Method.java:606), com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)] The final block Let's move on after the exception 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2384, "s": 2238, "text": "Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained." }, { "code": null, "e": 2526, "s": 2384, "text": "Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application." }, { "code": null, "e": 2592, "s": 2526, "text": "Exceptions are broadly classified into the following categories −" }, { "code": null, "e": 2801, "s": 2592, "text": "Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time." }, { "code": null, "e": 3010, "s": 2801, "text": "Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time." }, { "code": null, "e": 3149, "s": 3010, "text": "One classical case is the FileNotFoundException. Suppose you had the following codein your application which reads from a file in E drive." }, { "code": null, "e": 3298, "s": 3149, "text": "class Example {\n static void main(String[] args) {\n File file = new File(\"E://file.txt\");\n FileReader fr = new FileReader(file);\n } \n}" }, { "code": null, "e": 3395, "s": 3298, "text": "if the File (file.txt) is not there in the E drive then the following exception will be raised." }, { "code": null, "e": 3491, "s": 3395, "text": "Caught: java.io.FileNotFoundException: E:\\file.txt (The system cannot find the file specified)." }, { "code": null, "e": 3579, "s": 3491, "text": "java.io.FileNotFoundException: E:\\file.txt (The system cannot find the file specified)." }, { "code": null, "e": 3851, "s": 3579, "text": "Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime." }, { "code": null, "e": 4123, "s": 3851, "text": "Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime." }, { "code": null, "e": 4341, "s": 4123, "text": "One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake." }, { "code": null, "e": 4448, "s": 4341, "text": "class Example {\n static void main(String[] args) {\n def arr = new int[3];\n arr[5] = 5;\n } \n}" }, { "code": null, "e": 4521, "s": 4448, "text": "When the above code is executed the following exception will be raised." }, { "code": null, "e": 4573, "s": 4521, "text": "Caught: java.lang.ArrayIndexOutOfBoundsException: 5" }, { "code": null, "e": 4617, "s": 4573, "text": "java.lang.ArrayIndexOutOfBoundsException: 5" }, { "code": null, "e": 4712, "s": 4617, "text": "Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc." }, { "code": null, "e": 4807, "s": 4712, "text": "Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc." }, { "code": null, "e": 4902, "s": 4807, "text": "These are errors which the program can never recover from and will cause the program to crash." }, { "code": null, "e": 5035, "s": 4902, "text": "The following diagram shows how the hierarchy of exceptions in Groovy is organized. It’s all based on the hierarchy defined in Java." }, { "code": null, "e": 5194, "s": 5035, "text": "A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception." }, { "code": null, "e": 5270, "s": 5194, "text": "try { \n //Protected code \n} catch(ExceptionName e1) {\n //Catch block \n}" }, { "code": null, "e": 5357, "s": 5270, "text": "All of your code which could raise an exception is placed in the Protected code block." }, { "code": null, "e": 5484, "s": 5357, "text": "In the catch block, you can write custom code to handle your exception so that the application can recover from the exception." }, { "code": null, "e": 5686, "s": 5484, "text": "Let’s look at an example of the similar code we saw above for accessing an array with an index value which is greater than the size of the array. But this time let’s wrap our code in a try/catch block." }, { "code": null, "e": 5947, "s": 5686, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n } catch(Exception ex) {\n println(\"Catching the exception\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n }\n}" }, { "code": null, "e": 6013, "s": 5947, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 6072, "s": 6013, "text": "Catching the exception \nLet's move on after the exception\n" }, { "code": null, "e": 6246, "s": 6072, "text": "From the above code, we wrap out faulty code in the try block. In the catch block we are just catching our exception and outputting a message that an exception has occurred." }, { "code": null, "e": 6432, "s": 6246, "text": "One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly." }, { "code": null, "e": 6549, "s": 6432, "text": "Let’s modify our above code to catch the ArrayIndexOutOfBoundsException specifically. Following is the code snippet." }, { "code": null, "e": 6924, "s": 6549, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n }catch(ArrayIndexOutOfBoundsException ex) {\n println(\"Catching the Array out of Bounds exception\");\n }catch(Exception ex) {\n println(\"Catching the exception\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n } \n}" }, { "code": null, "e": 6990, "s": 6924, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 7068, "s": 6990, "text": "Catching the Aray out of Bounds exception \nLet's move on after the exception\n" }, { "code": null, "e": 7216, "s": 7068, "text": "From the above code you can see that the ArrayIndexOutOfBoundsException catch block is caught first because it means the criteria of the exception." }, { "code": null, "e": 7357, "s": 7216, "text": "The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception." }, { "code": null, "e": 7539, "s": 7357, "text": "Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. The syntax for this block is given below." }, { "code": null, "e": 7767, "s": 7539, "text": "try { \n //Protected code \n} catch(ExceptionType1 e1) { \n //Catch block \n} catch(ExceptionType2 e2) { \n //Catch block \n} catch(ExceptionType3 e3) { \n //Catch block \n} finally {\n //The finally block always executes. \n}\n" }, { "code": null, "e": 7861, "s": 7767, "text": "Let’s modify our above code and add the finally block of code. Following is the code snippet." }, { "code": null, "e": 8293, "s": 7861, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n } catch(ArrayIndexOutOfBoundsException ex) {\n println(\"Catching the Array out of Bounds exception\");\n }catch(Exception ex) {\n println(\"Catching the exception\");\n } finally {\n println(\"The final block\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n } \n} " }, { "code": null, "e": 8359, "s": 8293, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 8455, "s": 8359, "text": "Catching the Array out of Bounds exception \nThe final block \nLet's move on after the exception\n" }, { "code": null, "e": 8513, "s": 8455, "text": "Following are the Exception methods available in Groovy −" }, { "code": null, "e": 8637, "s": 8513, "text": "Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor." }, { "code": null, "e": 8710, "s": 8637, "text": "Returns the cause of the exception as represented by a Throwable object." }, { "code": null, "e": 8785, "s": 8710, "text": "Returns the name of the class concatenated with the result of getMessage()" }, { "code": null, "e": 8884, "s": 8785, "text": "Prints the result of toString() along with the stack trace to System.err, the error output stream." }, { "code": null, "e": 9095, "s": 8884, "text": "Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack." }, { "code": null, "e": 9227, "s": 9095, "text": "Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace." }, { "code": null, "e": 9297, "s": 9227, "text": "Following is the code example using some of the methods given above −" }, { "code": null, "e": 9771, "s": 9297, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n }catch(ArrayIndexOutOfBoundsException ex) {\n println(ex.toString());\n println(ex.getMessage());\n println(ex.getStackTrace()); \n } catch(Exception ex) {\n println(\"Catching the exception\");\n }finally {\n println(\"The final block\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n } \n}" }, { "code": null, "e": 9837, "s": 9771, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 12139, "s": 9837, "text": "java.lang.ArrayIndexOutOfBoundsException: 5 \n5 \n[org.codehaus.groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod$MyPojoMetaMet \nhodSite.call(IntegerArrayPutAtMetaMethod.java:75), \norg.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) ,\norg.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) ,\norg.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) ,\nExample.main(Sample:8), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),\nsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),\nsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,\njava.lang.reflect.Method.invoke(Method.java:606),\norg.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93),\ngroovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325),\ngroovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1443),\norg.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:893),\ngroovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:287),\ngroovy.lang.GroovyShell.run(GroovyShell.java:524),\ngroovy.lang.GroovyShell.run(GroovyShell.java:513),\ngroovy.ui.GroovyMain.processOnce(GroovyMain.java:652),\ngroovy.ui.GroovyMain.run(GroovyMain.java:384),\ngroovy.ui.GroovyMain.process(GroovyMain.java:370),\ngroovy.ui.GroovyMain.processArgs(GroovyMain.java:129),\ngroovy.ui.GroovyMain.main(GroovyMain.java:109),\nsun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),\nsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),\nsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,\njava.lang.reflect.Method.invoke(Method.java:606),\norg.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109),\norg.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131),\nsun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),\nsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),\nsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,\njava.lang.reflect.Method.invoke(Method.java:606),\ncom.intellij.rt.execution.application.AppMain.main(AppMain.java:144)]\n \nThe final block \nLet's move on after the exception \n" }, { "code": null, "e": 12172, "s": 12139, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 12190, "s": 12172, "text": " Krishna Sakinala" }, { "code": null, "e": 12225, "s": 12190, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12243, "s": 12225, "text": " Packt Publishing" }, { "code": null, "e": 12250, "s": 12243, "text": " Print" }, { "code": null, "e": 12261, "s": 12250, "text": " Add Notes" } ]
A better EDA with Pandas-profiling | by Thomas Gey | Towards Data Science
Mostly in Data Science, data we collect aren’t as clean and complete as available datasets on internet, designed and prepared for the application of machine learning models. Mostly, data comes from external sources, is not well structured or is simply incomplete, and it’s your job to make this data welcoming and usable! While data scientists are aware of the importance of data quality, this is not necessarily the case for business leaders. They focus more on adopting technology as early as possible to maintain a competitive advantage and often have little understanding of the practical aspects. This means that people use everything in their datasets and hope for the best, under the pretext that quantity can compensate for quality. Because of this difference of mindset, a data scientist spends 80% of his time preparing data sets before modelling. Why 80% of his time? There’s missing values, unbalanced data, column names without any meaning, deduped data, outdated data and other reasons. Awareness of the importance of data is recent. As a result, even if the trend is reversed, the data is rarely easily accessible and well structured. medium.com The consequence of a bad dataset is simple and logic: predictive models made with these datasets will have low accuracy and low efficiency. Train a model with incorrect data will create a bias and your results will be far from reality. A bad model is a model unable to be deployed, so its a loss of money for the company developing the model. A car built with rusted pieces will not drive correctly or at worst, not drive at all... and nobody wants to use or buy a rusted car! So, your dataset is an essential key to your project. Its technical and economic success depends on the quality of data you selected. During a machine learning project, skipping this data evaluation step can lead to a considerable waste of time and you will have to start your project over again from the beginning. It seems logic now data scientists spend so much time investigating and preparing datasets! becominghuman.ai Low quality data will only lead to low quality results. To ensure that our datasets are useful, a good practice is EDA, Exploratory Data Analysis. An EDA is a way to familiarize yourself with the dataset. Through this reflection work, it is the assurance of working with interesting, coherent and cleaned data. This step is very visual and is based on summary statistics and graphical representations. By an EDA, data scientists can find which features are important or the correlation between them. On the other hand, an EDA allows you to discover erroneous or missing values, detect anomalies or reject a hypothesis. The selection of feature variables will be later used for machine learning. In general, an Exploratory Data Analysis is followed by a feature engineering/data augmentation step where you work on the initial data to bring them additional value towardsdatascience.com For this example, I took a dataset that is perfect for EDA, FIFA 19 complete player dataset. Data contains multiple data types, missing values, and many metrics are applicable. Several complete analyses on this dataset are available here. I use JupyterLab as IDE because of its flexibility and its user-friendly interface. Let’s start by importing the data from the CSV file using Pandas library: Pretty quick to load. Now an overview with data.sample(5), a method that selects randomly 5 rows. It’s better to use .sample() than .head() if you don’t know how your data is sorted. Let’s get some descriptive statistics with .describe(). This method “summarizes the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values”. Now we have descriptive statistics, we’re gonna check missing values. We’ll just print 10 ordered features with more than 10% missing values: As you can see, doing an EDA on a notebook is convenient and efficient for a data scientist. Nevertheless, the visual remains summary and is print by metrics. Let’s see with Pandas-profiling now how we can print this information dynamically and with fewer efforts. It is by seeing that we learn Github description: “Generates profile reports from a pandas Dataframe” Pandas-profiling brings all the bricks together to a complete EDA: Most frequent values, missing values, correlations, quantile and descriptive statistics, data length and more. Thanks to these metrics, you’ll quickly see the distribution and disparity of your data. That information is essential to know if data is useful for future usages. github.com Pandas-profiling presents different metrics in a structured way through an HTML report. Thanks to its interaction, it is easy to switch from one feature to another and access its metrics. Let’s see how to use it: pip install pandas-profiling Using our previous FIFA Dataset: import pandas as pdimport pandas_profilingdata_fifa = pd.read_csv('fifa.csv')profile = data_fifa.profile_report(title='Pandas Profiling Report')profile.to_file(output_file="fifa_pandas_profiling.html") In the code above, we only import pandas and pandas-profiling dependencies, read our CSV file and call the profile_report() method because pandas_profiling extends the pandas DataFrame with data_fifa.profile_report() . Then, we export our ProfileReport object as an HTML file with .to_file() . And voilà! Here, our HTML file is located at the root of the folder : The image above presents the “overview” part of the report. This part briefly presents information on the type of variables, missing values, or the size of the dataset. Pandas-profiling uses matplotlib library for graphs and jinja2 as the template engine for its interface. As a freelance, when I have to work on a new dataset for a customer, I always produce first a pandas-profiling, it helps me to soak up the dataset. This practice allows me to quantify the processing time of the dataset. How many features seem to be correct? How many contain missing values? What percentage for each feature? Which variable depends on another? Also, this report can serve as an interface to give a global aspect of data health to a client. Instead of presenting your analysis on your Jupyter notebook, graph after graph with code between, the report centralizes the metrics by feature, and has a more user-friendly interface. My clients like to have a complete follow-up of the missions I carry out for them and would like to know my progress regularly. I very often use this report to give a health status of the data. This step is followed by the second step of more in-depth data analysis and visualization. Big data’s potential just keeps growing. Taking full advantage means companies must incorporate analytics and predictive systems into their strategic vision and use it to make better, faster decisions. Often, the data we retrieve contains erroneous or missing data. To be truly effective, these data must be analyzed and processed. That’s the role of the data scientist. With pandas-profiling, data scientists are able to produce quick exploratory data analysis reports with fewer efforts. The report is clear, easy to use and readable by anybody with basic statistic skills. With this global understanding of what you have in front of you, you will have some food for thought to go further in your analysis, start processing the data or looking for external data sources to enhance your quality data. It’s crucial to pre-process data and improve its quality because the quality of our predictive machine learning model is directly correlated with the quality of the data that we feed into our model. I hope you like this little introduction to Pandas-profiling! This is the first article I’m writing on medium, I’m interested in any comments and improvements!
[ { "code": null, "e": 494, "s": 172, "text": "Mostly in Data Science, data we collect aren’t as clean and complete as available datasets on internet, designed and prepared for the application of machine learning models. Mostly, data comes from external sources, is not well structured or is simply incomplete, and it’s your job to make this data welcoming and usable!" }, { "code": null, "e": 913, "s": 494, "text": "While data scientists are aware of the importance of data quality, this is not necessarily the case for business leaders. They focus more on adopting technology as early as possible to maintain a competitive advantage and often have little understanding of the practical aspects. This means that people use everything in their datasets and hope for the best, under the pretext that quantity can compensate for quality." }, { "code": null, "e": 1030, "s": 913, "text": "Because of this difference of mindset, a data scientist spends 80% of his time preparing data sets before modelling." }, { "code": null, "e": 1322, "s": 1030, "text": "Why 80% of his time? There’s missing values, unbalanced data, column names without any meaning, deduped data, outdated data and other reasons. Awareness of the importance of data is recent. As a result, even if the trend is reversed, the data is rarely easily accessible and well structured." }, { "code": null, "e": 1333, "s": 1322, "text": "medium.com" }, { "code": null, "e": 1810, "s": 1333, "text": "The consequence of a bad dataset is simple and logic: predictive models made with these datasets will have low accuracy and low efficiency. Train a model with incorrect data will create a bias and your results will be far from reality. A bad model is a model unable to be deployed, so its a loss of money for the company developing the model. A car built with rusted pieces will not drive correctly or at worst, not drive at all... and nobody wants to use or buy a rusted car!" }, { "code": null, "e": 2218, "s": 1810, "text": "So, your dataset is an essential key to your project. Its technical and economic success depends on the quality of data you selected. During a machine learning project, skipping this data evaluation step can lead to a considerable waste of time and you will have to start your project over again from the beginning. It seems logic now data scientists spend so much time investigating and preparing datasets!" }, { "code": null, "e": 2235, "s": 2218, "text": "becominghuman.ai" }, { "code": null, "e": 2291, "s": 2235, "text": "Low quality data will only lead to low quality results." }, { "code": null, "e": 2382, "s": 2291, "text": "To ensure that our datasets are useful, a good practice is EDA, Exploratory Data Analysis." }, { "code": null, "e": 2637, "s": 2382, "text": "An EDA is a way to familiarize yourself with the dataset. Through this reflection work, it is the assurance of working with interesting, coherent and cleaned data. This step is very visual and is based on summary statistics and graphical representations." }, { "code": null, "e": 2930, "s": 2637, "text": "By an EDA, data scientists can find which features are important or the correlation between them. On the other hand, an EDA allows you to discover erroneous or missing values, detect anomalies or reject a hypothesis. The selection of feature variables will be later used for machine learning." }, { "code": null, "e": 3097, "s": 2930, "text": "In general, an Exploratory Data Analysis is followed by a feature engineering/data augmentation step where you work on the initial data to bring them additional value" }, { "code": null, "e": 3120, "s": 3097, "text": "towardsdatascience.com" }, { "code": null, "e": 3443, "s": 3120, "text": "For this example, I took a dataset that is perfect for EDA, FIFA 19 complete player dataset. Data contains multiple data types, missing values, and many metrics are applicable. Several complete analyses on this dataset are available here. I use JupyterLab as IDE because of its flexibility and its user-friendly interface." }, { "code": null, "e": 3517, "s": 3443, "text": "Let’s start by importing the data from the CSV file using Pandas library:" }, { "code": null, "e": 3700, "s": 3517, "text": "Pretty quick to load. Now an overview with data.sample(5), a method that selects randomly 5 rows. It’s better to use .sample() than .head() if you don’t know how your data is sorted." }, { "code": null, "e": 3875, "s": 3700, "text": "Let’s get some descriptive statistics with .describe(). This method “summarizes the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values”." }, { "code": null, "e": 4017, "s": 3875, "text": "Now we have descriptive statistics, we’re gonna check missing values. We’ll just print 10 ordered features with more than 10% missing values:" }, { "code": null, "e": 4282, "s": 4017, "text": "As you can see, doing an EDA on a notebook is convenient and efficient for a data scientist. Nevertheless, the visual remains summary and is print by metrics. Let’s see with Pandas-profiling now how we can print this information dynamically and with fewer efforts." }, { "code": null, "e": 4312, "s": 4282, "text": "It is by seeing that we learn" }, { "code": null, "e": 4384, "s": 4312, "text": "Github description: “Generates profile reports from a pandas Dataframe”" }, { "code": null, "e": 4726, "s": 4384, "text": "Pandas-profiling brings all the bricks together to a complete EDA: Most frequent values, missing values, correlations, quantile and descriptive statistics, data length and more. Thanks to these metrics, you’ll quickly see the distribution and disparity of your data. That information is essential to know if data is useful for future usages." }, { "code": null, "e": 4737, "s": 4726, "text": "github.com" }, { "code": null, "e": 4925, "s": 4737, "text": "Pandas-profiling presents different metrics in a structured way through an HTML report. Thanks to its interaction, it is easy to switch from one feature to another and access its metrics." }, { "code": null, "e": 4950, "s": 4925, "text": "Let’s see how to use it:" }, { "code": null, "e": 4979, "s": 4950, "text": "pip install pandas-profiling" }, { "code": null, "e": 5012, "s": 4979, "text": "Using our previous FIFA Dataset:" }, { "code": null, "e": 5214, "s": 5012, "text": "import pandas as pdimport pandas_profilingdata_fifa = pd.read_csv('fifa.csv')profile = data_fifa.profile_report(title='Pandas Profiling Report')profile.to_file(output_file=\"fifa_pandas_profiling.html\")" }, { "code": null, "e": 5508, "s": 5214, "text": "In the code above, we only import pandas and pandas-profiling dependencies, read our CSV file and call the profile_report() method because pandas_profiling extends the pandas DataFrame with data_fifa.profile_report() . Then, we export our ProfileReport object as an HTML file with .to_file() ." }, { "code": null, "e": 5579, "s": 5508, "text": "And voilà! Here, our HTML file is located at the root of the folder :" }, { "code": null, "e": 5748, "s": 5579, "text": "The image above presents the “overview” part of the report. This part briefly presents information on the type of variables, missing values, or the size of the dataset." }, { "code": null, "e": 5853, "s": 5748, "text": "Pandas-profiling uses matplotlib library for graphs and jinja2 as the template engine for its interface." }, { "code": null, "e": 6213, "s": 5853, "text": "As a freelance, when I have to work on a new dataset for a customer, I always produce first a pandas-profiling, it helps me to soak up the dataset. This practice allows me to quantify the processing time of the dataset. How many features seem to be correct? How many contain missing values? What percentage for each feature? Which variable depends on another?" }, { "code": null, "e": 6780, "s": 6213, "text": "Also, this report can serve as an interface to give a global aspect of data health to a client. Instead of presenting your analysis on your Jupyter notebook, graph after graph with code between, the report centralizes the metrics by feature, and has a more user-friendly interface. My clients like to have a complete follow-up of the missions I carry out for them and would like to know my progress regularly. I very often use this report to give a health status of the data. This step is followed by the second step of more in-depth data analysis and visualization." }, { "code": null, "e": 7356, "s": 6780, "text": "Big data’s potential just keeps growing. Taking full advantage means companies must incorporate analytics and predictive systems into their strategic vision and use it to make better, faster decisions. Often, the data we retrieve contains erroneous or missing data. To be truly effective, these data must be analyzed and processed. That’s the role of the data scientist. With pandas-profiling, data scientists are able to produce quick exploratory data analysis reports with fewer efforts. The report is clear, easy to use and readable by anybody with basic statistic skills." }, { "code": null, "e": 7781, "s": 7356, "text": "With this global understanding of what you have in front of you, you will have some food for thought to go further in your analysis, start processing the data or looking for external data sources to enhance your quality data. It’s crucial to pre-process data and improve its quality because the quality of our predictive machine learning model is directly correlated with the quality of the data that we feed into our model." } ]
numpy.rollaxis
This function rolls the specified axis backwards, until it lies in a specified position. The function takes three parameters. numpy.rollaxis(arr, axis, start) Where, arr Input array axis Axis to roll backwards. The position of the other axes do not change relative to one another start Zero by default leading to the complete roll. Rolls until it reaches the specified position # It creates 3 dimensional ndarray import numpy as np a = np.arange(8).reshape(2,2,2) print 'The original array:' print a print '\n' # to roll axis-2 to axis-0 (along width to along depth) print 'After applying rollaxis function:' print np.rollaxis(a,2) # to roll axis 0 to 1 (along width to height) print '\n' print 'After applying rollaxis function:' print np.rollaxis(a,2,1) Its output is as follows − The original array: [[[0 1] [2 3]] [[4 5] [6 7]]] After applying rollaxis function: [[[0 2] [4 6]] [[1 3] [5 7]]] After applying rollaxis function: [[[0 2] [1 3]] [[4 6] [5 7]]] 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2369, "s": 2243, "text": "This function rolls the specified axis backwards, until it lies in a specified position. The function takes three parameters." }, { "code": null, "e": 2403, "s": 2369, "text": "numpy.rollaxis(arr, axis, start)\n" }, { "code": null, "e": 2410, "s": 2403, "text": "Where," }, { "code": null, "e": 2414, "s": 2410, "text": "arr" }, { "code": null, "e": 2426, "s": 2414, "text": "Input array" }, { "code": null, "e": 2431, "s": 2426, "text": "axis" }, { "code": null, "e": 2524, "s": 2431, "text": "Axis to roll backwards. The position of the other axes do not change relative to one another" }, { "code": null, "e": 2530, "s": 2524, "text": "start" }, { "code": null, "e": 2622, "s": 2530, "text": "Zero by default leading to the complete roll. Rolls until it reaches the specified position" }, { "code": null, "e": 3015, "s": 2622, "text": "# It creates 3 dimensional ndarray \nimport numpy as np \na = np.arange(8).reshape(2,2,2) \n\nprint 'The original array:' \nprint a \nprint '\\n'\n# to roll axis-2 to axis-0 (along width to along depth) \n\nprint 'After applying rollaxis function:' \nprint np.rollaxis(a,2) \n# to roll axis 0 to 1 (along width to height) \nprint '\\n' \n\nprint 'After applying rollaxis function:' \nprint np.rollaxis(a,2,1)" }, { "code": null, "e": 3042, "s": 3015, "text": "Its output is as follows −" }, { "code": null, "e": 3232, "s": 3042, "text": "The original array:\n[[[0 1]\n [2 3]]\n [[4 5]\n [6 7]]]\n\nAfter applying rollaxis function:\n[[[0 2]\n [4 6]]\n [[1 3]\n [5 7]]]\n\nAfter applying rollaxis function:\n[[[0 2]\n [1 3]]\n [[4 6]\n [5 7]]]\n" }, { "code": null, "e": 3265, "s": 3232, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3282, "s": 3265, "text": " Abhilash Nelson" }, { "code": null, "e": 3315, "s": 3282, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 3350, "s": 3315, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3383, "s": 3350, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 3418, "s": 3383, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3453, "s": 3418, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3465, "s": 3453, "text": " Akbar Khan" }, { "code": null, "e": 3498, "s": 3465, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3513, "s": 3498, "text": " Pruthviraja L" }, { "code": null, "e": 3546, "s": 3513, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3553, "s": 3546, "text": " Anmol" }, { "code": null, "e": 3560, "s": 3553, "text": " Print" }, { "code": null, "e": 3571, "s": 3560, "text": " Add Notes" } ]
GATE | GATE-CS-2016 (Set 1) | Question 42 - GeeksforGeeks
30 Sep, 2021 The stage delays in a 4-stage pipeline are 800, 500, 400 and 300 picoseconds. The first stage (with delay 800 picoseconds) is replaced with a functionally equivalent design involving two stages with respective delays 600 and 350 picoseconds. The throughput increase of the pipeline is _______ percent. [This Question was originally a Fill-in-the-Blanks question](A) 33 or 34(B) 30 or 31(C) 38 or 39(D) 100Answer: (A)Explanation: Throughput of 1st case T1: 1/max delay =1/800 Throughput of 2nd case T2: 1/max delay= 1/600 %age increase in throughput: (T2-T1)/T1 = ( (1/600) - (1/800) ) / (1/800) = 33.33% YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPipelining: Previous Year Question part-IV | COA | GeeksforGeeks GATE | Harshit NigamWatch 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:007:30 / 31:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=PmA5Ic9vc9o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question aparimeet GATE-CS-2016 (Set 1) GATE-GATE-CS-2016 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24071, "s": 24043, "text": "\n30 Sep, 2021" }, { "code": null, "e": 24373, "s": 24071, "text": "The stage delays in a 4-stage pipeline are 800, 500, 400 and 300 picoseconds. The first stage (with delay 800 picoseconds) is replaced with a functionally equivalent design involving two stages with respective delays 600 and 350 picoseconds. The throughput increase of the pipeline is _______ percent." }, { "code": null, "e": 24500, "s": 24373, "text": "[This Question was originally a Fill-in-the-Blanks question](A) 33 or 34(B) 30 or 31(C) 38 or 39(D) 100Answer: (A)Explanation:" }, { "code": null, "e": 24699, "s": 24500, "text": "Throughput of 1st case T1: 1/max delay =1/800\nThroughput of 2nd case T2: 1/max delay= 1/600\n%age increase in throughput: (T2-T1)/T1\n = ( (1/600) - (1/800) ) / (1/800)\n = 33.33%" }, { "code": null, "e": 25612, "s": 24699, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPipelining: Previous Year Question part-IV | COA | GeeksforGeeks GATE | Harshit NigamWatch 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:007:30 / 31:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=PmA5Ic9vc9o\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 25622, "s": 25612, "text": "aparimeet" }, { "code": null, "e": 25643, "s": 25622, "text": "GATE-CS-2016 (Set 1)" }, { "code": null, "e": 25669, "s": 25643, "text": "GATE-GATE-CS-2016 (Set 1)" }, { "code": null, "e": 25674, "s": 25669, "text": "GATE" }, { "code": null, "e": 25772, "s": 25674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25781, "s": 25772, "text": "Comments" }, { "code": null, "e": 25794, "s": 25781, "text": "Old Comments" }, { "code": null, "e": 25836, "s": 25794, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25878, "s": 25836, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25912, "s": 25878, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25954, "s": 25912, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25988, "s": 25954, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 26030, "s": 25988, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26084, "s": 26030, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 26126, "s": 26084, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 26159, "s": 26126, "text": "GATE | GATE-CS-2004 | Question 3" } ]
How to list files from SD card with runtime permission in android?
This example demonstrates How to list files from SD card with runtime permission 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" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <Button android:id = "@+id/read" android:text = "read" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <ListView android:id = "@+id/list" android:layout_width = "match_parent" android:layout_height = "wrap_content"></ListView> </LinearLayout> In the above code, we have taken list view and button. When user click on button, it will take data from external storage and append the data to list view. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_REQUEST_CODE = 100; Button read; ArrayList<String> myList; ListView listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview = findViewById(R.id.list); read = findViewById(R.id.read); myList = new ArrayList<>(); read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { if (Build.VERSION.SDK_INT > = 23) { if (checkPermission()) { File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"); if (dir.exists()) { Log.d("path", dir.toString()); File list[] = dir.listFiles(); for (int i = 0; i < list.length; i++) { myList.add(list[i].getName()); } ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, myList); listview.setAdapter(arrayAdapter); } } else { requestPermission(); // Code for permission } } else { File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"); if (dir.exists()) { Log.d("path", dir.toString()); File list[] = dir.listFiles(); for (int i = 0; i < list.length; i++) { myList.add(list[i].getName()); } ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, myList); listview.setAdapter(arrayAdapter); } } } } }); } private boolean checkPermission() { int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE); if (result = = PackageManager.PERMISSION_GRANTED) { return true; } else { return false; } } private void requestPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) { Toast.makeText(MainActivity.this, "Write External Storage permission allows us to read files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_CODE: if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) { Log.e("value", "Permission Granted, Now you can use local drive ."); } else { Log.e("value", "Permission Denied, You cannot use local drive ."); } break; } } } Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run play.jpg icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, click on read button to show list of external storage directory files as shown below – Click here to download the project code
[ { "code": null, "e": 1155, "s": 1062, "text": "This example demonstrates How to list files from SD card with runtime permission in android." }, { "code": null, "e": 1284, "s": 1155, "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": 1349, "s": 1284, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1997, "s": 1349, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <Button\n android:id = \"@+id/read\"\n android:text = \"read\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <ListView\n android:id = \"@+id/list\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"></ListView>\n</LinearLayout>" }, { "code": null, "e": 2153, "s": 1997, "text": "In the above code, we have taken list view and button. When user click on button, it will take data from external storage and append the data to list view." }, { "code": null, "e": 2210, "s": 2153, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6309, "s": 2210, "text": "package com.example.andy.myapplication;\n\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\nimport java.io.File;\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE = 100;\n Button read;\n ArrayList<String> myList;\n ListView listview;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n listview = findViewById(R.id.list);\n read = findViewById(R.id.read);\n myList = new ArrayList<>();\n read.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String state = Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(state)) {\n if (Build.VERSION.SDK_INT > = 23) {\n if (checkPermission()) {\n File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + \"/\");\n if (dir.exists()) {\n Log.d(\"path\", dir.toString());\n File list[] = dir.listFiles();\n for (int i = 0; i < list.length; i++) {\n myList.add(list[i].getName());\n }\n ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, myList);\n listview.setAdapter(arrayAdapter);\n }\n } else {\n requestPermission(); // Code for permission\n }\n } else {\n File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + \"/\");\n if (dir.exists()) {\n Log.d(\"path\", dir.toString());\n File list[] = dir.listFiles();\n for (int i = 0; i < list.length; i++) {\n myList.add(list[i].getName());\n }\n ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, myList);\n listview.setAdapter(arrayAdapter);\n }\n }\n }\n }\n });\n }\n private boolean checkPermission() {\n int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE);\n if (result = = PackageManager.PERMISSION_GRANTED) {\n return true;\n } else {\n return false;\n }\n }\n private void requestPermission() {\n if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {\n Toast.makeText(MainActivity.this, \"Write External Storage permission allows us to read files.\n Please allow this permission in App Settings.\", Toast.LENGTH_LONG).show();\n } else {\n ActivityCompat.requestPermissions(MainActivity.this, new String[]\n {android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);\n }\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {\n switch (requestCode) {\n case PERMISSION_REQUEST_CODE:\n if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {\n Log.e(\"value\", \"Permission Granted, Now you can use local drive .\");\n } else {\n Log.e(\"value\", \"Permission Denied, You cannot use local drive .\");\n }\n break;\n }\n }\n}" }, { "code": null, "e": 6357, "s": 6309, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 7233, "s": 6357, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <uses-permission android:name = \"android.permission.READ_EXTERNAL_STORAGE\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 7588, "s": 7233, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run play.jpg 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": 7696, "s": 7588, "text": "In the above result, click on read button to show list of external storage directory files as shown below –" }, { "code": null, "e": 7736, "s": 7696, "text": "Click here to download the project code" } ]
NLP | IOB tags - GeeksforGeeks
16 Jul, 2021 What are Chunks ? Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can’t be a part of chuck and such words are known as chinks. What are IOB tags ? It is a format for chunks. These tags are similar to part-of-speech tags but can denote the inside, outside, and beginning of a chunk. Not just noun phrase but multiple different chunk phrase types are allowed here. Example : It is an excerpt from the conll2000 corpus. Each word is with a part-of-speech tag followed by an IOB tag on its own line: Mr. NNP B-NP Meador NNP I-NP had VBD B-VP been VBN I-VP executive JJ B-NP vice NN I-NP president NN I-NP of IN B-PP Balcor NNP B-NP What it means ? B-NP : beginning of a noun phrase I-NP : describes that the word is inside of the current noun phrase. O : end of the sentence. B-VP and I-VP : beginning and inside of a verb phrase.Code #1 : How it works – chunking words with IOB tags. Python3 # Loading the librariesfrom nltk.corpus.reader import ConllChunkCorpusReader # Initializingreader = ConllChunkCorpusReader( '.', r'.*\.iob', ('NP', 'VP', 'PP')) reader.chunked_words() reader.iob_words() Output : [Tree('NP', [('Mr.', 'NNP'), ('Meador', 'NNP')]), Tree('VP', [('had', 'VBD'), ('been', 'VBN')]), ...] [('Mr.', 'NNP', 'B-NP'), ('Meador', 'NNP', 'I-NP'), ...] Code #2 : How it works – chunking sentence with IOB tags. Python3 # Loading the librariesfrom nltk.corpus.reader import ConllChunkCorpusReader # Initializingreader = ConllChunkCorpusReader( '.', r'.*\.iob', ('NP', 'VP', 'PP')) reader.chunked_sents() reader.iob_sents() Output : [Tree('S', [Tree('NP', [('Mr.', 'NNP'), ('Meador', 'NNP')]), Tree('VP', [('had', 'VBD'), ('been', 'VBN')]), Tree('NP', [('executive', 'JJ'), ('vice', 'NN'), ('president', 'NN')]), Tree('PP', [('of', 'IN')]), Tree('NP', [('Balcor', 'NNP')]), ('.', '.')])] [[('Mr.', 'NNP', 'B-NP'), ('Meador', 'NNP', 'I-NP'), ('had', 'VBD', 'B-VP'), ('been', 'VBN', 'I-VP'), ('executive', 'JJ', 'B-NP'), ('vice', 'NN', 'I-NP'), ('president', 'NN', 'I-NP'), ('of', 'IN', 'B-PP'), ('Balcor', 'NNP', 'B-NP'), ('.', '.', 'O')]] Let’s understand the code above : For reading the corpus with IOB format, ConllChunkCorpusReader class is used. No separation of paragraphs and each sentence is separated by a blank line, therefore para_* methods are not available. Tuple or list specifying the types of chunks in the file like (‘NP’, ‘VP’, ‘PP’) sreves as the third argument to ConllChunkCorpusReader. iob_words() and iob_sents() methods returns lists of three tuples of (word, pos, iob) Code #3 : Tree Leaves – i.e. the tagged tokens Python3 # Loading the librariesfrom nltk.corpus.reader import ConllChunkCorpusReader # Initializingreader = ConllChunkCorpusReader( '.', r'.*\.iob', ('NP', 'VP', 'PP')) reader.chunked_words()[0].leaves() reader.chunked_sents()[0].leaves() reader.chunked_paras()[0][0].leaves() Output : [('Earlier', 'JJR'), ('staff-reduction', 'NN'), ('moves', 'NNS')] [('Earlier', 'JJR'), ('staff-reduction', 'NN'), ('moves', 'NNS'), ('have', 'VBP'), ('trimmed', 'VBN'), ('about', 'IN'), ('300', 'CD'), ('jobs', 'NNS'), (', ', ', '), ('the', 'DT'), ('spokesman', 'NN'), ('said', 'VBD'), ('.', '.')] [('Earlier', 'JJR'), ('staff-reduction', 'NN'), ('moves', 'NNS'), ('have', 'VBP'), ('trimmed', 'VBN'), ('about', 'IN'), ('300', 'CD'), ('jobs', 'NNS'), (', ', ', '), ('the', 'DT'), ('spokesman', 'NN'), ('said', 'VBD'), ('.', '.')] Akanksha_Rai simmytarika5 saurabh1990aror mrtarunbhatia Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Activation functions in Neural Networks Decision Tree Introduction with example Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25575, "s": 25547, "text": "\n16 Jul, 2021" }, { "code": null, "e": 25794, "s": 25575, "text": "What are Chunks ? Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can’t be a part of chuck and such words are known as chinks. " }, { "code": null, "e": 26164, "s": 25794, "text": "What are IOB tags ? It is a format for chunks. These tags are similar to part-of-speech tags but can denote the inside, outside, and beginning of a chunk. Not just noun phrase but multiple different chunk phrase types are allowed here. Example : It is an excerpt from the conll2000 corpus. Each word is with a part-of-speech tag followed by an IOB tag on its own line: " }, { "code": null, "e": 26296, "s": 26164, "text": "Mr. NNP B-NP\nMeador NNP I-NP\nhad VBD B-VP\nbeen VBN I-VP\nexecutive JJ B-NP\nvice NN I-NP\npresident NN I-NP\nof IN B-PP\nBalcor NNP B-NP" }, { "code": null, "e": 26551, "s": 26296, "text": "What it means ? B-NP : beginning of a noun phrase I-NP : describes that the word is inside of the current noun phrase. O : end of the sentence. B-VP and I-VP : beginning and inside of a verb phrase.Code #1 : How it works – chunking words with IOB tags. " }, { "code": null, "e": 26559, "s": 26551, "text": "Python3" }, { "code": "# Loading the librariesfrom nltk.corpus.reader import ConllChunkCorpusReader # Initializingreader = ConllChunkCorpusReader( '.', r'.*\\.iob', ('NP', 'VP', 'PP')) reader.chunked_words() reader.iob_words()", "e": 26769, "s": 26559, "text": null }, { "code": null, "e": 26780, "s": 26769, "text": "Output : " }, { "code": null, "e": 26941, "s": 26780, "text": "[Tree('NP', [('Mr.', 'NNP'), ('Meador', 'NNP')]), Tree('VP', [('had', 'VBD'), \n('been', 'VBN')]), ...]\n\n[('Mr.', 'NNP', 'B-NP'), ('Meador', 'NNP', 'I-NP'), ...]" }, { "code": null, "e": 27001, "s": 26941, "text": "Code #2 : How it works – chunking sentence with IOB tags. " }, { "code": null, "e": 27009, "s": 27001, "text": "Python3" }, { "code": "# Loading the librariesfrom nltk.corpus.reader import ConllChunkCorpusReader # Initializingreader = ConllChunkCorpusReader( '.', r'.*\\.iob', ('NP', 'VP', 'PP')) reader.chunked_sents() reader.iob_sents()", "e": 27219, "s": 27009, "text": null }, { "code": null, "e": 27230, "s": 27219, "text": "Output : " }, { "code": null, "e": 27741, "s": 27230, "text": "[Tree('S', [Tree('NP', [('Mr.', 'NNP'), ('Meador', 'NNP')]),\nTree('VP', [('had', 'VBD'), ('been', 'VBN')]), \nTree('NP', [('executive', 'JJ'), ('vice', 'NN'), ('president', 'NN')]),\nTree('PP', [('of', 'IN')]), Tree('NP', [('Balcor', 'NNP')]), ('.', '.')])]\n\n[[('Mr.', 'NNP', 'B-NP'), ('Meador', 'NNP', 'I-NP'), ('had', 'VBD', 'B-VP'), \n('been', 'VBN', 'I-VP'), ('executive', 'JJ', 'B-NP'), ('vice', 'NN', 'I-NP'), \n('president', 'NN', 'I-NP'), ('of', 'IN', 'B-PP'), ('Balcor', 'NNP', 'B-NP'), \n('.', '.', 'O')]]" }, { "code": null, "e": 27777, "s": 27741, "text": "Let’s understand the code above : " }, { "code": null, "e": 27855, "s": 27777, "text": "For reading the corpus with IOB format, ConllChunkCorpusReader class is used." }, { "code": null, "e": 27975, "s": 27855, "text": "No separation of paragraphs and each sentence is separated by a blank line, therefore para_* methods are not available." }, { "code": null, "e": 28112, "s": 27975, "text": "Tuple or list specifying the types of chunks in the file like (‘NP’, ‘VP’, ‘PP’) sreves as the third argument to ConllChunkCorpusReader." }, { "code": null, "e": 28198, "s": 28112, "text": "iob_words() and iob_sents() methods returns lists of three tuples of (word, pos, iob)" }, { "code": null, "e": 28247, "s": 28198, "text": "Code #3 : Tree Leaves – i.e. the tagged tokens " }, { "code": null, "e": 28255, "s": 28247, "text": "Python3" }, { "code": "# Loading the librariesfrom nltk.corpus.reader import ConllChunkCorpusReader # Initializingreader = ConllChunkCorpusReader( '.', r'.*\\.iob', ('NP', 'VP', 'PP')) reader.chunked_words()[0].leaves() reader.chunked_sents()[0].leaves() reader.chunked_paras()[0][0].leaves()", "e": 28531, "s": 28255, "text": null }, { "code": null, "e": 28542, "s": 28531, "text": "Output : " }, { "code": null, "e": 29072, "s": 28542, "text": "[('Earlier', 'JJR'), ('staff-reduction', 'NN'), ('moves', 'NNS')]\n\n[('Earlier', 'JJR'), ('staff-reduction', 'NN'), ('moves', 'NNS'),\n('have', 'VBP'), ('trimmed', 'VBN'), ('about', 'IN'), ('300', 'CD'),\n('jobs', 'NNS'), (', ', ', '), ('the', 'DT'), ('spokesman', 'NN'),\n('said', 'VBD'), ('.', '.')]\n\n[('Earlier', 'JJR'), ('staff-reduction', 'NN'), ('moves', 'NNS'),\n('have', 'VBP'), ('trimmed', 'VBN'), ('about', 'IN'), ('300', 'CD'),\n('jobs', 'NNS'), (', ', ', '), ('the', 'DT'), ('spokesman', 'NN'),\n('said', 'VBD'), ('.', '.')]" }, { "code": null, "e": 29087, "s": 29074, "text": "Akanksha_Rai" }, { "code": null, "e": 29100, "s": 29087, "text": "simmytarika5" }, { "code": null, "e": 29116, "s": 29100, "text": "saurabh1990aror" }, { "code": null, "e": 29130, "s": 29116, "text": "mrtarunbhatia" }, { "code": null, "e": 29158, "s": 29130, "text": "Natural-language-processing" }, { "code": null, "e": 29170, "s": 29158, "text": "Python-nltk" }, { "code": null, "e": 29187, "s": 29170, "text": "Machine Learning" }, { "code": null, "e": 29194, "s": 29187, "text": "Python" }, { "code": null, "e": 29211, "s": 29194, "text": "Machine Learning" }, { "code": null, "e": 29309, "s": 29211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29332, "s": 29309, "text": "ML | Linear Regression" }, { "code": null, "e": 29355, "s": 29332, "text": "Reinforcement learning" }, { "code": null, "e": 29369, "s": 29355, "text": "Decision Tree" }, { "code": null, "e": 29409, "s": 29369, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 29449, "s": 29409, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29477, "s": 29449, "text": "Read JSON file using Python" }, { "code": null, "e": 29527, "s": 29477, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29549, "s": 29527, "text": "Python map() function" } ]
Highlight Pandas DataFrame's specific columns using applymap() - GeeksforGeeks
17 Aug, 2020 Let us see how to highlight elements and specific columns of a Pandas DataFrame. We can do this using the applymap() function of the Styler class. Syntax : Styler.applymap(self, func, subset = None, **kwargs) Parameters : func : takes a scalar and returns a scalar. subset : valid indexer to limit data to before applying the function. **kwargs : dict pass along to func. Returns : Styler Let’s understand with examples: First of all create a simple data frame: # importing pandas as pd import pandas as pd # creating the dataframe df = pd.DataFrame({"A" : [14, 4, 5, 4, 1], "B" : [5, 2, 54, 3, 2], "C" : [20, 20, 7, 3, 8], "D" : [14, 3, 6, 2, 6]}) print("Original DataFrame :")display(df) Output : Example 1 : For every cell in the DataFrame, if the value is less than 6 then we will highlight the cell with red color, otherwise with blue color. # function definitiondef highlight_cols(s): color = 'red' if s < 6 else 'blue' return 'background-color: % s' % color # highlighting the cellsdisplay(df.style.applymap(highlight_cols)) Output : Example 2 : This time we will highlight only the cells in some specified columns. # function definitiondef highlight_cols(s): return 'background-color: % s' % 'yellow' # highlighting the cellsdisplay(df.style.applymap(highlight_cols, subset = pd.IndexSlice[:, ['B', 'C']])) Output : Highlight specific columns with the help of Indexing: Python3 df.style.applymap(highlight_cols, subset = pd.IndexSlice[:, ['B', 'C']]) Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Defaultdict in Python How to Install PIP on Windows ? Deque in Python Bar Plot in Matplotlib Check if element exists in list in Python Python math function | sqrt() Python | Output Formatting Python - Pandas dataframe.append() How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Aug, 2020" }, { "code": null, "e": 25684, "s": 25537, "text": "Let us see how to highlight elements and specific columns of a Pandas DataFrame. We can do this using the applymap() function of the Styler class." }, { "code": null, "e": 25746, "s": 25684, "text": "Syntax : Styler.applymap(self, func, subset = None, **kwargs)" }, { "code": null, "e": 25759, "s": 25746, "text": "Parameters :" }, { "code": null, "e": 25803, "s": 25759, "text": "func : takes a scalar and returns a scalar." }, { "code": null, "e": 25873, "s": 25803, "text": "subset : valid indexer to limit data to before applying the function." }, { "code": null, "e": 25909, "s": 25873, "text": "**kwargs : dict pass along to func." }, { "code": null, "e": 25926, "s": 25909, "text": "Returns : Styler" }, { "code": null, "e": 25958, "s": 25926, "text": "Let’s understand with examples:" }, { "code": null, "e": 25999, "s": 25958, "text": "First of all create a simple data frame:" }, { "code": "# importing pandas as pd import pandas as pd # creating the dataframe df = pd.DataFrame({\"A\" : [14, 4, 5, 4, 1], \"B\" : [5, 2, 54, 3, 2], \"C\" : [20, 20, 7, 3, 8], \"D\" : [14, 3, 6, 2, 6]}) print(\"Original DataFrame :\")display(df)", "e": 26287, "s": 25999, "text": null }, { "code": null, "e": 26296, "s": 26287, "text": "Output :" }, { "code": null, "e": 26444, "s": 26296, "text": "Example 1 : For every cell in the DataFrame, if the value is less than 6 then we will highlight the cell with red color, otherwise with blue color." }, { "code": "# function definitiondef highlight_cols(s): color = 'red' if s < 6 else 'blue' return 'background-color: % s' % color # highlighting the cellsdisplay(df.style.applymap(highlight_cols))", "e": 26636, "s": 26444, "text": null }, { "code": null, "e": 26645, "s": 26636, "text": "Output :" }, { "code": null, "e": 26727, "s": 26645, "text": "Example 2 : This time we will highlight only the cells in some specified columns." }, { "code": "# function definitiondef highlight_cols(s): return 'background-color: % s' % 'yellow' # highlighting the cellsdisplay(df.style.applymap(highlight_cols, subset = pd.IndexSlice[:, ['B', 'C']]))", "e": 26949, "s": 26727, "text": null }, { "code": null, "e": 26958, "s": 26949, "text": "Output :" }, { "code": null, "e": 27012, "s": 26958, "text": "Highlight specific columns with the help of Indexing:" }, { "code": null, "e": 27020, "s": 27012, "text": "Python3" }, { "code": "df.style.applymap(highlight_cols, subset = pd.IndexSlice[:, ['B', 'C']])", "e": 27093, "s": 27020, "text": null }, { "code": null, "e": 27117, "s": 27093, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27131, "s": 27117, "text": "Python-pandas" }, { "code": null, "e": 27138, "s": 27131, "text": "Python" }, { "code": null, "e": 27236, "s": 27138, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27258, "s": 27236, "text": "Defaultdict in Python" }, { "code": null, "e": 27290, "s": 27258, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27306, "s": 27290, "text": "Deque in Python" }, { "code": null, "e": 27329, "s": 27306, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27371, "s": 27329, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27401, "s": 27371, "text": "Python math function | sqrt()" }, { "code": null, "e": 27428, "s": 27401, "text": "Python | Output Formatting" }, { "code": null, "e": 27463, "s": 27428, "text": "Python - Pandas dataframe.append()" }, { "code": null, "e": 27519, "s": 27463, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Computer Organization and Architecture - GeeksforGeeks
19 Nov, 2018 MBR ← PC MAR ← X PC ← Y Memory ← MBR Pipeline will have to be stalled till Ei stage of l4 completes, as Ei stage will tell whether to take branch or not. After that l4(WO) and l9(Fi) can go in parallel and later the following instructions. So, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns From l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns Total = 77 + 88 = 165 ns RAM chip size = 1k ×8[1024 words of 8 bits each] RAM to construct =16k ×16 Number of chips required = (16k x 16)/ ( 1k x 8) = (16 x 2) [16 chips vertically with each having 2 chips horizontally] So to select one chip out of 16 vertical chips, we need 4 x 16 decoder. Available decoder is 2 x 4 decoder To be constructed is 4 x 16 decoder Hence 4 + 1 = 5 decoders are required. c = a + b; d = c * a; e = c + a; x = c * c; if (x > a) { y = a * a; } else { d = d * d; e = e * e; } r1......r2 a.......b......c = a + b a.......c......x = c * c a.......x......but we will have to store c in mem as we don't know if x > a ................. or not y.......x......y = a * a choosing the best case of x > a , min spills = 1 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? What is Transmission Control Protocol (TCP)? How to Calculate Number of Host in a Subnet? Python OpenCV - Canny() Function How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python How to Fix: KeyError in Pandas
[ { "code": null, "e": 28683, "s": 28655, "text": "\n19 Nov, 2018" }, { "code": null, "e": 28745, "s": 28683, "text": " MBR ← PC \n MAR ← X \n PC ← Y \n Memory ← MBR" }, { "code": null, "e": 29099, "s": 28745, "text": "Pipeline will have to be stalled till Ei stage of l4 completes, \nas Ei stage will tell whether to take branch or not. \n\nAfter that l4(WO) and l9(Fi) can go in parallel and later the\nfollowing instructions.\nSo, till l4(Ei) completes : 7 cycles * (10 + 1 ) ns = 77ns\nFrom l4(WO) or l9(Fi) to l12(WO) : 8 cycles * (10 + 1)ns = 88ns\nTotal = 77 + 88 = 165 ns" }, { "code": null, "e": 29505, "s": 29099, "text": "RAM chip size = 1k ×8[1024 words of 8 bits each]\nRAM to construct =16k ×16\nNumber of chips required = (16k x 16)/ ( 1k x 8)\n = (16 x 2)\n[16 chips vertically with each having 2 chips\nhorizontally]\nSo to select one chip out of 16 vertical chips, \nwe need 4 x 16 decoder.\n\nAvailable decoder is 2 x 4 decoder\nTo be constructed is 4 x 16 decoder\n\nHence 4 + 1 = 5 decoders are required." }, { "code": null, "e": 29645, "s": 29505, "text": " c = a + b;\n d = c * a;\n e = c + a;\n x = c * c;\n if (x > a) {\n y = a * a;\n }\n else {\n d = d * d;\n e = e * e;\n }" }, { "code": null, "e": 29882, "s": 29645, "text": "r1......r2\na.......b......c = a + b\na.......c......x = c * c\na.......x......but we will have to store c in mem as we don't know if x > a\n................. or not\ny.......x......y = a * a\nchoosing the best case of x > a , min spills = 1 " }, { "code": null, "e": 29980, "s": 29882, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 30012, "s": 29980, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 30065, "s": 30012, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 30120, "s": 30065, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 30165, "s": 30120, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 30210, "s": 30165, "text": "How to Calculate Number of Host in a Subnet?" }, { "code": null, "e": 30243, "s": 30210, "text": "Python OpenCV - Canny() Function" }, { "code": null, "e": 30301, "s": 30243, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 30363, "s": 30301, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 30443, "s": 30363, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" } ]
Smallest integer greater than n such that it consists of digit m exactly k times - GeeksforGeeks
24 Nov, 2021 Given three integer n, m and k, the task is to find the smallest integer > n such that digit m appears exactly k times in it.Examples: Input: n = 111, m = 2, k = 2 Output: 122Input: n = 111, m = 2, k = 3 Output: 222 Approach: Start iterating from n + 1 and for each integer i check whether it consists of digit m exactly k times. This way smallest integer > n with digit m occurring exactly k times can be found.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if n contains// digit m exactly k timesbool digitWell(int n, int m, int k){ int cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n /= 10; } return cnt == k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesint findInt(int n, int m, int k){ int i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver codeint main(){ int n = 111, m = 2, k = 2; cout << findInt(n, m, k); return 0;} // Java implementation of the approachclass GFG{ // Function that returns true if n contains// digit m exactly k timesstatic boolean digitWell(int n, int m, int k){ int cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n /= 10; } return cnt == k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesstatic int findInt(int n, int m, int k){ int i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver codepublic static void main(String[] args){ int n = 111, m = 2, k = 2; System.out.println(findInt(n, m, k));}} // This code is contributed by Code_Mech # Python3 implementation of the approach # Function that returns true if n# contains digit m exactly k timesdef digitWell(n, m, k): cnt = 0 while (n > 0): if (n % 10 == m): cnt = cnt + 1; n = (int)(n / 10); return cnt == k; # Function to return the smallest integer > n# with digit m occurring exactly k timesdef findInt(n, m, k): i = n + 1; while (True): if (digitWell(i, m, k)): return i; i = i + 1; # Driver coden = 111; m = 2; k = 2;print(findInt(n, m, k)); # This code is contributed# by Akanksha Rai // C# implementation of the approachusing System;class GFG{ // Function that returns true if n contains// digit m exactly k timesstatic bool digitWell(int n, int m, int k){ int cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n /= 10; } return cnt == k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesstatic int findInt(int n, int m, int k){ int i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver codepublic static void Main(){ int n = 111, m = 2, k = 2; Console.WriteLine(findInt(n, m, k));}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the approach // Function that returns true if n// contains digit m exactly k timesfunction digitWell($n, $m, $k){ $cnt = 0; while ($n > 0) { if ($n % 10 == $m) ++$cnt; $n = floor($n / 10); } return $cnt == $k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesfunction findInt($n, $m, $k){ $i = $n + 1; while (true) { if (digitWell($i, $m, $k)) return $i; $i++; }} // Driver code$n = 111;$m = 2;$k = 2; echo findInt($n, $m, $k); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function that returns true if n contains// digit m exactly k timesfunction digitWell(n, m, k){ var cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n = Math.floor(n/10); } if(cnt == k) return true; else return false;} // Function to return the smallest integer > n// with digit m occurring exactly k timesfunction findInt(n, m, k){ var i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver code var n = 111, m = 2, k = 2; document.write(findInt(n, m, k)); </script> 122 Time Complexity: O(n * log10n) Auxiliary Space: O(1) ankthon Code_Mech Akanksha_Rai bgangwar59 samim2000 number-digits Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25937, "s": 25909, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26074, "s": 25937, "text": "Given three integer n, m and k, the task is to find the smallest integer > n such that digit m appears exactly k times in it.Examples: " }, { "code": null, "e": 26157, "s": 26074, "text": "Input: n = 111, m = 2, k = 2 Output: 122Input: n = 111, m = 2, k = 3 Output: 222 " }, { "code": null, "e": 26408, "s": 26159, "text": "Approach: Start iterating from n + 1 and for each integer i check whether it consists of digit m exactly k times. This way smallest integer > n with digit m occurring exactly k times can be found.Below is the implementation of the above approach: " }, { "code": null, "e": 26412, "s": 26408, "text": "C++" }, { "code": null, "e": 26417, "s": 26412, "text": "Java" }, { "code": null, "e": 26425, "s": 26417, "text": "Python3" }, { "code": null, "e": 26428, "s": 26425, "text": "C#" }, { "code": null, "e": 26432, "s": 26428, "text": "PHP" }, { "code": null, "e": 26443, "s": 26432, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if n contains// digit m exactly k timesbool digitWell(int n, int m, int k){ int cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n /= 10; } return cnt == k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesint findInt(int n, int m, int k){ int i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver codeint main(){ int n = 111, m = 2, k = 2; cout << findInt(n, m, k); return 0;}", "e": 27078, "s": 26443, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function that returns true if n contains// digit m exactly k timesstatic boolean digitWell(int n, int m, int k){ int cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n /= 10; } return cnt == k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesstatic int findInt(int n, int m, int k){ int i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver codepublic static void main(String[] args){ int n = 111, m = 2, k = 2; System.out.println(findInt(n, m, k));}} // This code is contributed by Code_Mech", "e": 27776, "s": 27078, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if n# contains digit m exactly k timesdef digitWell(n, m, k): cnt = 0 while (n > 0): if (n % 10 == m): cnt = cnt + 1; n = (int)(n / 10); return cnt == k; # Function to return the smallest integer > n# with digit m occurring exactly k timesdef findInt(n, m, k): i = n + 1; while (True): if (digitWell(i, m, k)): return i; i = i + 1; # Driver coden = 111; m = 2; k = 2;print(findInt(n, m, k)); # This code is contributed# by Akanksha Rai", "e": 28352, "s": 27776, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{ // Function that returns true if n contains// digit m exactly k timesstatic bool digitWell(int n, int m, int k){ int cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n /= 10; } return cnt == k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesstatic int findInt(int n, int m, int k){ int i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver codepublic static void Main(){ int n = 111, m = 2, k = 2; Console.WriteLine(findInt(n, m, k));}} // This code is contributed// by Akanksha Rai", "e": 29049, "s": 28352, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that returns true if n// contains digit m exactly k timesfunction digitWell($n, $m, $k){ $cnt = 0; while ($n > 0) { if ($n % 10 == $m) ++$cnt; $n = floor($n / 10); } return $cnt == $k;} // Function to return the smallest integer > n// with digit m occurring exactly k timesfunction findInt($n, $m, $k){ $i = $n + 1; while (true) { if (digitWell($i, $m, $k)) return $i; $i++; }} // Driver code$n = 111;$m = 2;$k = 2; echo findInt($n, $m, $k); // This code is contributed by Ryuga?>", "e": 29663, "s": 29049, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that returns true if n contains// digit m exactly k timesfunction digitWell(n, m, k){ var cnt = 0; while (n > 0) { if (n % 10 == m) ++cnt; n = Math.floor(n/10); } if(cnt == k) return true; else return false;} // Function to return the smallest integer > n// with digit m occurring exactly k timesfunction findInt(n, m, k){ var i = n + 1; while (true) { if (digitWell(i, m, k)) return i; i++; }} // Driver code var n = 111, m = 2, k = 2; document.write(findInt(n, m, k)); </script>", "e": 30304, "s": 29663, "text": null }, { "code": null, "e": 30308, "s": 30304, "text": "122" }, { "code": null, "e": 30341, "s": 30310, "text": "Time Complexity: O(n * log10n)" }, { "code": null, "e": 30363, "s": 30341, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30371, "s": 30363, "text": "ankthon" }, { "code": null, "e": 30381, "s": 30371, "text": "Code_Mech" }, { "code": null, "e": 30394, "s": 30381, "text": "Akanksha_Rai" }, { "code": null, "e": 30405, "s": 30394, "text": "bgangwar59" }, { "code": null, "e": 30415, "s": 30405, "text": "samim2000" }, { "code": null, "e": 30429, "s": 30415, "text": "number-digits" }, { "code": null, "e": 30442, "s": 30429, "text": "Mathematical" }, { "code": null, "e": 30461, "s": 30442, "text": "School Programming" }, { "code": null, "e": 30474, "s": 30461, "text": "Mathematical" }, { "code": null, "e": 30572, "s": 30474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30616, "s": 30572, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30658, "s": 30616, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 30689, "s": 30658, "text": "Modular multiplicative inverse" }, { "code": null, "e": 30760, "s": 30689, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 30785, "s": 30760, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 30803, "s": 30785, "text": "Python Dictionary" }, { "code": null, "e": 30819, "s": 30803, "text": "Arrays in C/C++" }, { "code": null, "e": 30838, "s": 30819, "text": "Inheritance in C++" }, { "code": null, "e": 30863, "s": 30838, "text": "Reverse a string in Java" } ]
How to Design Phong Shading Graphics using p5.js ? - GeeksforGeeks
12 Aug, 2021 Phong shading is a specific type of shading technique in 3D computer graphics that is useful for smoothing out multi-surface shapes, approximating surface highlights, and creating more sophisticated computer-modeled images. Experts refer to the technique as “interpolation,” where Phong shading visualizes a smoother surface for a 3D model. The Phong model is also very useful to learn about more advanced rendering techniques. Phong shading has the following features: It is able to produce highlights that occur in the middle of a polygon. The lighting computation is performed at every pixel. Normal vectors are interpolated over the polygon. Phong Shading Algorithm: There are three distinct components involved in Phong Shading: Ambient: This component approximates light coming from a surface due to all the non-directional ambient light that is in the environment. Diffuse: This component approximates light, originally from light source, reflecting from a surface which is diffuse or non glossy. Specular: This component determines how much the object shines. The complete Phong shading model for a single light source is: [ra,ga,ba] + [rd,gd,bd]max0(n•L) + [rs,gs,bs]max0(R•L)p The model for multiple light sources is: [ra,ga,ba] + Σi( [Lr,Lg,Lb] ( [rd,gd,bd]max0(n•Li) + [rs,gs,bs]max0(R•Li)p ) ) Visual Illustration of Phong Shading: Here the light is white with position x=1, y =1, z=-1. The ambient and diffuse component colors are both purple, the specular color is white which is reflecting a small part of the light hitting the surface of the object in narrow highlights. The intensity of the diffuse component varies with the direction of the surface and due to different light positions. The ambient component is uniformly shaded. AMBIENT + DIFFUSE + SPECULAR = PHONG SHADING Javascript function setup() { createCanvas(640, 500, WEBGL);} function draw() { // Setting the vector values // or the direction of light let dx = 300; let dy = 200; let dz = -600; let v = createVector(dx, dy, dz); // Creating the ambient light ambientLight(0, 0,255); // Creating the directional light // by using the given vector directionalLight(255, 0, 0, v); shininess(255); specularColor(255); specularMaterial(255); // Creating the point lights at the // given points from the given directions pointLight(255, 255, 255, 0, -50, 0); pointLight(255, 255, 255, 200,200,30); rotateX(0.01*frameCount); rotateY(0.01*frameCount); rotateZ(0.03*frameCount); // Setting the background // to black background(0); noStroke(); fill(255, 0, 0); torus(100,25);} Output: JavaScript-p5.js JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux 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": 26627, "s": 26599, "text": "\n12 Aug, 2021" }, { "code": null, "e": 27055, "s": 26627, "text": "Phong shading is a specific type of shading technique in 3D computer graphics that is useful for smoothing out multi-surface shapes, approximating surface highlights, and creating more sophisticated computer-modeled images. Experts refer to the technique as “interpolation,” where Phong shading visualizes a smoother surface for a 3D model. The Phong model is also very useful to learn about more advanced rendering techniques." }, { "code": null, "e": 27097, "s": 27055, "text": "Phong shading has the following features:" }, { "code": null, "e": 27169, "s": 27097, "text": "It is able to produce highlights that occur in the middle of a polygon." }, { "code": null, "e": 27223, "s": 27169, "text": "The lighting computation is performed at every pixel." }, { "code": null, "e": 27273, "s": 27223, "text": "Normal vectors are interpolated over the polygon." }, { "code": null, "e": 27361, "s": 27273, "text": "Phong Shading Algorithm: There are three distinct components involved in Phong Shading:" }, { "code": null, "e": 27499, "s": 27361, "text": "Ambient: This component approximates light coming from a surface due to all the non-directional ambient light that is in the environment." }, { "code": null, "e": 27631, "s": 27499, "text": "Diffuse: This component approximates light, originally from light source, reflecting from a surface which is diffuse or non glossy." }, { "code": null, "e": 27695, "s": 27631, "text": "Specular: This component determines how much the object shines." }, { "code": null, "e": 27758, "s": 27695, "text": "The complete Phong shading model for a single light source is:" }, { "code": null, "e": 27814, "s": 27758, "text": "[ra,ga,ba] + [rd,gd,bd]max0(n•L) + [rs,gs,bs]max0(R•L)p" }, { "code": null, "e": 27857, "s": 27816, "text": "The model for multiple light sources is:" }, { "code": null, "e": 27941, "s": 27857, "text": "[ra,ga,ba] + Σi( [Lr,Lg,Lb] \n ( [rd,gd,bd]max0(n•Li) + [rs,gs,bs]max0(R•Li)p ) )" }, { "code": null, "e": 28383, "s": 27941, "text": "Visual Illustration of Phong Shading: Here the light is white with position x=1, y =1, z=-1. The ambient and diffuse component colors are both purple, the specular color is white which is reflecting a small part of the light hitting the surface of the object in narrow highlights. The intensity of the diffuse component varies with the direction of the surface and due to different light positions. The ambient component is uniformly shaded." }, { "code": null, "e": 28428, "s": 28383, "text": "AMBIENT + DIFFUSE + SPECULAR = PHONG SHADING" }, { "code": null, "e": 28439, "s": 28428, "text": "Javascript" }, { "code": "function setup() { createCanvas(640, 500, WEBGL);} function draw() { // Setting the vector values // or the direction of light let dx = 300; let dy = 200; let dz = -600; let v = createVector(dx, dy, dz); // Creating the ambient light ambientLight(0, 0,255); // Creating the directional light // by using the given vector directionalLight(255, 0, 0, v); shininess(255); specularColor(255); specularMaterial(255); // Creating the point lights at the // given points from the given directions pointLight(255, 255, 255, 0, -50, 0); pointLight(255, 255, 255, 200,200,30); rotateX(0.01*frameCount); rotateY(0.01*frameCount); rotateZ(0.03*frameCount); // Setting the background // to black background(0); noStroke(); fill(255, 0, 0); torus(100,25);}", "e": 29241, "s": 28439, "text": null }, { "code": null, "e": 29249, "s": 29241, "text": "Output:" }, { "code": null, "e": 29266, "s": 29249, "text": "JavaScript-p5.js" }, { "code": null, "e": 29287, "s": 29266, "text": "JavaScript-Questions" }, { "code": null, "e": 29298, "s": 29287, "text": "JavaScript" }, { "code": null, "e": 29315, "s": 29298, "text": "Web Technologies" }, { "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": 29453, "s": 29413, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29514, "s": 29453, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29555, "s": 29514, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29577, "s": 29555, "text": "JavaScript | Promises" }, { "code": null, "e": 29631, "s": 29577, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29671, "s": 29631, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29704, "s": 29671, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29747, "s": 29704, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29797, "s": 29747, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to read any request header in PHP - GeeksforGeeks
13 Nov, 2018 HTTP Header: HTTP headers are the code that transfers the data between web server and browser. The HTTP headers are mainly intended for the communication between the server and the client in both directions. HTTP Request Header: When type a URL in the address bar of browser and try to access it, the browser sends an HTTP request to the server. The HTTP request header contains information in a text-record form, which includes many useful informations such as the type, capabilities, and version of the browser that generates the request, the operating system used by the client, the page that was requested, the various types of outputs accepted by the browser, and so on. Receiving the request header, the web server will send an HTTP response header back to the client. Read any request header: It can be achieved by using getallheaders() function. Example 1: <?phpforeach (getallheaders() as $name => $value) { echo "$name: $value <br>";}?> Output: Host: 127.0.0.3:2025 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US, en;q=0.9 Example 2: It can be achieved by using apache_request_headers() function. <?php$header = apache_request_headers(); foreach ($header as $headers => $value) { echo "$headers: $value <br />\n";}?> Host: 127.0.0.6:2027 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US, en;q=0.9 Reference: http://php.net/manual/en/function.header.php Picked Technical Scripter 2018 PHP PHP Programs Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Comparing two dates in PHP How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP
[ { "code": null, "e": 26011, "s": 25983, "text": "\n13 Nov, 2018" }, { "code": null, "e": 26219, "s": 26011, "text": "HTTP Header: HTTP headers are the code that transfers the data between web server and browser. The HTTP headers are mainly intended for the communication between the server and the client in both directions." }, { "code": null, "e": 26786, "s": 26219, "text": "HTTP Request Header: When type a URL in the address bar of browser and try to access it, the browser sends an HTTP request to the server. The HTTP request header contains information in a text-record form, which includes many useful informations such as the type, capabilities, and version of the browser that generates the request, the operating system used by the client, the page that was requested, the various types of outputs accepted by the browser, and so on. Receiving the request header, the web server will send an HTTP response header back to the client." }, { "code": null, "e": 26865, "s": 26786, "text": "Read any request header: It can be achieved by using getallheaders() function." }, { "code": null, "e": 26876, "s": 26865, "text": "Example 1:" }, { "code": "<?phpforeach (getallheaders() as $name => $value) { echo \"$name: $value <br>\";}?>", "e": 26961, "s": 26876, "text": null }, { "code": null, "e": 26969, "s": 26961, "text": "Output:" }, { "code": null, "e": 27362, "s": 26969, "text": "Host: 127.0.0.3:2025 \nConnection: keep-alive \nCache-Control: max-age=0 \nUpgrade-Insecure-Requests: 1 \nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, \nlike Gecko) Chrome/70.0.3538.67 Safari/537.36 \nAccept: text/html, application/xhtml+xml, application/xml;q=0.9, \nimage/webp, image/apng, */*;q=0.8 \nAccept-Encoding: gzip, deflate, br \nAccept-Language: en-US, en;q=0.9 \n" }, { "code": null, "e": 27436, "s": 27362, "text": "Example 2: It can be achieved by using apache_request_headers() function." }, { "code": "<?php$header = apache_request_headers(); foreach ($header as $headers => $value) { echo \"$headers: $value <br />\\n\";}?>", "e": 27560, "s": 27436, "text": null }, { "code": null, "e": 27952, "s": 27560, "text": "Host: 127.0.0.6:2027 \nConnection: keep-alive \nCache-Control: max-age=0 \nUpgrade-Insecure-Requests: 1 \nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,\nlike Gecko) Chrome/70.0.3538.67 Safari/537.36 \nAccept: text/html, application/xhtml+xml, application/xml;q=0.9, \nimage/webp, image/apng, */*;q=0.8 \nAccept-Encoding: gzip, deflate, br \nAccept-Language: en-US, en;q=0.9 \n" }, { "code": null, "e": 28008, "s": 27952, "text": "Reference: http://php.net/manual/en/function.header.php" }, { "code": null, "e": 28015, "s": 28008, "text": "Picked" }, { "code": null, "e": 28039, "s": 28015, "text": "Technical Scripter 2018" }, { "code": null, "e": 28043, "s": 28039, "text": "PHP" }, { "code": null, "e": 28056, "s": 28043, "text": "PHP Programs" }, { "code": null, "e": 28075, "s": 28056, "text": "Technical Scripter" }, { "code": null, "e": 28079, "s": 28075, "text": "PHP" }, { "code": null, "e": 28177, "s": 28079, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28227, "s": 28177, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28267, "s": 28227, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28312, "s": 28267, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28339, "s": 28312, "text": "Comparing two dates in PHP" }, { "code": null, "e": 28375, "s": 28339, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 28425, "s": 28375, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28465, "s": 28425, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28492, "s": 28465, "text": "Comparing two dates in PHP" }, { "code": null, "e": 28534, "s": 28492, "text": "How to pass JavaScript variables to PHP ?" } ]
Is main method compulsory in Java? - GeeksforGeeks
17 Feb, 2021 The answer to this question depends on the version of java you are using. Prior to JDK 7, the main method was not mandatory in a java program. You could write your full code under static block and it ran normally. The static block is first executed as soon as the class is loaded before the main(); the method is invoked and therefore before the main() is called. main is usually declared as static method and hence Java doesn’t need an object to call the main method. When you will give the run command(i.e java Test in the below-mentioned program in notepad), so compiler presumes Test is that class in which main() is there and since compiler load, the main() method, static blocks are ready to get executed. So here, it will run static block first and then it will see no main() is there. Therefore it will give “exception”, as exception comes while execution. However, if we don’t want an exception, we can terminate the program bySystem.exit(0); However, from JDK7 main method is mandatory. The compiler will verify first, whether main() is present or not. If your program doesn’t contain the main method, then you will get an error “main method not found in the class”. It will give an error (byte code verification error because in it’s byte code, main is not there) not an exception because the program has not run yet. Note:- However, both the programs will get compile because for compilation we don’t need main() method. // This program will successfully run// prior to JDK 7public class Test { // static block static { System.out.println("Hello User"); }} Below is the screenshot of the output to help you to visualize the same thing, practically. I have run this program on Notepad so that you can able to understand why that exception has changed into error in the latest version. If run prior to JDK 7Output in JAVA 6 version. Output in JAVA 6 version. If run on JDK 7,8 and so on...Output in JAVA 7YouTubeGeeksforGeeks507K subscribersIs main method compulsory in Java? | GeeksforGeeksWatch laterShareCopy link2/9InfoShoppingTap 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 / 1:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KXkz1gu6dxQ" 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 Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Output in JAVA 7 YouTubeGeeksforGeeks507K subscribersIs main method compulsory in Java? | GeeksforGeeksWatch laterShareCopy link2/9InfoShoppingTap 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 / 1:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KXkz1gu6dxQ" 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 Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. AnshulVaidya java-basics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples Reverse a string in Java Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25031, "s": 25003, "text": "\n17 Feb, 2021" }, { "code": null, "e": 25174, "s": 25031, "text": "The answer to this question depends on the version of java you are using. Prior to JDK 7, the main method was not mandatory in a java program." }, { "code": null, "e": 25245, "s": 25174, "text": "You could write your full code under static block and it ran normally." }, { "code": null, "e": 25500, "s": 25245, "text": "The static block is first executed as soon as the class is loaded before the main(); the method is invoked and therefore before the main() is called. main is usually declared as static method and hence Java doesn’t need an object to call the main method." }, { "code": null, "e": 25983, "s": 25500, "text": "When you will give the run command(i.e java Test in the below-mentioned program in notepad), so compiler presumes Test is that class in which main() is there and since compiler load, the main() method, static blocks are ready to get executed. So here, it will run static block first and then it will see no main() is there. Therefore it will give “exception”, as exception comes while execution. However, if we don’t want an exception, we can terminate the program bySystem.exit(0);" }, { "code": null, "e": 26362, "s": 25985, "text": "However, from JDK7 main method is mandatory. The compiler will verify first, whether main() is present or not. If your program doesn’t contain the main method, then you will get an error “main method not found in the class”. It will give an error (byte code verification error because in it’s byte code, main is not there) not an exception because the program has not run yet." }, { "code": null, "e": 26466, "s": 26362, "text": "Note:- However, both the programs will get compile because for compilation we don’t need main() method." }, { "code": "// This program will successfully run// prior to JDK 7public class Test { // static block static { System.out.println(\"Hello User\"); }}", "e": 26621, "s": 26466, "text": null }, { "code": null, "e": 26848, "s": 26621, "text": "Below is the screenshot of the output to help you to visualize the same thing, practically. I have run this program on Notepad so that you can able to understand why that exception has changed into error in the latest version." }, { "code": null, "e": 26895, "s": 26848, "text": "If run prior to JDK 7Output in JAVA 6 version." }, { "code": null, "e": 26921, "s": 26895, "text": "Output in JAVA 6 version." }, { "code": null, "e": 28263, "s": 26921, "text": "If run on JDK 7,8 and so on...Output in JAVA 7YouTubeGeeksforGeeks507K subscribersIs main method compulsory in Java? | GeeksforGeeksWatch laterShareCopy link2/9InfoShoppingTap 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 / 1:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KXkz1gu6dxQ\" 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 Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28280, "s": 28263, "text": "Output in JAVA 7" }, { "code": null, "e": 29417, "s": 28280, "text": "YouTubeGeeksforGeeks507K subscribersIs main method compulsory in Java? | GeeksforGeeksWatch laterShareCopy link2/9InfoShoppingTap 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 / 1:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KXkz1gu6dxQ\" 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 Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29542, "s": 29417, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29555, "s": 29542, "text": "AnshulVaidya" }, { "code": null, "e": 29567, "s": 29555, "text": "java-basics" }, { "code": null, "e": 29572, "s": 29567, "text": "Java" }, { "code": null, "e": 29577, "s": 29572, "text": "Java" }, { "code": null, "e": 29675, "s": 29577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29690, "s": 29675, "text": "Arrays in Java" }, { "code": null, "e": 29734, "s": 29690, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29756, "s": 29734, "text": "For-each loop in Java" }, { "code": null, "e": 29807, "s": 29756, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29843, "s": 29807, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 29873, "s": 29843, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29898, "s": 29873, "text": "Reverse a string in Java" }, { "code": null, "e": 29913, "s": 29898, "text": "Stream In Java" }, { "code": null, "e": 29932, "s": 29913, "text": "Interfaces in Java" } ]
HTML | <input type="checkbox"> - GeeksforGeeks
28 May, 2019 the HTML <input type=”checkbox”> is used to define a checkbox field. The checkbox is shown as a square box that is ticked when it is activated. It allows the user to select one or more option among all the limited choices. Syntax: <input type="checkbox"> Example: <!DOCTYPE html><html> <head> <title> Input type = "checkbox" </title></head> <body style="text-align: center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2><input type="checkbox"></h2> <form> <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" checked> Checked by default <br> <input type="checkbox" name="check" value="2"> Not checked by default <br> </form> <br> </body> </html> Output: Supported Browsers: Google Chrome Firefox Edge Opera Apple Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26501, "s": 26473, "text": "\n28 May, 2019" }, { "code": null, "e": 26724, "s": 26501, "text": "the HTML <input type=”checkbox”> is used to define a checkbox field. The checkbox is shown as a square box that is ticked when it is activated. It allows the user to select one or more option among all the limited choices." }, { "code": null, "e": 26732, "s": 26724, "text": "Syntax:" }, { "code": null, "e": 26757, "s": 26732, "text": "<input type=\"checkbox\"> " }, { "code": null, "e": 26766, "s": 26757, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Input type = \"checkbox\" </title></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2><input type=\"checkbox\"></h2> <form> <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" checked> Checked by default <br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default <br> </form> <br> </body> </html>", "e": 27418, "s": 26766, "text": null }, { "code": null, "e": 27426, "s": 27418, "text": "Output:" }, { "code": null, "e": 27446, "s": 27426, "text": "Supported Browsers:" }, { "code": null, "e": 27460, "s": 27446, "text": "Google Chrome" }, { "code": null, "e": 27468, "s": 27460, "text": "Firefox" }, { "code": null, "e": 27473, "s": 27468, "text": "Edge" }, { "code": null, "e": 27479, "s": 27473, "text": "Opera" }, { "code": null, "e": 27492, "s": 27479, "text": "Apple Safari" }, { "code": null, "e": 27629, "s": 27492, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27645, "s": 27629, "text": "HTML-Attributes" }, { "code": null, "e": 27650, "s": 27645, "text": "HTML" }, { "code": null, "e": 27667, "s": 27650, "text": "Web Technologies" }, { "code": null, "e": 27672, "s": 27667, "text": "HTML" }, { "code": null, "e": 27770, "s": 27672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27818, "s": 27770, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27842, "s": 27818, "text": "REST API (Introduction)" }, { "code": null, "e": 27892, "s": 27842, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27942, "s": 27892, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27979, "s": 27942, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28019, "s": 27979, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28052, "s": 28019, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28097, "s": 28052, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28140, "s": 28097, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Move or Copy Files and Directories - GeeksforGeeks
29 Dec, 2020 Let’s say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. import shutil # Copy src to dst. (cp src dst)shutil.copy(src, dst) # Copy files, but preserve metadata (cp -p src dst)shutil.copy2(src, dst) # Copy directory tree (cp -R src dst)shutil.copytree(src, dst) # Move src to dst (mv src dst)shutil.move(src, dst) The arguments to these functions are all strings supplying file or directory names. The underlying semantics tries to emulate that of similar Unix commands, as shown in the comments. By default, symbolic links are followed by these commands. For example, if the source file is a symbolic link, then the destination file will be a copy of the file the link points to. To copy the symbolic link instead, supply the follow_symlinks keyword argument as shown in the code below: Code #2 : shutil.copy2(src, dst, follow_symlinks = False) # To preserve symbolic links in copied directoriesshutil.copytree(src, dst, symlinks = True) The copytree() optionally allows to ignore certain files and directories during the copy process. To do this, supply an ignore function that takes a directory name and filename listing as input, and returns a list of names to ignore as a result. The example is shown in the code below – Code #3 : def ignore_pyc_files(dirname, filenames): return [name in filenames if name.endswith('.pyc')] shutil.copytree(src, dst, ignore = ignore_pyc_files) Since ignoring filename patterns is common, a utility function ignore_patterns() has already been provided to do it as shown in the code given below. Code #4 : shutil.copytree(src, dst, ignore = shutil.ignore_patterns('*~', '*.pyc')) How it works? Using shutil to copy files and directories is mostly straightforward. However, one caution concerning file metadata is that functions such as copy2() only make the best effort in preserving this data. Basic information, such as access times, creation times, and permissions, will always be preserved, but the preservation of owners, ACLs, resource forks, and other extended file metadata may or may not work depending on the underlying operating system and the user’s own access permissions. The user probably wouldn’t want to use a function like shutil.copytree() to perform system backups. When working with filenames, make sure to use the functions in os.path for the greatest portability (especially if working with both Unix and Windows). Code #5 : Example filename = '/Users/gfg/programs/abc.py' import os.pathos.path.basename(filename) 'abc.py' os.path.dirname(filename) '/Users/gfg/programs' os.path.split(filename) ('/Users/gfg/programs', 'abc.py') os.path.join('/new/dir', os.path.basename(filename)) '/new/dir/spam.py' os.path.expanduser('~/gfg/programs/spam.py') '/Users/gfg/programs/abc.py' One tricky bit about copying directories with copytree() is the handling of errors. For example, in the process of copying, the function might encounter broken symbolic links, files that can’t be accessed due to permission problems, and so on. Python file-handling-programs Python os-module-programs python-file-handling python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 Convert integer to string in Python
[ { "code": null, "e": 25629, "s": 25601, "text": "\n29 Dec, 2020" }, { "code": null, "e": 25846, "s": 25629, "text": "Let’s say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories." }, { "code": "import shutil # Copy src to dst. (cp src dst)shutil.copy(src, dst) # Copy files, but preserve metadata (cp -p src dst)shutil.copy2(src, dst) # Copy directory tree (cp -R src dst)shutil.copytree(src, dst) # Move src to dst (mv src dst)shutil.move(src, dst)", "e": 26106, "s": 25846, "text": null }, { "code": null, "e": 26473, "s": 26106, "text": "The arguments to these functions are all strings supplying file or directory names. The underlying semantics tries to emulate that of similar Unix commands, as shown in the comments. By default, symbolic links are followed by these commands. For example, if the source file is a symbolic link, then the destination file will be a copy of the file the link points to." }, { "code": null, "e": 26580, "s": 26473, "text": "To copy the symbolic link instead, supply the follow_symlinks keyword argument as shown in the code below:" }, { "code": null, "e": 26590, "s": 26580, "text": "Code #2 :" }, { "code": "shutil.copy2(src, dst, follow_symlinks = False) # To preserve symbolic links in copied directoriesshutil.copytree(src, dst, symlinks = True)", "e": 26732, "s": 26590, "text": null }, { "code": null, "e": 27019, "s": 26732, "text": "The copytree() optionally allows to ignore certain files and directories during the copy process. To do this, supply an ignore function that takes a directory name and filename listing as input, and returns a list of names to ignore as a result. The example is shown in the code below –" }, { "code": null, "e": 27029, "s": 27019, "text": "Code #3 :" }, { "code": "def ignore_pyc_files(dirname, filenames): return [name in filenames if name.endswith('.pyc')] shutil.copytree(src, dst, ignore = ignore_pyc_files)", "e": 27180, "s": 27029, "text": null }, { "code": null, "e": 27330, "s": 27180, "text": "Since ignoring filename patterns is common, a utility function ignore_patterns() has already been provided to do it as shown in the code given below." }, { "code": null, "e": 27340, "s": 27330, "text": "Code #4 :" }, { "code": "shutil.copytree(src, dst, ignore = shutil.ignore_patterns('*~', '*.pyc'))", "e": 27414, "s": 27340, "text": null }, { "code": null, "e": 27428, "s": 27414, "text": "How it works?" }, { "code": null, "e": 27498, "s": 27428, "text": "Using shutil to copy files and directories is mostly straightforward." }, { "code": null, "e": 27629, "s": 27498, "text": "However, one caution concerning file metadata is that functions such as copy2() only make the best effort in preserving this data." }, { "code": null, "e": 27920, "s": 27629, "text": "Basic information, such as access times, creation times, and permissions, will always be preserved, but the preservation of owners, ACLs, resource forks, and other extended file metadata may or may not work depending on the underlying operating system and the user’s own access permissions." }, { "code": null, "e": 28020, "s": 27920, "text": "The user probably wouldn’t want to use a function like shutil.copytree() to perform system backups." }, { "code": null, "e": 28172, "s": 28020, "text": "When working with filenames, make sure to use the functions in os.path for the greatest portability (especially if working with both Unix and Windows)." }, { "code": null, "e": 28190, "s": 28172, "text": "Code #5 : Example" }, { "code": "filename = '/Users/gfg/programs/abc.py' import os.pathos.path.basename(filename)", "e": 28272, "s": 28190, "text": null }, { "code": null, "e": 28281, "s": 28272, "text": "'abc.py'" }, { "code": "os.path.dirname(filename)", "e": 28309, "s": 28283, "text": null }, { "code": null, "e": 28331, "s": 28309, "text": "'/Users/gfg/programs'" }, { "code": "os.path.split(filename)", "e": 28357, "s": 28333, "text": null }, { "code": null, "e": 28391, "s": 28357, "text": "('/Users/gfg/programs', 'abc.py')" }, { "code": "os.path.join('/new/dir', os.path.basename(filename))", "e": 28446, "s": 28393, "text": null }, { "code": null, "e": 28465, "s": 28446, "text": "'/new/dir/spam.py'" }, { "code": "os.path.expanduser('~/gfg/programs/spam.py')", "e": 28512, "s": 28467, "text": null }, { "code": null, "e": 28541, "s": 28512, "text": "'/Users/gfg/programs/abc.py'" }, { "code": null, "e": 28785, "s": 28541, "text": "One tricky bit about copying directories with copytree() is the handling of errors. For example, in the process of copying, the function might encounter broken symbolic links, files that can’t be accessed due to permission problems, and so on." }, { "code": null, "e": 28815, "s": 28785, "text": "Python file-handling-programs" }, { "code": null, "e": 28841, "s": 28815, "text": "Python os-module-programs" }, { "code": null, "e": 28862, "s": 28841, "text": "python-file-handling" }, { "code": null, "e": 28879, "s": 28862, "text": "python-os-module" }, { "code": null, "e": 28886, "s": 28879, "text": "Python" }, { "code": null, "e": 28984, "s": 28886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29002, "s": 28984, "text": "Python Dictionary" }, { "code": null, "e": 29034, "s": 29002, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29056, "s": 29034, "text": "Enumerate() in Python" }, { "code": null, "e": 29098, "s": 29056, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29128, "s": 29098, "text": "Iterate over a list in Python" }, { "code": null, "e": 29154, "s": 29128, "text": "Python String | replace()" }, { "code": null, "e": 29183, "s": 29154, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29227, "s": 29183, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29264, "s": 29227, "text": "Create a Pandas DataFrame from Lists" } ]
How to Install Seaborn on Windows? - GeeksforGeeks
09 Sep, 2021 In this article, we will look into the process of installing Python Seaborn on Windows. Python PIP or conda (Depending upon user preference) PIP users can open up the command prompt and run the below command to install Python Seaborn Package on Windows: pip install Seaborn The following message will be shown once the installation is completed: To verify the installation use the below code in your python ide: Python3 import seaborn as snssns.__version__ Output: Conda users can open up the Anaconda Power Shell Prompt and use the below command to install Python Seaborn package on Windows: conda install -c anaconda seaborn The following message will be shown once the installation is completed: To verify the installation use the below code in your python ide: Python3 import seaborn as snssns.__version__ Output: Blogathon-2021 how-to-install Picked Python-Seaborn Blogathon How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to Install Tkinter in Windows? Python program to convert XML to Dictionary How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 26097, "s": 26069, "text": "\n09 Sep, 2021" }, { "code": null, "e": 26185, "s": 26097, "text": "In this article, we will look into the process of installing Python Seaborn on Windows." }, { "code": null, "e": 26192, "s": 26185, "text": "Python" }, { "code": null, "e": 26238, "s": 26192, "text": "PIP or conda (Depending upon user preference)" }, { "code": null, "e": 26351, "s": 26238, "text": "PIP users can open up the command prompt and run the below command to install Python Seaborn Package on Windows:" }, { "code": null, "e": 26371, "s": 26351, "text": "pip install Seaborn" }, { "code": null, "e": 26443, "s": 26371, "text": "The following message will be shown once the installation is completed:" }, { "code": null, "e": 26509, "s": 26443, "text": "To verify the installation use the below code in your python ide:" }, { "code": null, "e": 26517, "s": 26509, "text": "Python3" }, { "code": "import seaborn as snssns.__version__", "e": 26554, "s": 26517, "text": null }, { "code": null, "e": 26562, "s": 26554, "text": "Output:" }, { "code": null, "e": 26690, "s": 26562, "text": "Conda users can open up the Anaconda Power Shell Prompt and use the below command to install Python Seaborn package on Windows:" }, { "code": null, "e": 26724, "s": 26690, "text": "conda install -c anaconda seaborn" }, { "code": null, "e": 26796, "s": 26724, "text": "The following message will be shown once the installation is completed:" }, { "code": null, "e": 26862, "s": 26796, "text": "To verify the installation use the below code in your python ide:" }, { "code": null, "e": 26870, "s": 26862, "text": "Python3" }, { "code": "import seaborn as snssns.__version__", "e": 26907, "s": 26870, "text": null }, { "code": null, "e": 26915, "s": 26907, "text": "Output:" }, { "code": null, "e": 26930, "s": 26915, "text": "Blogathon-2021" }, { "code": null, "e": 26945, "s": 26930, "text": "how-to-install" }, { "code": null, "e": 26952, "s": 26945, "text": "Picked" }, { "code": null, "e": 26967, "s": 26952, "text": "Python-Seaborn" }, { "code": null, "e": 26977, "s": 26967, "text": "Blogathon" }, { "code": null, "e": 26984, "s": 26977, "text": "How To" }, { "code": null, "e": 27003, "s": 26984, "text": "Installation Guide" }, { "code": null, "e": 27010, "s": 27003, "text": "Python" }, { "code": null, "e": 27108, "s": 27010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27165, "s": 27108, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27206, "s": 27165, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 27236, "s": 27206, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 27271, "s": 27236, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 27315, "s": 27271, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 27347, "s": 27315, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27400, "s": 27347, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 27444, "s": 27400, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 27471, "s": 27444, "text": "How to Align Text in HTML?" } ]
Dice Rolling Simulator using Python-random - GeeksforGeeks
13 May, 2022 In this article, we will create a classic rolling dice simulator with the help of basic Python knowledge. Here we will be using the random module since we randomize the dice simulator for random outputs. 1) random.randint(): This function generates a random number in the given range. Below is the implementation. Example 1: Dice Simulator Python3 import random x = "y" while x == "y": # Generates a random number # between 1 and 6 (including # both 1 and 6) no = random.randint(1,6) if no == 1: print("[-----]") print("[ ]") print("[ 0 ]") print("[ ]") print("[-----]") if no == 2: print("[-----]") print("[ 0 ]") print("[ ]") print("[ 0 ]") print("[-----]") if no == 3: print("[-----]") print("[ ]") print("[0 0 0]") print("[ ]") print("[-----]") if no == 4: print("[-----]") print("[0 0]") print("[ ]") print("[0 0]") print("[-----]") if no == 5: print("[-----]") print("[0 0]") print("[ 0 ]") print("[0 0]") print("[-----]") if no == 6: print("[-----]") print("[0 0 0]") print("[ ]") print("[0 0 0]") print("[-----]") x=input("press y to roll again and n to exit:") print("\n") Output: Example 2: Dice simulator Python import randomwhile True: print('''1.roll the dice 2.To exit ''') user = int(input("what you want to do\n")) if user==1: number = random.randint(1,6) print(number) else: break Output: varshagumber28 ayushcoding100 Python-random Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 25973, "s": 25945, "text": "\n13 May, 2022" }, { "code": null, "e": 26177, "s": 25973, "text": "In this article, we will create a classic rolling dice simulator with the help of basic Python knowledge. Here we will be using the random module since we randomize the dice simulator for random outputs." }, { "code": null, "e": 26287, "s": 26177, "text": "1) random.randint(): This function generates a random number in the given range. Below is the implementation." }, { "code": null, "e": 26313, "s": 26287, "text": "Example 1: Dice Simulator" }, { "code": null, "e": 26321, "s": 26313, "text": "Python3" }, { "code": "import random x = \"y\" while x == \"y\": # Generates a random number # between 1 and 6 (including # both 1 and 6) no = random.randint(1,6) if no == 1: print(\"[-----]\") print(\"[ ]\") print(\"[ 0 ]\") print(\"[ ]\") print(\"[-----]\") if no == 2: print(\"[-----]\") print(\"[ 0 ]\") print(\"[ ]\") print(\"[ 0 ]\") print(\"[-----]\") if no == 3: print(\"[-----]\") print(\"[ ]\") print(\"[0 0 0]\") print(\"[ ]\") print(\"[-----]\") if no == 4: print(\"[-----]\") print(\"[0 0]\") print(\"[ ]\") print(\"[0 0]\") print(\"[-----]\") if no == 5: print(\"[-----]\") print(\"[0 0]\") print(\"[ 0 ]\") print(\"[0 0]\") print(\"[-----]\") if no == 6: print(\"[-----]\") print(\"[0 0 0]\") print(\"[ ]\") print(\"[0 0 0]\") print(\"[-----]\") x=input(\"press y to roll again and n to exit:\") print(\"\\n\")", "e": 27366, "s": 26321, "text": null }, { "code": null, "e": 27375, "s": 27366, "text": "Output: " }, { "code": null, "e": 27401, "s": 27375, "text": "Example 2: Dice simulator" }, { "code": null, "e": 27408, "s": 27401, "text": "Python" }, { "code": "import randomwhile True: print('''1.roll the dice 2.To exit ''') user = int(input(\"what you want to do\\n\")) if user==1: number = random.randint(1,6) print(number) else: break", "e": 27599, "s": 27408, "text": null }, { "code": null, "e": 27607, "s": 27599, "text": "Output:" }, { "code": null, "e": 27626, "s": 27611, "text": "varshagumber28" }, { "code": null, "e": 27641, "s": 27626, "text": "ayushcoding100" }, { "code": null, "e": 27655, "s": 27641, "text": "Python-random" }, { "code": null, "e": 27662, "s": 27655, "text": "Python" }, { "code": null, "e": 27760, "s": 27662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27778, "s": 27760, "text": "Python Dictionary" }, { "code": null, "e": 27810, "s": 27778, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27832, "s": 27810, "text": "Enumerate() in Python" }, { "code": null, "e": 27874, "s": 27832, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27900, "s": 27874, "text": "Python String | replace()" }, { "code": null, "e": 27929, "s": 27900, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27966, "s": 27929, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28002, "s": 27966, "text": "Convert integer to string in Python" }, { "code": null, "e": 28044, "s": 28002, "text": "Check if element exists in list in Python" } ]
Remove all the prime numbers from the given array - GeeksforGeeks
28 Jan, 2022 Given an array arr[] of N integers, the task is to remove all the prime numbers. Examples: Input: arr[] = {4, 6, 5, 3, 8, 7, 10, 11, 14, 15} Output: 4 6 8 10 14 15 Input: arr[] = {2, 4, 7, 8, 9, 11} Output: 4 8 9 Approach: Traverse the array and check if the current number is prime, if it is then left shift all the elements after it to remove this prime number and decrease the value of the array length. Repeat this for all the elements of the array. To check the number is prime or not, use Sieve of Eratosthenes to generate all the primes. 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; const int sz = 1e5;bool isPrime[sz + 1]; // Function for Sieve of Eratosthenesvoid sieve(){ memset(isPrime, true, sizeof(isPrime)); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements of the arrayvoid printArray(int arr[], int len){ for (int i = 0; i < len; i++) { cout << arr[i] << ' '; }} // Function to remove all the prime numbersvoid removePrimes(int arr[], int len){ // Generate primes sieve(); // Traverse the array for (int i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for (int j = i; j < len; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codeint main(){ int arr[] = { 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 }; int len = sizeof(arr) / sizeof(int); removePrimes(arr, len); return 0;} // Java implementation of the approachclass GFG{static int sz = (int) 1e5;static boolean []isPrime = new boolean[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for (int i = 0; i < sz + 1; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements of the arraystatic void printArray(int arr[], int len){ for (int i = 0; i < len; i++) { System.out.print(arr[i] + " "); }} // Function to remove all the prime numbersstatic void removePrimes(int arr[], int len){ // Generate primes sieve(); // Traverse the array for (int i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for (int j = i; j < len-1; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codepublic static void main(String[] args){ int arr[] = { 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 }; int len = arr.length; removePrimes(arr, len);}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approachsz = 10**5isPrime = [True for i in range(sz + 1)] # Function for Sieve of Eratosthenesdef sieve(): isPrime[0] = isPrime[1] = False i = 2 while i * i < sz: if (isPrime[i]): for j in range(i * i, sz, i): isPrime[j] = False i += 1 # Function to print the elements of the arraydef prArray(arr, lenn): for i in range(lenn): print(arr[i], end = " ") # Function to remove all the prime numbersdef removePrimes(arr, lenn): # Generate primes sieve() # Traverse the array i = 0 while i < lenn: # If the current element is prime if (isPrime[arr[i]]): # Shift all the elements on the # right of it to the left for j in range(i, lenn - 1): arr[j] = arr[j + 1] # Decrease the loop counter by 1 # to check the shifted element i -= 1 # Decrease the length lenn -= 1 i += 1 # Print the updated array prArray(arr, lenn) # Driver codeif __name__ == '__main__': arr = [4, 6, 5, 3, 8, 7, 10, 11, 14, 15] lenn = len(arr) removePrimes(arr, lenn) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{static int sz = (int) 1e5;static bool []isPrime = new bool[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for (int i = 0; i < sz + 1; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements// of the arraystatic void printArray(int []arr, int len){ for (int i = 0; i < len; i++) { Console.Write(arr[i] + " "); }} // Function to remove// all the prime numbersstatic void removePrimes(int []arr, int len){ // Generate primes sieve(); // Traverse the array for (int i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for (int j = i; j < len - 1; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codepublic static void Main(String[] args){ int []arr = { 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 }; int len = arr.Length; removePrimes(arr, len);}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approachconst sz = 1e5;let isPrime = new Array(sz + 1); // Function for Sieve of Eratosthenesfunction sieve(){ isPrime.fill(true) isPrime[0] = isPrime[1] = false; for(let i = 2; i * i <= sz; i++) { if (isPrime[i]) { for(let j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements of the arrayfunction printArray(arr, len){ for(let i = 0; i < len; i++) { document.write(arr[i] + ' '); }} // Function to remove all the prime numbersfunction removePrimes(arr, len){ // Generate primes sieve(); // Traverse the array for(let i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for(let j = i; j < len; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codelet arr = [ 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 ];let len = arr.length; removePrimes(arr, len); // This code is contributed by _saurabh_jaiswal </script> 4 6 8 10 14 15 mohit kumar 29 princiraj1992 surinderdawra388 _saurabh_jaiswal Prime Number sieve Arrays Mathematical Arrays Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26041, "s": 26013, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26122, "s": 26041, "text": "Given an array arr[] of N integers, the task is to remove all the prime numbers." }, { "code": null, "e": 26133, "s": 26122, "text": "Examples: " }, { "code": null, "e": 26206, "s": 26133, "text": "Input: arr[] = {4, 6, 5, 3, 8, 7, 10, 11, 14, 15} Output: 4 6 8 10 14 15" }, { "code": null, "e": 26257, "s": 26206, "text": "Input: arr[] = {2, 4, 7, 8, 9, 11} Output: 4 8 9 " }, { "code": null, "e": 26589, "s": 26257, "text": "Approach: Traverse the array and check if the current number is prime, if it is then left shift all the elements after it to remove this prime number and decrease the value of the array length. Repeat this for all the elements of the array. To check the number is prime or not, use Sieve of Eratosthenes to generate all the primes." }, { "code": null, "e": 26642, "s": 26589, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26646, "s": 26642, "text": "C++" }, { "code": null, "e": 26651, "s": 26646, "text": "Java" }, { "code": null, "e": 26659, "s": 26651, "text": "Python3" }, { "code": null, "e": 26662, "s": 26659, "text": "C#" }, { "code": null, "e": 26673, "s": 26662, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int sz = 1e5;bool isPrime[sz + 1]; // Function for Sieve of Eratosthenesvoid sieve(){ memset(isPrime, true, sizeof(isPrime)); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements of the arrayvoid printArray(int arr[], int len){ for (int i = 0; i < len; i++) { cout << arr[i] << ' '; }} // Function to remove all the prime numbersvoid removePrimes(int arr[], int len){ // Generate primes sieve(); // Traverse the array for (int i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for (int j = i; j < len; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codeint main(){ int arr[] = { 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 }; int len = sizeof(arr) / sizeof(int); removePrimes(arr, len); return 0;}", "e": 28091, "s": 26673, "text": null }, { "code": "// Java implementation of the approachclass GFG{static int sz = (int) 1e5;static boolean []isPrime = new boolean[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for (int i = 0; i < sz + 1; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements of the arraystatic void printArray(int arr[], int len){ for (int i = 0; i < len; i++) { System.out.print(arr[i] + \" \"); }} // Function to remove all the prime numbersstatic void removePrimes(int arr[], int len){ // Generate primes sieve(); // Traverse the array for (int i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for (int j = i; j < len-1; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codepublic static void main(String[] args){ int arr[] = { 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 }; int len = arr.length; removePrimes(arr, len);}} // This code is contributed by PrinciRaj1992", "e": 29654, "s": 28091, "text": null }, { "code": "# Python3 implementation of the approachsz = 10**5isPrime = [True for i in range(sz + 1)] # Function for Sieve of Eratosthenesdef sieve(): isPrime[0] = isPrime[1] = False i = 2 while i * i < sz: if (isPrime[i]): for j in range(i * i, sz, i): isPrime[j] = False i += 1 # Function to print the elements of the arraydef prArray(arr, lenn): for i in range(lenn): print(arr[i], end = \" \") # Function to remove all the prime numbersdef removePrimes(arr, lenn): # Generate primes sieve() # Traverse the array i = 0 while i < lenn: # If the current element is prime if (isPrime[arr[i]]): # Shift all the elements on the # right of it to the left for j in range(i, lenn - 1): arr[j] = arr[j + 1] # Decrease the loop counter by 1 # to check the shifted element i -= 1 # Decrease the length lenn -= 1 i += 1 # Print the updated array prArray(arr, lenn) # Driver codeif __name__ == '__main__': arr = [4, 6, 5, 3, 8, 7, 10, 11, 14, 15] lenn = len(arr) removePrimes(arr, lenn) # This code is contributed by Mohit Kumar", "e": 30891, "s": 29654, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int sz = (int) 1e5;static bool []isPrime = new bool[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for (int i = 0; i < sz + 1; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements// of the arraystatic void printArray(int []arr, int len){ for (int i = 0; i < len; i++) { Console.Write(arr[i] + \" \"); }} // Function to remove// all the prime numbersstatic void removePrimes(int []arr, int len){ // Generate primes sieve(); // Traverse the array for (int i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for (int j = i; j < len - 1; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codepublic static void Main(String[] args){ int []arr = { 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 }; int len = arr.Length; removePrimes(arr, len);}} // This code is contributed by PrinciRaj1992", "e": 32527, "s": 30891, "text": null }, { "code": "<script> // Javascript implementation of the approachconst sz = 1e5;let isPrime = new Array(sz + 1); // Function for Sieve of Eratosthenesfunction sieve(){ isPrime.fill(true) isPrime[0] = isPrime[1] = false; for(let i = 2; i * i <= sz; i++) { if (isPrime[i]) { for(let j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print the elements of the arrayfunction printArray(arr, len){ for(let i = 0; i < len; i++) { document.write(arr[i] + ' '); }} // Function to remove all the prime numbersfunction removePrimes(arr, len){ // Generate primes sieve(); // Traverse the array for(let i = 0; i < len; i++) { // If the current element is prime if (isPrime[arr[i]]) { // Shift all the elements on the // right of it to the left for(let j = i; j < len; j++) { arr[j] = arr[j + 1]; } // Decrease the loop counter by 1 // to check the shifted element i--; // Decrease the length len--; } } // Print the updated array printArray(arr, len);} // Driver codelet arr = [ 4, 6, 5, 3, 8, 7, 10, 11, 14, 15 ];let len = arr.length; removePrimes(arr, len); // This code is contributed by _saurabh_jaiswal </script>", "e": 33950, "s": 32527, "text": null }, { "code": null, "e": 33965, "s": 33950, "text": "4 6 8 10 14 15" }, { "code": null, "e": 33982, "s": 33967, "text": "mohit kumar 29" }, { "code": null, "e": 33996, "s": 33982, "text": "princiraj1992" }, { "code": null, "e": 34013, "s": 33996, "text": "surinderdawra388" }, { "code": null, "e": 34030, "s": 34013, "text": "_saurabh_jaiswal" }, { "code": null, "e": 34043, "s": 34030, "text": "Prime Number" }, { "code": null, "e": 34049, "s": 34043, "text": "sieve" }, { "code": null, "e": 34056, "s": 34049, "text": "Arrays" }, { "code": null, "e": 34069, "s": 34056, "text": "Mathematical" }, { "code": null, "e": 34076, "s": 34069, "text": "Arrays" }, { "code": null, "e": 34089, "s": 34076, "text": "Mathematical" }, { "code": null, "e": 34102, "s": 34089, "text": "Prime Number" }, { "code": null, "e": 34108, "s": 34102, "text": "sieve" }, { "code": null, "e": 34206, "s": 34108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34233, "s": 34206, "text": "Count pairs with given sum" }, { "code": null, "e": 34264, "s": 34233, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34289, "s": 34264, "text": "Window Sliding Technique" }, { "code": null, "e": 34327, "s": 34289, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34348, "s": 34327, "text": "Next Greater Element" }, { "code": null, "e": 34378, "s": 34348, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34438, "s": 34378, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34453, "s": 34438, "text": "C++ Data Types" }, { "code": null, "e": 34496, "s": 34453, "text": "Set in C++ Standard Template Library (STL)" } ]
HTML | data-* Attributes - GeeksforGeeks
03 May, 2021 Custom Data Attributes allow you to add your own information to tags in HTML. Even though the name suggests otherwise, these are not specific to HTML5 and you can use the data-* attribute on all HTML elements. The data-* attributes can be used to define our own custom data attributes. It is used to store custom data in private to the page or application. There are mainly 2 parts of the Data Attributes: Attribute Name: Must be at least one character long, contain no capital letters and be prefixed with ‘data-‘.Attribute Value: Can be any string. Attribute Name: Must be at least one character long, contain no capital letters and be prefixed with ‘data-‘. Attribute Value: Can be any string. Syntax: <li data-book-author="Rabindra Nath Tagore"> Gitanjali </li> Example: HTML <!DOCTYPE html><html><head> <script> function showDetails(book) { var bookauthor = book.getAttribute("data-book-author"); alert(book.innerHTML + " is written by " + bookauthor + "."); } </script></head> <body> <h1>Books</h1> <p>Click on the book name to know author's name :</p> <ul> <li onclick="showDetails(this)" id="gitanjali" data-book-author="Rabindra Nath Tagore"> Gitanjali </li> <li onclick="showDetails(this)" id="conquest_of_self" data-book-author="Mahatma Gandhi"> Conquest of Self </li> <li onclick="showDetails(this)" id="broken_wings" data-book-author="Sarojini Naidu"> Broken Wings </li> </ul></body></html> Output: When we click on the book, we can see the name of the author in a separate dialogue box. Supported Browsers: The browser supported by HTML | data-* Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-Attributes Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 24946, "s": 24918, "text": "\n03 May, 2021" }, { "code": null, "e": 25354, "s": 24946, "text": "Custom Data Attributes allow you to add your own information to tags in HTML. Even though the name suggests otherwise, these are not specific to HTML5 and you can use the data-* attribute on all HTML elements. The data-* attributes can be used to define our own custom data attributes. It is used to store custom data in private to the page or application. There are mainly 2 parts of the Data Attributes: " }, { "code": null, "e": 25499, "s": 25354, "text": "Attribute Name: Must be at least one character long, contain no capital letters and be prefixed with ‘data-‘.Attribute Value: Can be any string." }, { "code": null, "e": 25609, "s": 25499, "text": "Attribute Name: Must be at least one character long, contain no capital letters and be prefixed with ‘data-‘." }, { "code": null, "e": 25645, "s": 25609, "text": "Attribute Value: Can be any string." }, { "code": null, "e": 25655, "s": 25645, "text": "Syntax: " }, { "code": null, "e": 25716, "s": 25655, "text": "<li data-book-author=\"Rabindra Nath Tagore\"> Gitanjali </li>" }, { "code": null, "e": 25727, "s": 25716, "text": "Example: " }, { "code": null, "e": 25732, "s": 25727, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <script> function showDetails(book) { var bookauthor = book.getAttribute(\"data-book-author\"); alert(book.innerHTML + \" is written by \" + bookauthor + \".\"); } </script></head> <body> <h1>Books</h1> <p>Click on the book name to know author's name :</p> <ul> <li onclick=\"showDetails(this)\" id=\"gitanjali\" data-book-author=\"Rabindra Nath Tagore\"> Gitanjali </li> <li onclick=\"showDetails(this)\" id=\"conquest_of_self\" data-book-author=\"Mahatma Gandhi\"> Conquest of Self </li> <li onclick=\"showDetails(this)\" id=\"broken_wings\" data-book-author=\"Sarojini Naidu\"> Broken Wings </li> </ul></body></html> ", "e": 26608, "s": 25732, "text": null }, { "code": null, "e": 26618, "s": 26608, "text": "Output: " }, { "code": null, "e": 26709, "s": 26618, "text": "When we click on the book, we can see the name of the author in a separate dialogue box. " }, { "code": null, "e": 26778, "s": 26709, "text": "Supported Browsers: The browser supported by HTML | data-* Attribute" }, { "code": null, "e": 26800, "s": 26778, "text": " are listed below: " }, { "code": null, "e": 26814, "s": 26800, "text": "Google Chrome" }, { "code": null, "e": 26832, "s": 26814, "text": "Internet Explorer" }, { "code": null, "e": 26840, "s": 26832, "text": "Firefox" }, { "code": null, "e": 26847, "s": 26840, "text": "Safari" }, { "code": null, "e": 26853, "s": 26847, "text": "Opera" }, { "code": null, "e": 26992, "s": 26855, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27012, "s": 26992, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27028, "s": 27012, "text": "HTML-Attributes" }, { "code": null, "e": 27035, "s": 27028, "text": "Picked" }, { "code": null, "e": 27039, "s": 27035, "text": "CSS" }, { "code": null, "e": 27044, "s": 27039, "text": "HTML" }, { "code": null, "e": 27061, "s": 27044, "text": "Web Technologies" }, { "code": null, "e": 27066, "s": 27061, "text": "HTML" }, { "code": null, "e": 27164, "s": 27066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27214, "s": 27164, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27276, "s": 27214, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27324, "s": 27276, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27382, "s": 27324, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27437, "s": 27382, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 27487, "s": 27437, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27549, "s": 27487, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27597, "s": 27549, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27657, "s": 27597, "text": "How to set the default value for an HTML <select> element ?" } ]
Breadth First Traversal ( BFS ) on a 2D array - GeeksforGeeks
31 May, 2021 Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0, 1}, {-1, -1, -2, -1}, {-1, -1, -1, -1}, {0, 0, 0, 0}}Output: -1 0 -1 0 -1 -1 1 -2 -1 0 -1 -1 0 -1 0 0 Approach: Follow the steps below to solve the problem: Initialize the direction vectors dRow[] = {-1, 0, 1, 0} and dCol[] = {0, 1, 0, -1} and a queue of pairs to store the indices of matrix cells.Start BFS traversal from the first cell, i.e. (0, 0), and enqueue the index of this cell into the queue.Initialize a boolean array to mark the visited cells of the matrix. Mark the cell (0, 0) as visited.Declare a function isValid() to check if the cell coordinates are valid or not, i.e lies within the boundaries of the given Matrix and are unvisited or not.Iterate while the queue is not empty and perform the following operations:Dequeue the cell present at the front of the queue and print it.Move to its adjacent cells that are not visited.Mark them visited and enqueue them into the queue. Initialize the direction vectors dRow[] = {-1, 0, 1, 0} and dCol[] = {0, 1, 0, -1} and a queue of pairs to store the indices of matrix cells. Start BFS traversal from the first cell, i.e. (0, 0), and enqueue the index of this cell into the queue. Initialize a boolean array to mark the visited cells of the matrix. Mark the cell (0, 0) as visited. Declare a function isValid() to check if the cell coordinates are valid or not, i.e lies within the boundaries of the given Matrix and are unvisited or not. Iterate while the queue is not empty and perform the following operations:Dequeue the cell present at the front of the queue and print it.Move to its adjacent cells that are not visited.Mark them visited and enqueue them into the queue. Dequeue the cell present at the front of the queue and print it. Move to its adjacent cells that are not visited. Mark them visited and enqueue them into the queue. Note: Direction vectors are used to traverse the adjacent cells of a given cell in a given order. For example (x, y) is a cell whose adjacent cells (x – 1, y), (x, y + 1), (x + 1, y), (x, y – 1) need to be traversed, then it can be done using the direction vectors (-1, 0), (0, 1), (1, 0), (0, -1) in the up, left, down and right order. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define ROW 4#define COL 4 // Direction vectorsint dRow[] = { -1, 0, 1, 0 };int dCol[] = { 0, 1, 0, -1 }; // Function to check if a cell// is be visited or notbool isValid(bool vis[][COL], int row, int col){ // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row][col]) return false; // Otherwise return true;} // Function to perform the BFS traversalvoid BFS(int grid[][COL], bool vis[][COL], int row, int col){ // Stores indices of the matrix cells queue<pair<int, int> > q; // Mark the starting cell as visited // and push it into the queue q.push({ row, col }); vis[row][col] = true; // Iterate while the queue // is not empty while (!q.empty()) { pair<int, int> cell = q.front(); int x = cell.first; int y = cell.second; cout << grid[x][y] << " "; q.pop(); // Go to the adjacent cells for (int i = 0; i < 4; i++) { int adjx = x + dRow[i]; int adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.push({ adjx, adjy }); vis[adjx][adjy] = true; } } }} // Driver Codeint main(){ // Given input matrix int grid[ROW][COL] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Declare the visited array bool vis[ROW][COL]; memset(vis, false, sizeof vis); BFS(grid, vis, 0, 0); return 0;} // Java program for the above approachimport java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static final int ROW = 4;static final int COL = 4; // Direction vectorsstatic int dRow[] = { -1, 0, 1, 0 };static int dCol[] = { 0, 1, 0, -1 }; // Function to check if a cell// is be visited or notstatic boolean isValid(boolean vis[][], int row, int col){ // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row][col]) return false; // Otherwise return true;} // Function to perform the BFS traversalstatic void BFS(int grid[][], boolean vis[][], int row, int col){ // Stores indices of the matrix cells Queue<pair > q = new LinkedList<>(); // Mark the starting cell as visited // and push it into the queue q.add(new pair(row, col)); vis[row][col] = true; // Iterate while the queue // is not empty while (!q.isEmpty()) { pair cell = q.peek(); int x = cell.first; int y = cell.second; System.out.print(grid[x][y] + " "); q.remove(); // Go to the adjacent cells for(int i = 0; i < 4; i++) { int adjx = x + dRow[i]; int adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.add(new pair(adjx, adjy)); vis[adjx][adjy] = true; } } }} // Driver Codepublic static void main(String[] args){ // Given input matrix int grid[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Declare the visited array boolean [][]vis = new boolean[ROW][COL]; BFS(grid, vis, 0, 0);}} // This code is contributed by 29AjayKumar # Python3 program for the above approachfrom collections import deque as queue # Direction vectorsdRow = [ -1, 0, 1, 0]dCol = [ 0, 1, 0, -1] # Function to check if a cell# is be visited or notdef isValid(vis, row, col): # If cell lies out of bounds if (row < 0 or col < 0 or row >= 4 or col >= 4): return False # If cell is already visited if (vis[row][col]): return False # Otherwise return True # Function to perform the BFS traversaldef BFS(grid, vis, row, col): # Stores indices of the matrix cells q = queue() # Mark the starting cell as visited # and push it into the queue q.append(( row, col )) vis[row][col] = True # Iterate while the queue # is not empty while (len(q) > 0): cell = q.popleft() x = cell[0] y = cell[1] print(grid[x][y], end = " ") #q.pop() # Go to the adjacent cells for i in range(4): adjx = x + dRow[i] adjy = y + dCol[i] if (isValid(vis, adjx, adjy)): q.append((adjx, adjy)) vis[adjx][adjy] = True # Driver Codeif __name__ == '__main__': # Given input matrix grid= [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] # Declare the visited array vis = [[ False for i in range(4)] for i in range(4)] # vis, False, sizeof vis) BFS(grid, vis, 0, 0) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Collections.Generic;public class GFG{ class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static readonly int ROW = 4; static readonly int COL = 4; // Direction vectors static int []dRow = { -1, 0, 1, 0 }; static int []dCol = { 0, 1, 0, -1 }; // Function to check if a cell // is be visited or not static bool isValid(bool [,]vis, int row, int col) { // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row,col]) return false; // Otherwise return true; } // Function to perform the BFS traversal static void BFS(int [,]grid, bool [,]vis, int row, int col) { // Stores indices of the matrix cells Queue<pair> q = new Queue<pair>(); // Mark the starting cell as visited // and push it into the queue q.Enqueue(new pair(row, col)); vis[row,col] = true; // Iterate while the queue // is not empty while (q.Count!=0) { pair cell = q.Peek(); int x = cell.first; int y = cell.second; Console.Write(grid[x,y] + " "); q.Dequeue(); // Go to the adjacent cells for(int i = 0; i < 4; i++) { int adjx = x + dRow[i]; int adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.Enqueue(new pair(adjx, adjy)); vis[adjx,adjy] = true; } } } } // Driver Code public static void Main(String[] args) { // Given input matrix int [,]grid = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Declare the visited array bool [,]vis = new bool[ROW,COL]; BFS(grid, vis, 0, 0); }} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach var ROW = 4;var COL = 4; // Direction vectorsvar dRow = [-1, 0, 1, 0 ];var dCol = [0, 1, 0, -1 ]; // Function to check if a cell// is be visited or notfunction isValid(vis, row, col){ // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row][col]) return false; // Otherwise return true;} // Function to perform the BFS traversalfunction BFS( grid, vis,row, col){ // Stores indices of the matrix cells var q = []; // Mark the starting cell as visited // and push it into the queue q.push([row, col ]); vis[row][col] = true; // Iterate while the queue // is not empty while (q.length!=0) { var cell = q[0]; var x = cell[0]; var y = cell[1]; document.write( grid[x][y] + " "); q.shift(); // Go to the adjacent cells for (var i = 0; i < 4; i++) { var adjx = x + dRow[i]; var adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.push([adjx, adjy ]); vis[adjx][adjy] = true; } } }} // Driver Code// Given input matrixvar grid = [[1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ];// Declare the visited arrayvar vis = Array.from(Array(ROW), ()=> Array(COL).fill(false));BFS(grid, vis, 0, 0); </script> 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Time Complexity: O(N * M)Auxiliary Space: O(N * M) mohit kumar 29 29AjayKumar rrrtnx array-traversal-question BFS Technical Scripter 2020 Competitive Programming Graph Matrix Technical Scripter Matrix Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 7 Best Coding Challenge Websites in 2020 What is Competitive Programming and How to Prepare for It? Formatted output in Java Algorithm Library | C++ Magicians STL Algorithm Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Graph and its representations
[ { "code": null, "e": 26567, "s": 26539, "text": "\n31 May, 2021" }, { "code": null, "e": 26699, "s": 26567, "text": "Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal." }, { "code": null, "e": 26709, "s": 26699, "text": "Examples:" }, { "code": null, "e": 26837, "s": 26709, "text": "Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16" }, { "code": null, "e": 26969, "s": 26837, "text": "Input: grid[][] = {{-1, 0, 0, 1}, {-1, -1, -2, -1}, {-1, -1, -1, -1}, {0, 0, 0, 0}}Output: -1 0 -1 0 -1 -1 1 -2 -1 0 -1 -1 0 -1 0 0" }, { "code": null, "e": 27024, "s": 26969, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 27762, "s": 27024, "text": "Initialize the direction vectors dRow[] = {-1, 0, 1, 0} and dCol[] = {0, 1, 0, -1} and a queue of pairs to store the indices of matrix cells.Start BFS traversal from the first cell, i.e. (0, 0), and enqueue the index of this cell into the queue.Initialize a boolean array to mark the visited cells of the matrix. Mark the cell (0, 0) as visited.Declare a function isValid() to check if the cell coordinates are valid or not, i.e lies within the boundaries of the given Matrix and are unvisited or not.Iterate while the queue is not empty and perform the following operations:Dequeue the cell present at the front of the queue and print it.Move to its adjacent cells that are not visited.Mark them visited and enqueue them into the queue." }, { "code": null, "e": 27904, "s": 27762, "text": "Initialize the direction vectors dRow[] = {-1, 0, 1, 0} and dCol[] = {0, 1, 0, -1} and a queue of pairs to store the indices of matrix cells." }, { "code": null, "e": 28009, "s": 27904, "text": "Start BFS traversal from the first cell, i.e. (0, 0), and enqueue the index of this cell into the queue." }, { "code": null, "e": 28110, "s": 28009, "text": "Initialize a boolean array to mark the visited cells of the matrix. Mark the cell (0, 0) as visited." }, { "code": null, "e": 28267, "s": 28110, "text": "Declare a function isValid() to check if the cell coordinates are valid or not, i.e lies within the boundaries of the given Matrix and are unvisited or not." }, { "code": null, "e": 28504, "s": 28267, "text": "Iterate while the queue is not empty and perform the following operations:Dequeue the cell present at the front of the queue and print it.Move to its adjacent cells that are not visited.Mark them visited and enqueue them into the queue." }, { "code": null, "e": 28569, "s": 28504, "text": "Dequeue the cell present at the front of the queue and print it." }, { "code": null, "e": 28618, "s": 28569, "text": "Move to its adjacent cells that are not visited." }, { "code": null, "e": 28669, "s": 28618, "text": "Mark them visited and enqueue them into the queue." }, { "code": null, "e": 29006, "s": 28669, "text": "Note: Direction vectors are used to traverse the adjacent cells of a given cell in a given order. For example (x, y) is a cell whose adjacent cells (x – 1, y), (x, y + 1), (x + 1, y), (x, y – 1) need to be traversed, then it can be done using the direction vectors (-1, 0), (0, 1), (1, 0), (0, -1) in the up, left, down and right order." }, { "code": null, "e": 29057, "s": 29006, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29061, "s": 29057, "text": "C++" }, { "code": null, "e": 29066, "s": 29061, "text": "Java" }, { "code": null, "e": 29074, "s": 29066, "text": "Python3" }, { "code": null, "e": 29077, "s": 29074, "text": "C#" }, { "code": null, "e": 29088, "s": 29077, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define ROW 4#define COL 4 // Direction vectorsint dRow[] = { -1, 0, 1, 0 };int dCol[] = { 0, 1, 0, -1 }; // Function to check if a cell// is be visited or notbool isValid(bool vis[][COL], int row, int col){ // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row][col]) return false; // Otherwise return true;} // Function to perform the BFS traversalvoid BFS(int grid[][COL], bool vis[][COL], int row, int col){ // Stores indices of the matrix cells queue<pair<int, int> > q; // Mark the starting cell as visited // and push it into the queue q.push({ row, col }); vis[row][col] = true; // Iterate while the queue // is not empty while (!q.empty()) { pair<int, int> cell = q.front(); int x = cell.first; int y = cell.second; cout << grid[x][y] << \" \"; q.pop(); // Go to the adjacent cells for (int i = 0; i < 4; i++) { int adjx = x + dRow[i]; int adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.push({ adjx, adjy }); vis[adjx][adjy] = true; } } }} // Driver Codeint main(){ // Given input matrix int grid[ROW][COL] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Declare the visited array bool vis[ROW][COL]; memset(vis, false, sizeof vis); BFS(grid, vis, 0, 0); return 0;}", "e": 30798, "s": 29088, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static final int ROW = 4;static final int COL = 4; // Direction vectorsstatic int dRow[] = { -1, 0, 1, 0 };static int dCol[] = { 0, 1, 0, -1 }; // Function to check if a cell// is be visited or notstatic boolean isValid(boolean vis[][], int row, int col){ // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row][col]) return false; // Otherwise return true;} // Function to perform the BFS traversalstatic void BFS(int grid[][], boolean vis[][], int row, int col){ // Stores indices of the matrix cells Queue<pair > q = new LinkedList<>(); // Mark the starting cell as visited // and push it into the queue q.add(new pair(row, col)); vis[row][col] = true; // Iterate while the queue // is not empty while (!q.isEmpty()) { pair cell = q.peek(); int x = cell.first; int y = cell.second; System.out.print(grid[x][y] + \" \"); q.remove(); // Go to the adjacent cells for(int i = 0; i < 4; i++) { int adjx = x + dRow[i]; int adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.add(new pair(adjx, adjy)); vis[adjx][adjy] = true; } } }} // Driver Codepublic static void main(String[] args){ // Given input matrix int grid[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Declare the visited array boolean [][]vis = new boolean[ROW][COL]; BFS(grid, vis, 0, 0);}} // This code is contributed by 29AjayKumar", "e": 32799, "s": 30798, "text": null }, { "code": "# Python3 program for the above approachfrom collections import deque as queue # Direction vectorsdRow = [ -1, 0, 1, 0]dCol = [ 0, 1, 0, -1] # Function to check if a cell# is be visited or notdef isValid(vis, row, col): # If cell lies out of bounds if (row < 0 or col < 0 or row >= 4 or col >= 4): return False # If cell is already visited if (vis[row][col]): return False # Otherwise return True # Function to perform the BFS traversaldef BFS(grid, vis, row, col): # Stores indices of the matrix cells q = queue() # Mark the starting cell as visited # and push it into the queue q.append(( row, col )) vis[row][col] = True # Iterate while the queue # is not empty while (len(q) > 0): cell = q.popleft() x = cell[0] y = cell[1] print(grid[x][y], end = \" \") #q.pop() # Go to the adjacent cells for i in range(4): adjx = x + dRow[i] adjy = y + dCol[i] if (isValid(vis, adjx, adjy)): q.append((adjx, adjy)) vis[adjx][adjy] = True # Driver Codeif __name__ == '__main__': # Given input matrix grid= [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] # Declare the visited array vis = [[ False for i in range(4)] for i in range(4)] # vis, False, sizeof vis) BFS(grid, vis, 0, 0) # This code is contributed by mohit kumar 29.", "e": 34277, "s": 32799, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{ class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static readonly int ROW = 4; static readonly int COL = 4; // Direction vectors static int []dRow = { -1, 0, 1, 0 }; static int []dCol = { 0, 1, 0, -1 }; // Function to check if a cell // is be visited or not static bool isValid(bool [,]vis, int row, int col) { // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row,col]) return false; // Otherwise return true; } // Function to perform the BFS traversal static void BFS(int [,]grid, bool [,]vis, int row, int col) { // Stores indices of the matrix cells Queue<pair> q = new Queue<pair>(); // Mark the starting cell as visited // and push it into the queue q.Enqueue(new pair(row, col)); vis[row,col] = true; // Iterate while the queue // is not empty while (q.Count!=0) { pair cell = q.Peek(); int x = cell.first; int y = cell.second; Console.Write(grid[x,y] + \" \"); q.Dequeue(); // Go to the adjacent cells for(int i = 0; i < 4; i++) { int adjx = x + dRow[i]; int adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.Enqueue(new pair(adjx, adjy)); vis[adjx,adjy] = true; } } } } // Driver Code public static void Main(String[] args) { // Given input matrix int [,]grid = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Declare the visited array bool [,]vis = new bool[ROW,COL]; BFS(grid, vis, 0, 0); }} // This code is contributed by 29AjayKumar", "e": 36246, "s": 34277, "text": null }, { "code": "<script> // Javascript program for the above approach var ROW = 4;var COL = 4; // Direction vectorsvar dRow = [-1, 0, 1, 0 ];var dCol = [0, 1, 0, -1 ]; // Function to check if a cell// is be visited or notfunction isValid(vis, row, col){ // If cell lies out of bounds if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; // If cell is already visited if (vis[row][col]) return false; // Otherwise return true;} // Function to perform the BFS traversalfunction BFS( grid, vis,row, col){ // Stores indices of the matrix cells var q = []; // Mark the starting cell as visited // and push it into the queue q.push([row, col ]); vis[row][col] = true; // Iterate while the queue // is not empty while (q.length!=0) { var cell = q[0]; var x = cell[0]; var y = cell[1]; document.write( grid[x][y] + \" \"); q.shift(); // Go to the adjacent cells for (var i = 0; i < 4; i++) { var adjx = x + dRow[i]; var adjy = y + dCol[i]; if (isValid(vis, adjx, adjy)) { q.push([adjx, adjy ]); vis[adjx][adjy] = true; } } }} // Driver Code// Given input matrixvar grid = [[1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ];// Declare the visited arrayvar vis = Array.from(Array(ROW), ()=> Array(COL).fill(false));BFS(grid, vis, 0, 0); </script>", "e": 37772, "s": 36246, "text": null }, { "code": null, "e": 37811, "s": 37772, "text": "1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16" }, { "code": null, "e": 37864, "s": 37813, "text": "Time Complexity: O(N * M)Auxiliary Space: O(N * M)" }, { "code": null, "e": 37881, "s": 37866, "text": "mohit kumar 29" }, { "code": null, "e": 37893, "s": 37881, "text": "29AjayKumar" }, { "code": null, "e": 37900, "s": 37893, "text": "rrrtnx" }, { "code": null, "e": 37925, "s": 37900, "text": "array-traversal-question" }, { "code": null, "e": 37929, "s": 37925, "text": "BFS" }, { "code": null, "e": 37953, "s": 37929, "text": "Technical Scripter 2020" }, { "code": null, "e": 37977, "s": 37953, "text": "Competitive Programming" }, { "code": null, "e": 37983, "s": 37977, "text": "Graph" }, { "code": null, "e": 37990, "s": 37983, "text": "Matrix" }, { "code": null, "e": 38009, "s": 37990, "text": "Technical Scripter" }, { "code": null, "e": 38016, "s": 38009, "text": "Matrix" }, { "code": null, "e": 38022, "s": 38016, "text": "Graph" }, { "code": null, "e": 38026, "s": 38022, "text": "BFS" }, { "code": null, "e": 38124, "s": 38026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38153, "s": 38124, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 38194, "s": 38153, "text": "7 Best Coding Challenge Websites in 2020" }, { "code": null, "e": 38253, "s": 38194, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 38278, "s": 38253, "text": "Formatted output in Java" }, { "code": null, "e": 38326, "s": 38278, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 38377, "s": 38326, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 38428, "s": 38377, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 38486, "s": 38428, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Convert vowels into upper case character in a given string
27 Apr, 2021 Given string str, the task is to convert all the vowels present in the given string to uppercase characters in the given string. Examples: Input: str = “GeeksforGeeks”Output: GEEksfOrGEEksExplanation:Vowels present in the given string are: {‘e’, ‘o’}Replace ‘e’ to ‘E’ and ‘o’ to ‘O’.Therefore, the required output is GEEksfOrGEEks. Input: str = “eutopia”Output: EUtOpIA Approach: The idea is to iterate over the characters of the given string and check if the current character is a lowercase character and a vowel or not. If found to be true, convert the character to its uppercase. Follow the steps below to solve the problem: Traverse the given string and check if str[i] is a lowercase vowel or not. If found to be true, replace str[i] to (str[i] – ‘a’ + ‘A’). Finally, after complete the traversal of the string, print the final string. Below is the implementation of the approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to convert vowels// into uppercasestring conVowUpp(string& str){ // Stores the length // of str int N = str.length(); for (int i = 0; i < N; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') { str[i] = str[i] - 'a' + 'A'; } } return str;} // Driver Codeint main(){ string str = "eutopia"; cout << conVowUpp(str);} // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to convert vowels// into uppercasestatic void conVowUpp(char[] str){ // Stores the length // of str int N = str.length; for (int i = 0; i < N; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') { char c = Character.toUpperCase(str[i]); str[i] = c; } } for(char c : str) System.out.print(c);} // Driver Codepublic static void main(String[] args){ String str = "eutopia"; conVowUpp(str.toCharArray());}} // This code is contributed by 29AjayKumar # Python3 program to implement# the above approach # Function to convert vowels# into uppercasedef conVowUpp(str): # Stores the length # of str N = len(str) str1 ="" for i in range(N): if (str[i] == 'a' or str[i] == 'e' or str[i] == 'i' or str[i] == 'o' or str[i] == 'u'): c = (str[i]).upper() str1 += c else: str1 += str[i] print(str1) # Driver Codeif __name__ == '__main__': str = "eutopia" conVowUpp(str) # This code is contributed by Amit Katiyar // C# program to implement// the above approachusing System;class GFG{ // Function to convert vowels// into uppercasestatic void conVowUpp(char[] str){ // Stores the length // of str int N = str.Length; for (int i = 0; i < N; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') { char c = char.ToUpperInvariant(str[i]); str[i] = c; } } foreach(char c in str) Console.Write(c);} // Driver Codepublic static void Main(String[] args){ String str = "eutopia"; conVowUpp(str.ToCharArray());}} // This code is contributed by shikhasingrajput <script> // JavaScript program to implement // the above approach // Function to convert vowels // into uppercase function conVowUpp(str) { // Stores the length // of str var N = str.length; for (var i = 0; i < N; i++) { if ( str[i] === "a" || str[i] === "e" || str[i] === "i" || str[i] === "o" || str[i] === "u" ) { document.write(str[i].toUpperCase()); } else { document.write(str[i]); } } } // Driver Code var str = "eutopia"; conVowUpp(str); </script> EUtOpIA Time Complexity: O(N)Auxiliary Space: O(1) 29AjayKumar shikhasingrajput amit143katiyar simmytarika5 rdtank School Programming Searching Strings Searching Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2021" }, { "code": null, "e": 157, "s": 28, "text": "Given string str, the task is to convert all the vowels present in the given string to uppercase characters in the given string." }, { "code": null, "e": 167, "s": 157, "text": "Examples:" }, { "code": null, "e": 361, "s": 167, "text": "Input: str = “GeeksforGeeks”Output: GEEksfOrGEEksExplanation:Vowels present in the given string are: {‘e’, ‘o’}Replace ‘e’ to ‘E’ and ‘o’ to ‘O’.Therefore, the required output is GEEksfOrGEEks." }, { "code": null, "e": 399, "s": 361, "text": "Input: str = “eutopia”Output: EUtOpIA" }, { "code": null, "e": 658, "s": 399, "text": "Approach: The idea is to iterate over the characters of the given string and check if the current character is a lowercase character and a vowel or not. If found to be true, convert the character to its uppercase. Follow the steps below to solve the problem:" }, { "code": null, "e": 733, "s": 658, "text": "Traverse the given string and check if str[i] is a lowercase vowel or not." }, { "code": null, "e": 794, "s": 733, "text": "If found to be true, replace str[i] to (str[i] – ‘a’ + ‘A’)." }, { "code": null, "e": 871, "s": 794, "text": "Finally, after complete the traversal of the string, print the final string." }, { "code": null, "e": 916, "s": 871, "text": "Below is the implementation of the approach:" }, { "code": null, "e": 920, "s": 916, "text": "C++" }, { "code": null, "e": 925, "s": 920, "text": "Java" }, { "code": null, "e": 933, "s": 925, "text": "Python3" }, { "code": null, "e": 936, "s": 933, "text": "C#" }, { "code": null, "e": 947, "s": 936, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to convert vowels// into uppercasestring conVowUpp(string& str){ // Stores the length // of str int N = str.length(); for (int i = 0; i < N; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') { str[i] = str[i] - 'a' + 'A'; } } return str;} // Driver Codeint main(){ string str = \"eutopia\"; cout << conVowUpp(str);}", "e": 1483, "s": 947, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to convert vowels// into uppercasestatic void conVowUpp(char[] str){ // Stores the length // of str int N = str.length; for (int i = 0; i < N; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') { char c = Character.toUpperCase(str[i]); str[i] = c; } } for(char c : str) System.out.print(c);} // Driver Codepublic static void main(String[] args){ String str = \"eutopia\"; conVowUpp(str.toCharArray());}} // This code is contributed by 29AjayKumar", "e": 2108, "s": 1483, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to convert vowels# into uppercasedef conVowUpp(str): # Stores the length # of str N = len(str) str1 =\"\" for i in range(N): if (str[i] == 'a' or str[i] == 'e' or str[i] == 'i' or str[i] == 'o' or str[i] == 'u'): c = (str[i]).upper() str1 += c else: str1 += str[i] print(str1) # Driver Codeif __name__ == '__main__': str = \"eutopia\" conVowUpp(str) # This code is contributed by Amit Katiyar", "e": 2678, "s": 2108, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to convert vowels// into uppercasestatic void conVowUpp(char[] str){ // Stores the length // of str int N = str.Length; for (int i = 0; i < N; i++) { if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') { char c = char.ToUpperInvariant(str[i]); str[i] = c; } } foreach(char c in str) Console.Write(c);} // Driver Codepublic static void Main(String[] args){ String str = \"eutopia\"; conVowUpp(str.ToCharArray());}} // This code is contributed by shikhasingrajput", "e": 3302, "s": 2678, "text": null }, { "code": "<script> // JavaScript program to implement // the above approach // Function to convert vowels // into uppercase function conVowUpp(str) { // Stores the length // of str var N = str.length; for (var i = 0; i < N; i++) { if ( str[i] === \"a\" || str[i] === \"e\" || str[i] === \"i\" || str[i] === \"o\" || str[i] === \"u\" ) { document.write(str[i].toUpperCase()); } else { document.write(str[i]); } } } // Driver Code var str = \"eutopia\"; conVowUpp(str); </script>", "e": 3968, "s": 3302, "text": null }, { "code": null, "e": 3976, "s": 3968, "text": "EUtOpIA" }, { "code": null, "e": 4021, "s": 3978, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 4033, "s": 4021, "text": "29AjayKumar" }, { "code": null, "e": 4050, "s": 4033, "text": "shikhasingrajput" }, { "code": null, "e": 4065, "s": 4050, "text": "amit143katiyar" }, { "code": null, "e": 4078, "s": 4065, "text": "simmytarika5" }, { "code": null, "e": 4085, "s": 4078, "text": "rdtank" }, { "code": null, "e": 4104, "s": 4085, "text": "School Programming" }, { "code": null, "e": 4114, "s": 4104, "text": "Searching" }, { "code": null, "e": 4122, "s": 4114, "text": "Strings" }, { "code": null, "e": 4132, "s": 4122, "text": "Searching" }, { "code": null, "e": 4140, "s": 4132, "text": "Strings" } ]
Python – Insertion at the beginning in OrderedDict
15 Oct, 2021 Given an ordered dict, write a program to insert items in beginning of ordered dict.Examples – Input: original_dict = {'a':1, 'b':2} item to be inserted ('c', 3) Output: {'c':3, 'a':1, 'b':2} Input: original_dict = {'akshat':1, 'manjeet':2} item to be inserted ('nikhil', 3) Output: {'nikhil':3, 'akshat':1, 'manjeet':2} Below are various methods to insert items in starting of ordered dict.Method #1: Using OrderedDict.move_to_end() Python3 # Python code to demonstrate# insertion of items in beginning of ordered dictfrom collections import OrderedDict # initialising ordered_dictiniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')]) # inserting items in starting of dictiniordered_dict.update({'manjeet':'3'})iniordered_dict.move_to_end('manjeet', last = False) # print resultprint ("Resultant Dictionary : "+str(iniordered_dict)) Output: Resultant Dictionary : OrderedDict([(‘manjeet’, ‘3’), (‘akshat’, ‘1’), (‘nikhil’, ‘2’)]) Method #2: Using Naive ApproachThis method only works in case of unique keys Python3 # Python code to demonstrate# insertion of items in beginning of ordered dictfrom collections import OrderedDict # initialising ordered_dictini_dict1 = OrderedDict([('akshat', '1'), ('nikhil', '2')])ini_dict2 = OrderedDict([("manjeet", '4'), ("akash", '4')]) # adding in beginning of dictboth = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items())) # print resultprint ("Resultant Dictionary :"+str(both)) Output: Resultant Dictionary :OrderedDict([(‘manjeet’, ‘4’), (‘akash’, ‘4’), (‘akshat’, ‘1’), (‘nikhil’, ‘2’)]) anikakapoor Python dictionary-programs Python Python Programs 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 | os.path.join() method Python OOPs Concepts Introduction To PYTHON Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Oct, 2021" }, { "code": null, "e": 150, "s": 53, "text": "Given an ordered dict, write a program to insert items in beginning of ordered dict.Examples – " }, { "code": null, "e": 383, "s": 150, "text": "Input: \noriginal_dict = {'a':1, 'b':2}\nitem to be inserted ('c', 3)\n\nOutput: {'c':3, 'a':1, 'b':2}\n\nInput: \noriginal_dict = {'akshat':1, 'manjeet':2}\nitem to be inserted ('nikhil', 3)\n\nOutput: {'nikhil':3, 'akshat':1, 'manjeet':2}" }, { "code": null, "e": 499, "s": 383, "text": " Below are various methods to insert items in starting of ordered dict.Method #1: Using OrderedDict.move_to_end() " }, { "code": null, "e": 507, "s": 499, "text": "Python3" }, { "code": "# Python code to demonstrate# insertion of items in beginning of ordered dictfrom collections import OrderedDict # initialising ordered_dictiniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')]) # inserting items in starting of dictiniordered_dict.update({'manjeet':'3'})iniordered_dict.move_to_end('manjeet', last = False) # print resultprint (\"Resultant Dictionary : \"+str(iniordered_dict))", "e": 911, "s": 507, "text": null }, { "code": null, "e": 921, "s": 911, "text": "Output: " }, { "code": null, "e": 1012, "s": 921, "text": "Resultant Dictionary : OrderedDict([(‘manjeet’, ‘3’), (‘akshat’, ‘1’), (‘nikhil’, ‘2’)]) " }, { "code": null, "e": 1093, "s": 1012, "text": " Method #2: Using Naive ApproachThis method only works in case of unique keys " }, { "code": null, "e": 1101, "s": 1093, "text": "Python3" }, { "code": "# Python code to demonstrate# insertion of items in beginning of ordered dictfrom collections import OrderedDict # initialising ordered_dictini_dict1 = OrderedDict([('akshat', '1'), ('nikhil', '2')])ini_dict2 = OrderedDict([(\"manjeet\", '4'), (\"akash\", '4')]) # adding in beginning of dictboth = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items())) # print resultprint (\"Resultant Dictionary :\"+str(both))", "e": 1516, "s": 1101, "text": null }, { "code": null, "e": 1526, "s": 1516, "text": "Output: " }, { "code": null, "e": 1632, "s": 1526, "text": "Resultant Dictionary :OrderedDict([(‘manjeet’, ‘4’), (‘akash’, ‘4’), (‘akshat’, ‘1’), (‘nikhil’, ‘2’)]) " }, { "code": null, "e": 1646, "s": 1634, "text": "anikakapoor" }, { "code": null, "e": 1673, "s": 1646, "text": "Python dictionary-programs" }, { "code": null, "e": 1680, "s": 1673, "text": "Python" }, { "code": null, "e": 1696, "s": 1680, "text": "Python Programs" }, { "code": null, "e": 1794, "s": 1696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1826, "s": 1794, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1853, "s": 1826, "text": "Python Classes and Objects" }, { "code": null, "e": 1884, "s": 1853, "text": "Python | os.path.join() method" }, { "code": null, "e": 1905, "s": 1884, "text": "Python OOPs Concepts" }, { "code": null, "e": 1928, "s": 1905, "text": "Introduction To PYTHON" }, { "code": null, "e": 1950, "s": 1928, "text": "Defaultdict in Python" }, { "code": null, "e": 1989, "s": 1950, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2027, "s": 1989, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2064, "s": 2027, "text": "Python Program for Fibonacci numbers" } ]
How to send email using PowerShell?
To send email using PowerShell, there are multiple methods but there is a simple command called SendMailMessage. This command is a part of the module called Microsoft.PowerShell.Utility To send email using the specific SMTP server we need to add the SMTP server parameter. Send-MailMessage ` -From '[email protected]' ` -To '[email protected]' ` -Subject 'Test Email' ` -SmtpServer 'Smtp.TestDomain.com' In the above example, an email will be sent from the -From parameter, a user to -To parameter users with the subject name ‘Test Email’ with the specified SMTP server name. If you have multiple users then you can separate them using a comma and you can also add CC and BCC recipients. For example, Send-MailMessage ` -From '[email protected]' ` -To '[email protected]','[email protected]' ` -Cc '[email protected]' ` -Bcc '[email protected]' -Subject 'Test Email' ` -Attachments 'C:\Temp\Confidential.pdf' -SmtpServer 'Smtp.TestDomain.com' In the above example, an attachment will be stored from the location C:\temp. If your SMTP server requires an SSL connection on the specific port then you can also specify it for example, Send-MailMessage ` -From '[email protected]' ` -To '[email protected]','[email protected]' ` -Subject 'Test Email' ` -SmtpServer 'Smtp.TestDomain.com' ` -UseSsl -Port 587 -Priority High We are using here SSL connection on the 587 port with a High Priority email. You can also set Priority to Normal (Default) or Low. If your server using different SMTP credentials then you can provide credential parameters as well and you can also the Delivery Notification on Delay, Success, Failure, or Never. The default is None. $creds = Get-Credential Send-MailMessage ` -From '[email protected]' ` -To '[email protected]','[email protected]' ` -Subject 'Test Email' ` -SmtpServer 'Smtp.TestDomain.com' ` -UseSsl -Port 587 -Priority High ` -Credential $creds ` -DeliveryNotificationOption OnSuccess
[ { "code": null, "e": 1248, "s": 1062, "text": "To send email using PowerShell, there are multiple methods but there is a simple command called SendMailMessage. This command is a part of the module called Microsoft.PowerShell.Utility" }, { "code": null, "e": 1335, "s": 1248, "text": "To send email using the specific SMTP server we need to add the SMTP server parameter." }, { "code": null, "e": 1484, "s": 1335, "text": "Send-MailMessage `\n -From '[email protected]' `\n -To '[email protected]' `\n -Subject 'Test Email' `\n -SmtpServer 'Smtp.TestDomain.com'" }, { "code": null, "e": 1656, "s": 1484, "text": "In the above example, an email will be sent from the -From parameter, a user to -To parameter users with the subject name ‘Test Email’ with the specified SMTP server name." }, { "code": null, "e": 1781, "s": 1656, "text": "If you have multiple users then you can separate them using a comma and you can also add CC and BCC recipients. For example," }, { "code": null, "e": 2065, "s": 1781, "text": "Send-MailMessage `\n -From '[email protected]' `\n -To '[email protected]','[email protected]' `\n -Cc '[email protected]' `\n -Bcc '[email protected]'\n -Subject 'Test Email' `\n -Attachments 'C:\\Temp\\Confidential.pdf'\n -SmtpServer 'Smtp.TestDomain.com'" }, { "code": null, "e": 2143, "s": 2065, "text": "In the above example, an attachment will be stored from the location C:\\temp." }, { "code": null, "e": 2253, "s": 2143, "text": "If your SMTP server requires an SSL connection on the specific port then you can also specify it for example," }, { "code": null, "e": 2463, "s": 2253, "text": "Send-MailMessage `\n -From '[email protected]' `\n -To '[email protected]','[email protected]' `\n -Subject 'Test Email' `\n -SmtpServer 'Smtp.TestDomain.com' `\n -UseSsl -Port 587 -Priority High" }, { "code": null, "e": 2594, "s": 2463, "text": "We are using here SSL connection on the 587 port with a High Priority email. You can also set Priority to Normal (Default) or Low." }, { "code": null, "e": 2795, "s": 2594, "text": "If your server using different SMTP credentials then you can provide credential parameters as well and you can also the Delivery Notification on Delay, Success, Failure, or Never. The default is None." }, { "code": null, "e": 3096, "s": 2795, "text": "$creds = Get-Credential\nSend-MailMessage `\n -From '[email protected]' `\n -To '[email protected]','[email protected]' `\n -Subject 'Test Email' `\n -SmtpServer 'Smtp.TestDomain.com' `\n -UseSsl -Port 587 -Priority High `\n -Credential $creds `\n -DeliveryNotificationOption OnSuccess" } ]
Can neural networks solve any problem? | by Brendan Fortuner | Towards Data Science
At some point in your deep learning journey you probably came across the Universal Approximation Theorem. A feedforward network with a single layer is sufficient to represent any function, but the layer may be infeasibly large and may fail to learn and generalize correctly. — Ian Goodfellow, DLB This is an incredible statement. If you accept most classes of problems can be reduced to functions, this statement implies a neural network can, in theory, solve any problem. If human intelligence can be modeled with functions (exceedingly complex ones perhaps), then we have the tools to reproduce human intelligence today. Neural nets might be AI’s version of the Babbage analytical engine (1822) whereas the Terminator needs a Macbook Pro, but still. Perhaps UAT explains why deep learning has been so successfully tackling “hard problems” in AI —image recognition, machine translation, speech-to-text, etc. TLDR; I prove to myself visually and empirically that UAT holds for a non-trivial function (x3+x2-x -1) using a single hidden layer and 6 neurons. I pretend I’m a neural network and try to “learn” the correct weights on my own. I also verify this works in code. This question stumped me for a long time and I couldn’t find a great explanation online. Most explanations with a sentence-to-equation ratio above .57 would read something like: Introducing non-linearity via an activation function allows us to approximate any function. It’s quite simple, really. — Elon Musk So nonlinear activation functions are the secret sauce? Can we really model any function by chaining together a bunch of Sigmoid activations? How about the ReLU function? Surely not— it has the word linear in it! Rectified Linear Units! I eventually discovered Michael Neilson’s tutorial which is so good it nearly renders this post obsolete (I highly encourage you to read it!), but for now let’s travel back in time and pretend Michael took his family to Disneyland that day instead of writing the world’s greatest tutorial on neural networks ever. Thanks, Michael ;) I realized early on I wasn’t going to win this battle perusing mathematical proofs, so I decided to take an experimental approach. I went to Desmos and started chaining together ReLU activation functions to see if I could build something interesting-looking. After each attempt I tweaked my functions to make them look more like the target—sound familiar? I chose x3+x2-x -1 as my target function. Using only ReLU max(0,x), I iteratively tried different combinations of ReLUs until I had an output that roughly resembled the target. Here are the results I achieved taking the weighted sum of 3 ReLUs. Not bad? The left chart shows the ReLU functions. The right chart shows the output of my model compared to the target. You can think of each ReLU function as a neuron. So combining 3 ReLU functions is like training a network of 3 hidden neurons. Here are the equations I used to generate these charts. Each neuron’s output equals ReLU wrapped around the weighted input wx + b. I found I could shift the ReLU function left and right by changing the bias and adjust the slope by changing the weight. I combined these 3 functions into a final sum of weighted inputs (Z) which is standard practice in most neural networks. The negative signs in Z represent the final layer’s weights which I set to -1 in order to “flip” the graph across the x-axis to match our concave target. After playing around a bit more I finally arrived at the following 7 equations that, together, roughly approximate x3+x2-x -1. So visually at least, it looks like it IS possible to model non-trivial functions with a single hidden layer and a handful of neurons. Pretty cool. Here is a diagram of a neural network initialized with my fake weights and biases. If you give this network a dataset that resembles x3+x2-x-1, it should be able approximate the correct output for inputs between -2 and 2. That last statement, approximate the correct output for any input between -2 and 2, is key. The Universal Approximation Theorem states that a neural network with 1 hidden layer can approximate any continuous function for inputs within a specific range. If the function jumps around or has large gaps, we won’t be able to approximate it. Additionally, if we train a network on inputs between 10 and 20, we can’t say for sure whether it will work on inputs between 40 and 50. I wanted to prove programmatically the weights I came up with actually work when plugged into a basic neural network with one hidden layer and 6 neurons. Instead of training the network to learn weights, however, I replaced its default weights and biases with my hand-picked values. The method feed_forward() below takes a vector of inputs (e.g. [-2,-1,0,1..]) and outputs a vector of predictions using my weights. Here’s what happened: Look at that! I’m a genius. It’s exactly what we wanted. But what if our boss asks us to expand the range beyond -2 to 2? What if she wants -5 to 5? Ah, not so great. But this actually supports our earlier conclusion: a neural network with one hidden layer can approximate any continuous function but only for inputs within a specific range. If you train a network on inputs between -2 and 2, like we did, then it will work well for inputs in a similar range, but you can’t expect it to generalize to other inputs without retraining the model or adding more hidden neurons. Now we know Brendan Fortuner can learn these weights on his own, but can a real-world neural network with 1 hidden layer and 6 neurons also learn these parameters or others that lead to the same result? Let’s use scikit-neuralnetwork to test this theory. We’ll design a network so it works for regression problems and configure it to use ReLU, Stochastic Gradient Descent, and Mean Squared Error — the usual gang. It worked! Here are the weights Scikit learned. They’re clearly different from my own, but the order of magnitude is the same. hiddenLayerWeights = [ [-1.5272, -1.0567, -0.2828, 1.0399, 0.1243, 2.2446]]finalLayerWeights = [ [-2.2466], [ 1.0707], [-1.0643], [ 1.8229], [-0.4581], [ 2.9386]] Perhaps if I rewrote this blog post 100,000 times I would have come to these parameters on my own, but for now we can only speculate. Maybe someday I’ll take the derivative of my up-votes and update my sentences in the direction that maximizes views. Please hit the ♥ button below if you enjoyed reading!
[ { "code": null, "e": 277, "s": 171, "text": "At some point in your deep learning journey you probably came across the Universal Approximation Theorem." }, { "code": null, "e": 446, "s": 277, "text": "A feedforward network with a single layer is sufficient to represent any function, but the layer may be infeasibly large and may fail to learn and generalize correctly." }, { "code": null, "e": 468, "s": 446, "text": "— Ian Goodfellow, DLB" }, { "code": null, "e": 1080, "s": 468, "text": "This is an incredible statement. If you accept most classes of problems can be reduced to functions, this statement implies a neural network can, in theory, solve any problem. If human intelligence can be modeled with functions (exceedingly complex ones perhaps), then we have the tools to reproduce human intelligence today. Neural nets might be AI’s version of the Babbage analytical engine (1822) whereas the Terminator needs a Macbook Pro, but still. Perhaps UAT explains why deep learning has been so successfully tackling “hard problems” in AI —image recognition, machine translation, speech-to-text, etc." }, { "code": null, "e": 1342, "s": 1080, "text": "TLDR; I prove to myself visually and empirically that UAT holds for a non-trivial function (x3+x2-x -1) using a single hidden layer and 6 neurons. I pretend I’m a neural network and try to “learn” the correct weights on my own. I also verify this works in code." }, { "code": null, "e": 1520, "s": 1342, "text": "This question stumped me for a long time and I couldn’t find a great explanation online. Most explanations with a sentence-to-equation ratio above .57 would read something like:" }, { "code": null, "e": 1651, "s": 1520, "text": "Introducing non-linearity via an activation function allows us to approximate any function. It’s quite simple, really. — Elon Musk" }, { "code": null, "e": 1888, "s": 1651, "text": "So nonlinear activation functions are the secret sauce? Can we really model any function by chaining together a bunch of Sigmoid activations? How about the ReLU function? Surely not— it has the word linear in it! Rectified Linear Units!" }, { "code": null, "e": 2221, "s": 1888, "text": "I eventually discovered Michael Neilson’s tutorial which is so good it nearly renders this post obsolete (I highly encourage you to read it!), but for now let’s travel back in time and pretend Michael took his family to Disneyland that day instead of writing the world’s greatest tutorial on neural networks ever. Thanks, Michael ;)" }, { "code": null, "e": 2577, "s": 2221, "text": "I realized early on I wasn’t going to win this battle perusing mathematical proofs, so I decided to take an experimental approach. I went to Desmos and started chaining together ReLU activation functions to see if I could build something interesting-looking. After each attempt I tweaked my functions to make them look more like the target—sound familiar?" }, { "code": null, "e": 2822, "s": 2577, "text": "I chose x3+x2-x -1 as my target function. Using only ReLU max(0,x), I iteratively tried different combinations of ReLUs until I had an output that roughly resembled the target. Here are the results I achieved taking the weighted sum of 3 ReLUs." }, { "code": null, "e": 3124, "s": 2822, "text": "Not bad? The left chart shows the ReLU functions. The right chart shows the output of my model compared to the target. You can think of each ReLU function as a neuron. So combining 3 ReLU functions is like training a network of 3 hidden neurons. Here are the equations I used to generate these charts." }, { "code": null, "e": 3199, "s": 3124, "text": "Each neuron’s output equals ReLU wrapped around the weighted input wx + b." }, { "code": null, "e": 3441, "s": 3199, "text": "I found I could shift the ReLU function left and right by changing the bias and adjust the slope by changing the weight. I combined these 3 functions into a final sum of weighted inputs (Z) which is standard practice in most neural networks." }, { "code": null, "e": 3722, "s": 3441, "text": "The negative signs in Z represent the final layer’s weights which I set to -1 in order to “flip” the graph across the x-axis to match our concave target. After playing around a bit more I finally arrived at the following 7 equations that, together, roughly approximate x3+x2-x -1." }, { "code": null, "e": 3870, "s": 3722, "text": "So visually at least, it looks like it IS possible to model non-trivial functions with a single hidden layer and a handful of neurons. Pretty cool." }, { "code": null, "e": 4092, "s": 3870, "text": "Here is a diagram of a neural network initialized with my fake weights and biases. If you give this network a dataset that resembles x3+x2-x-1, it should be able approximate the correct output for inputs between -2 and 2." }, { "code": null, "e": 4566, "s": 4092, "text": "That last statement, approximate the correct output for any input between -2 and 2, is key. The Universal Approximation Theorem states that a neural network with 1 hidden layer can approximate any continuous function for inputs within a specific range. If the function jumps around or has large gaps, we won’t be able to approximate it. Additionally, if we train a network on inputs between 10 and 20, we can’t say for sure whether it will work on inputs between 40 and 50." }, { "code": null, "e": 5003, "s": 4566, "text": "I wanted to prove programmatically the weights I came up with actually work when plugged into a basic neural network with one hidden layer and 6 neurons. Instead of training the network to learn weights, however, I replaced its default weights and biases with my hand-picked values. The method feed_forward() below takes a vector of inputs (e.g. [-2,-1,0,1..]) and outputs a vector of predictions using my weights. Here’s what happened:" }, { "code": null, "e": 5152, "s": 5003, "text": "Look at that! I’m a genius. It’s exactly what we wanted. But what if our boss asks us to expand the range beyond -2 to 2? What if she wants -5 to 5?" }, { "code": null, "e": 5577, "s": 5152, "text": "Ah, not so great. But this actually supports our earlier conclusion: a neural network with one hidden layer can approximate any continuous function but only for inputs within a specific range. If you train a network on inputs between -2 and 2, like we did, then it will work well for inputs in a similar range, but you can’t expect it to generalize to other inputs without retraining the model or adding more hidden neurons." }, { "code": null, "e": 5991, "s": 5577, "text": "Now we know Brendan Fortuner can learn these weights on his own, but can a real-world neural network with 1 hidden layer and 6 neurons also learn these parameters or others that lead to the same result? Let’s use scikit-neuralnetwork to test this theory. We’ll design a network so it works for regression problems and configure it to use ReLU, Stochastic Gradient Descent, and Mean Squared Error — the usual gang." }, { "code": null, "e": 6002, "s": 5991, "text": "It worked!" }, { "code": null, "e": 6118, "s": 6002, "text": "Here are the weights Scikit learned. They’re clearly different from my own, but the order of magnitude is the same." }, { "code": null, "e": 6287, "s": 6118, "text": "hiddenLayerWeights = [ [-1.5272, -1.0567, -0.2828, 1.0399, 0.1243, 2.2446]]finalLayerWeights = [ [-2.2466], [ 1.0707], [-1.0643], [ 1.8229], [-0.4581], [ 2.9386]]" }, { "code": null, "e": 6538, "s": 6287, "text": "Perhaps if I rewrote this blog post 100,000 times I would have come to these parameters on my own, but for now we can only speculate. Maybe someday I’ll take the derivative of my up-votes and update my sentences in the direction that maximizes views." } ]
Introduction to Pandas apply, applymap and map | by B. Chen | Towards Data Science
In Data Processing, it is often necessary to perform operations (such as statistical calculations, splitting, or substituting value) on a certain row or column to obtain new data. Writing a for-loop to iterate through Pandas DataFrame and Series will do the job, but that doesn’t seem like a good idea. The for-loop tends to have more lines of code, less code readability, and slower performance. Fortunately, there are already great methods that are built into Pandas to help you accomplish the goals! In this article, we will see how to perform operations using apply() and applymap(), and how to substitute value using map(). First of all, you should be aware that DataFrame and Series will have some or all of these three methods, as follows: And the Pandas official API reference suggests that: apply() is used to apply a function along an axis of the DataFrame or on values of Series. applymap() is used to apply a function to a DataFrame elementwise. map() is used to substitute each value in a Series with another value. Before we diving into the details, let’s first create a DataFrame for demonstration. import pandas as pddf = pd.DataFrame({ 'A': [1,2,3,4], 'B': [10,20,30,40], 'C': [20,40,60,80] }, index=['Row 1', 'Row 2', 'Row 3', 'Row 4']) The Pandas apply() is used to apply a function along an axis of the DataFrame or on values of Series. Let’s begin with a simple example, to sum each row and save the result to a new column “D” # Let's call this "custom_sum" as "sum" is a built-in functiondef custom_sum(row): return row.sum()df['D'] = df.apply(custom_sum, axis=1) And here is the output Do you really understand what just happened? Let’s take a look df.apply(custom_sum, axis=1) The first parameter custom_sum is a function. The second parameter axis is to specify which axis the function is applied to. 0 for applying the function to each column and 1 for applying the function to each row. Let me explain this process in a more intuitive way. The second parameter axis = 1 tells Pandas to use the row. So, the custom_sum is applied to each row and returns a new Series with the output of each row as value. With the understanding of the sum of each row, the sum of each column is just to use axis = 0 instead df.loc['Row 5'] = df.apply(custom_sum, axis=0) So far, we have been talking about apply() on a DataFrame. Similarly, apply() can be used on the values of Series. For example, multiply the column “C” by 2 and save the result to a new column “D” def multiply_by_2(val): return val * 2df['D'] = df['C'].apply(multiply_by_2) Notice that df[‘C’] is used to select the column “C” and then call apply() with the only parameter multiply_by_2. We don’t need to specify axis anymore because Series is a one-dimensional array. The return value is a Series and get assigned to the new column D by df[‘D’]. You can also use lambda expression with Pandas apply() function. The lambda equivalent for the sum of each row of a DataFrame: df['D'] = df.apply(lambda x:x.sum(), axis=1) The lambda equivalent for the sum of each column of a DataFrame: df.loc['Row 5'] = df.apply(lambda x:x.sum(), axis=0) And the lambda equivalent for multiply by 2 on a Series: df['D'] = df['C'].apply(lambda x:x*2) result_type is a parameter in apply() set to 'expand', 'reduce', or 'broadcast' to get the desired type of result. In the above scenario if result_type is set to 'broadcast' then the output will be a DataFrame substituted by the custom_sum value. df.apply(custom_sum, axis=1, result_type='broadcast') The result is broadcasted to the original shape of the frame, the original index and columns are retained. To understand result_type as 'expand' and 'reduce', we will first create a function that returns a list. def cal_multi_col(row): return [row['A'] * 2, row['B'] * 3] Now apply this function across the DataFrame column with result_type as 'expand' df.apply(cal_multi_col, axis=1, result_type='expand') The output is a new DataFrame with column names 0 and 1. In order to append this to the existing DataFrame, the result has to be kept in a variable so the column names can be accessed by res.columns. res = df.apply(cal_multi_col, axis=1, result_type='expand')df[res.columns] = res And the output is: Next, apply the function across the DataFrame column with result_type as 'reduce' . result_type='reduce' is just opposite of 'expand' and returns a Series if possible rather than expanding list-like results. df['New'] = df.apply(cal_multi_col, axis=1, result_type='reduce') applymap() is only available in DataFrame and used for element-wise operation across the whole DataFrame. It has been optimized and some cases work much faster than apply() , but it’s good to compare it with apply() before going for any heavier operation. For example: to output a DataFrame with number squared df.applymap(np.square) map() is only available in Series and used for substituting each value in a Series with another value. To understand how the map() works, we first create a Series. >>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])>>> s0 cat1 dog2 NaN3 rabbitdtype: object map() accepts a dict or a Series. Values that are not found in the dict are converted to NaN, unless the dict has a default value (e.g. defaultdict): >>> s.map({'cat': 'kitten', 'dog': 'puppy'})0 kitten1 puppy2 NaN3 NaNdtype: object It also accepts a function: >>> s.map('I am a {}'.format)0 I am a cat1 I am a dog2 I am a nan3 I am a rabbitdtype: object To avoid applying the function to missing values (and keep them as NaN) na_action='ignore' can be used: >>> s.map('I am a {}'.format, na_action='ignore')0 I am a cat1 I am a dog2 NaN3 I am a rabbitdtype: object Finally, here is a summary: For DataFrame: apply(): It is used when you want to apply a function along the row or column. axis = 0 for column and axis = 1 for row. applymap(): It is used for element-wise operation across the whole DataFrame. For Series: apply(): It is used when you want to apply a function on the values of Series. map(): It is used to substitute each value with another value. Pandas concat() tricks you should know How to do a Custom Sort on Pandas DataFrame When to use Pandas transform() function Using Pandas method chaining to improve code readability Working with datetime in Pandas DataFrame Working with missing values in Pandas Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More can be found from my Github That’s about it. Thanks for reading.
[ { "code": null, "e": 444, "s": 47, "text": "In Data Processing, it is often necessary to perform operations (such as statistical calculations, splitting, or substituting value) on a certain row or column to obtain new data. Writing a for-loop to iterate through Pandas DataFrame and Series will do the job, but that doesn’t seem like a good idea. The for-loop tends to have more lines of code, less code readability, and slower performance." }, { "code": null, "e": 676, "s": 444, "text": "Fortunately, there are already great methods that are built into Pandas to help you accomplish the goals! In this article, we will see how to perform operations using apply() and applymap(), and how to substitute value using map()." }, { "code": null, "e": 794, "s": 676, "text": "First of all, you should be aware that DataFrame and Series will have some or all of these three methods, as follows:" }, { "code": null, "e": 847, "s": 794, "text": "And the Pandas official API reference suggests that:" }, { "code": null, "e": 938, "s": 847, "text": "apply() is used to apply a function along an axis of the DataFrame or on values of Series." }, { "code": null, "e": 1005, "s": 938, "text": "applymap() is used to apply a function to a DataFrame elementwise." }, { "code": null, "e": 1076, "s": 1005, "text": "map() is used to substitute each value in a Series with another value." }, { "code": null, "e": 1161, "s": 1076, "text": "Before we diving into the details, let’s first create a DataFrame for demonstration." }, { "code": null, "e": 1374, "s": 1161, "text": "import pandas as pddf = pd.DataFrame({ 'A': [1,2,3,4], 'B': [10,20,30,40], 'C': [20,40,60,80] }, index=['Row 1', 'Row 2', 'Row 3', 'Row 4'])" }, { "code": null, "e": 1476, "s": 1374, "text": "The Pandas apply() is used to apply a function along an axis of the DataFrame or on values of Series." }, { "code": null, "e": 1567, "s": 1476, "text": "Let’s begin with a simple example, to sum each row and save the result to a new column “D”" }, { "code": null, "e": 1708, "s": 1567, "text": "# Let's call this \"custom_sum\" as \"sum\" is a built-in functiondef custom_sum(row): return row.sum()df['D'] = df.apply(custom_sum, axis=1)" }, { "code": null, "e": 1731, "s": 1708, "text": "And here is the output" }, { "code": null, "e": 1776, "s": 1731, "text": "Do you really understand what just happened?" }, { "code": null, "e": 1823, "s": 1776, "text": "Let’s take a look df.apply(custom_sum, axis=1)" }, { "code": null, "e": 1869, "s": 1823, "text": "The first parameter custom_sum is a function." }, { "code": null, "e": 2036, "s": 1869, "text": "The second parameter axis is to specify which axis the function is applied to. 0 for applying the function to each column and 1 for applying the function to each row." }, { "code": null, "e": 2253, "s": 2036, "text": "Let me explain this process in a more intuitive way. The second parameter axis = 1 tells Pandas to use the row. So, the custom_sum is applied to each row and returns a new Series with the output of each row as value." }, { "code": null, "e": 2355, "s": 2253, "text": "With the understanding of the sum of each row, the sum of each column is just to use axis = 0 instead" }, { "code": null, "e": 2402, "s": 2355, "text": "df.loc['Row 5'] = df.apply(custom_sum, axis=0)" }, { "code": null, "e": 2599, "s": 2402, "text": "So far, we have been talking about apply() on a DataFrame. Similarly, apply() can be used on the values of Series. For example, multiply the column “C” by 2 and save the result to a new column “D”" }, { "code": null, "e": 2679, "s": 2599, "text": "def multiply_by_2(val): return val * 2df['D'] = df['C'].apply(multiply_by_2)" }, { "code": null, "e": 2952, "s": 2679, "text": "Notice that df[‘C’] is used to select the column “C” and then call apply() with the only parameter multiply_by_2. We don’t need to specify axis anymore because Series is a one-dimensional array. The return value is a Series and get assigned to the new column D by df[‘D’]." }, { "code": null, "e": 3017, "s": 2952, "text": "You can also use lambda expression with Pandas apply() function." }, { "code": null, "e": 3079, "s": 3017, "text": "The lambda equivalent for the sum of each row of a DataFrame:" }, { "code": null, "e": 3124, "s": 3079, "text": "df['D'] = df.apply(lambda x:x.sum(), axis=1)" }, { "code": null, "e": 3189, "s": 3124, "text": "The lambda equivalent for the sum of each column of a DataFrame:" }, { "code": null, "e": 3242, "s": 3189, "text": "df.loc['Row 5'] = df.apply(lambda x:x.sum(), axis=0)" }, { "code": null, "e": 3299, "s": 3242, "text": "And the lambda equivalent for multiply by 2 on a Series:" }, { "code": null, "e": 3337, "s": 3299, "text": "df['D'] = df['C'].apply(lambda x:x*2)" }, { "code": null, "e": 3452, "s": 3337, "text": "result_type is a parameter in apply() set to 'expand', 'reduce', or 'broadcast' to get the desired type of result." }, { "code": null, "e": 3584, "s": 3452, "text": "In the above scenario if result_type is set to 'broadcast' then the output will be a DataFrame substituted by the custom_sum value." }, { "code": null, "e": 3638, "s": 3584, "text": "df.apply(custom_sum, axis=1, result_type='broadcast')" }, { "code": null, "e": 3745, "s": 3638, "text": "The result is broadcasted to the original shape of the frame, the original index and columns are retained." }, { "code": null, "e": 3850, "s": 3745, "text": "To understand result_type as 'expand' and 'reduce', we will first create a function that returns a list." }, { "code": null, "e": 3913, "s": 3850, "text": "def cal_multi_col(row): return [row['A'] * 2, row['B'] * 3]" }, { "code": null, "e": 3994, "s": 3913, "text": "Now apply this function across the DataFrame column with result_type as 'expand'" }, { "code": null, "e": 4048, "s": 3994, "text": "df.apply(cal_multi_col, axis=1, result_type='expand')" }, { "code": null, "e": 4105, "s": 4048, "text": "The output is a new DataFrame with column names 0 and 1." }, { "code": null, "e": 4248, "s": 4105, "text": "In order to append this to the existing DataFrame, the result has to be kept in a variable so the column names can be accessed by res.columns." }, { "code": null, "e": 4329, "s": 4248, "text": "res = df.apply(cal_multi_col, axis=1, result_type='expand')df[res.columns] = res" }, { "code": null, "e": 4348, "s": 4329, "text": "And the output is:" }, { "code": null, "e": 4556, "s": 4348, "text": "Next, apply the function across the DataFrame column with result_type as 'reduce' . result_type='reduce' is just opposite of 'expand' and returns a Series if possible rather than expanding list-like results." }, { "code": null, "e": 4622, "s": 4556, "text": "df['New'] = df.apply(cal_multi_col, axis=1, result_type='reduce')" }, { "code": null, "e": 4878, "s": 4622, "text": "applymap() is only available in DataFrame and used for element-wise operation across the whole DataFrame. It has been optimized and some cases work much faster than apply() , but it’s good to compare it with apply() before going for any heavier operation." }, { "code": null, "e": 4933, "s": 4878, "text": "For example: to output a DataFrame with number squared" }, { "code": null, "e": 4956, "s": 4933, "text": "df.applymap(np.square)" }, { "code": null, "e": 5120, "s": 4956, "text": "map() is only available in Series and used for substituting each value in a Series with another value. To understand how the map() works, we first create a Series." }, { "code": null, "e": 5230, "s": 5120, "text": ">>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])>>> s0 cat1 dog2 NaN3 rabbitdtype: object" }, { "code": null, "e": 5380, "s": 5230, "text": "map() accepts a dict or a Series. Values that are not found in the dict are converted to NaN, unless the dict has a default value (e.g. defaultdict):" }, { "code": null, "e": 5478, "s": 5380, "text": ">>> s.map({'cat': 'kitten', 'dog': 'puppy'})0 kitten1 puppy2 NaN3 NaNdtype: object" }, { "code": null, "e": 5506, "s": 5478, "text": "It also accepts a function:" }, { "code": null, "e": 5621, "s": 5506, "text": ">>> s.map('I am a {}'.format)0 I am a cat1 I am a dog2 I am a nan3 I am a rabbitdtype: object" }, { "code": null, "e": 5725, "s": 5621, "text": "To avoid applying the function to missing values (and keep them as NaN) na_action='ignore' can be used:" }, { "code": null, "e": 5852, "s": 5725, "text": ">>> s.map('I am a {}'.format, na_action='ignore')0 I am a cat1 I am a dog2 NaN3 I am a rabbitdtype: object" }, { "code": null, "e": 5880, "s": 5852, "text": "Finally, here is a summary:" }, { "code": null, "e": 5895, "s": 5880, "text": "For DataFrame:" }, { "code": null, "e": 6016, "s": 5895, "text": "apply(): It is used when you want to apply a function along the row or column. axis = 0 for column and axis = 1 for row." }, { "code": null, "e": 6094, "s": 6016, "text": "applymap(): It is used for element-wise operation across the whole DataFrame." }, { "code": null, "e": 6106, "s": 6094, "text": "For Series:" }, { "code": null, "e": 6185, "s": 6106, "text": "apply(): It is used when you want to apply a function on the values of Series." }, { "code": null, "e": 6248, "s": 6185, "text": "map(): It is used to substitute each value with another value." }, { "code": null, "e": 6287, "s": 6248, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 6331, "s": 6287, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 6371, "s": 6331, "text": "When to use Pandas transform() function" }, { "code": null, "e": 6428, "s": 6371, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 6470, "s": 6428, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 6508, "s": 6470, "text": "Working with missing values in Pandas" }, { "code": null, "e": 6549, "s": 6508, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 6619, "s": 6549, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" }, { "code": null, "e": 6652, "s": 6619, "text": "More can be found from my Github" } ]
Riot API: a machine learning and data analysis application | by Marco Sanguineti | Towards Data Science
A simple python based tutorial for data analysis and machine learning for personal improvement through Riot API. If you are reading this article you might be a fan of League of Legends, a popular online game of the genre MOBA (multiplayer online battle arena). Or maybe you’re interested in the possible applications of machine learning and data analysis in the world of online gaming. This game is developed and published by Riot Games. With millions of players around the world, this game boasts a wide audience of amateurs and professional players. It takes advantage of the game’s constant evolution and statistical complexity. The basic principles of the game are (very) simple. With thousands of variables and possible scenarios, each game is different. Given the plenty of data, the extraction of important ones can allow you to get interesting information about your style of play. You can extract information useful to improve your game-style or predict what will be your future performance. Many sites such as op.gg provide a huge amount of data, analysis and graphics. That’s great, but in case you want to develop custom or more complex models you’ll need some manual work. The Riot Games API is a REST API that provides useful data to the developers for building your own applications or websites. I recommend you to read the documentation before start programming to avoid violating the legal terms of service. You might also avoid problems with the data request rate. In the next sections we will see how to: Extract useful data from the Riot API Process data to obtain useful information Create simple predictive models Let’s start by installing and importing some basic libraries. In case you are working with a Google Colaboratory notebook, you will not have any problems, otherwise, you will need to install the individual libraries according to your operating system. !pip3 install riotwatcher!pip install -q seaborn!pip install -q git+https://github.com/tensorflow/docsimport numpy as npimport matplotlib.pyplot as pltimport pathlibimport pandas as pdimport seaborn as snsimport tensorflow as tfimport timefrom tensorflow import kerasfrom tensorflow.keras import layersimport tensorflow_docs as tfdocsimport tensorflow_docs.plotsimport tensorflow_docs.modelingfrom riotwatcher import LolWatcher, ApiError For data extraction we use RiotWatcher, is a thin wrapper on top of the Riot Games API for League of Legends. It is necessary to use the Riot API key, to be generated again every 24 hours. Remember that this key is personal and should not be shared. Let’s start by extracting some information about a player (or summoner): let’s get the rank of the desired player lol_watcher = LolWatcher('%YOUR RIOT API KEY%')my_region = 'euw1'me = lol_watcher.summoner.by_name(my_region, '%YOUR SUMMONER NAME%')my_ranked_stats = lol_watcher.league.by_summoner(my_region, me['id'])print(my_ranked_stats) Let’s extract an updated version of champions, objects, summoner spells and any other desired properties and therefore our match history: versions = lol_watcher.data_dragon.versions_for_region(my_region)champions_version = versions['n']['champion']summoner_spells_version=versions['n']['summoner']items_version=versions['n']['item']( ... )current_champ_list = lol_watcher.data_dragon.champions(champions_version)( ... )my_matches = lol_watcher.match.matchlist_by_account(my_region, me['accountId']) We have at our disposal a huge amount of data, the importance of which is highly subjective. More features will lead to a more complex, but more accurate model. To obtain a really accurate analysis it is necessary to have information on as many games as possible to better fit in our models and make the results more plausible. Let’s extract data from the last 100 games and define a series of Pandas data-frames containing all the main information. n_games = 100Games = {}Game_duration=np.zeros(n_games)Damage = np.zeros(n_games)(...)j=0cont=0while cont<n_games: try: last_match = my_matches['matches'][cont] match_detail = lol_watcher.match.by_id(my_region, last_match['gameId']) participants = [] for row in match_detail['participants']: participants_row = {} participants_row['champion'] = row['championId'] participants_row['win'] = row['stats']['win'] participants_row['assists'] = row['stats']['assists'] ( ... ) participants.append(participants_row) Games[j] = pd.DataFrame(participants) champ_dict = {} for key in static_champ_list['data']: row = static_champ_list['data'][key] champ_dict[row['key']] = row['id'] summoners_dict = {} for key in static_summoners_list['data']: row = static_summoners_list['data'][key] summoners_dict[row['key']] = row['id'] Summoner_name = [] for row in match_detail['participantIdentities']: Summoner_name_row = {} Summoner_name_row=row['player']['summonerName'] Summoner_name.append(Summoner_name_row) i=0for row in participants: row['championName'] = champ_dict[str(row['champion'])] row['Summoner_name']=Summoner_name[i] row['Summoner Spell 1']=summoners_dict[str(row['spell1'])] row['Summoner Spell 2']=summoners_dict[str(row['spell2'])] i+=1 Games[j]= pd.DataFrame(participants) for index, row in Games[j].iterrows(): if row['Summoner_name']=='%YOUR SUMMONER NAME%': Damage[j]=row['totalDamageDealt'] Gold[j]=row['goldEarned'] ( ... ) time.sleep(10) j+=1 cont+=1 except: cont+=1 At this point we have extracted all the data we are interested in: let’s proceed with the data analysis. Warning: a 10-second pause has been inserted in each loop to not exceed the maximum number of hourly requests granted by Riot API. At this point we have at our disposal a large amount of data, apparently not significant: to obtain useful information you need to combine your interests in terms of “game properties” with modern algorithms of data analysis and machine learning, able to give effective answers. The data can give a lot of answers about the performance in-game, with the possibility to discover strengths/weaknesses or even predict the probability of winning based on your live game statistics! In the following paragraphs are presented as an example some simple analysis conducted on a reduced set of parameters to facilitate understanding, but you can easily generate more complex and interesting models. We can start by preparing a database that can be effectively used for data analysis: let’s see some simple features of our games: dataset={}dataset['Total Damage']=Damagedataset['Gold']=Gold( ... )dataset['Victory']=Victory #Boolean Whether our goal is to solve a regression problem (continuous output system) or a classification (discrete output system), it is necessary to divide the starting dataset into two separate datasets: Training set: this dataset is used for the training of the model (i.e. Neural Network). E’ important to have good performances of forecast on the training set, but at the same time, it is necessary to avoid the phenomenon of overfitting. Test set: set used for model validation during the training iterating process train_dataset_raw = dataset.sample(frac=0.8,random_state=0)test_dataset_raw = dataset.drop(train_dataset_raw.index)train_dataset=train_dataset_raw.iloc[:,range(0,4)]test_dataset=test_dataset_raw.iloc[:,range(0,4)]train_labels=train_dataset_raw.iloc[:,4]test_labels=test_dataset_raw.iloc[:,4] Pair plots A Pairplot plot pairwise relationships in a dataset. The Pairplot function creates a grid of Axes such that each variable in data will be shared in the y-axis across a single row and in the x-axis across a single column. sns.pairplot(train_dataset_raw, diag_kind="kde") Why analyze such a graph? Because it allows you to have quick qualitative information about the respective relationship between the chosen data. For example, we might note that an increase in total gold owned leads to greater total damage, a relationship between the number of wins and game parameters, as well as a probability distribution of the individual magnitudes in their domain. Cross-correlation matrix For a more qualitative analysis of the correlation between data, we can refer to the correlation matrix. “There are several methods for calculating a correlation value. The most popular one is the Pearson Correlation Coefficient. Nevertheless, it should be noticed that it measures only a linear relationship between two variables. In other words, it may not be able to reveal a nonlinear relationship. The value of Pearson correlation ranges from -1 to +1, where +/-1 describes a perfect positive/negative correlation and 0 means no correlation. The correlation matrix is a symmetrical matrix with all diagonal elements equal to +1” corr = dataset.corr()mask = np.triu(np.ones_like(corr, dtype=bool))f, ax = plt.subplots(figsize=(11, 9))cmap = sns.diverging_palette(230, 20, as_cmap=True)sb.heatmap(corr, mask=mask, cmap=cmap, vmax=0.9, center=0, vmin=-0.2,square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot = True)plt.show() Who knows the problem could realize that information like, for example, an increase of the damage with the possessed gold or the inverse trend between dead and Victory are correct, even if apparently trivial. However, the validation of these models with simple statements can lead to a more accurate application to more complex datasets. Estimation of the probability of victory: a simple classification problem First of all, let’s normalize the data: def norm(x):return (x - train_stats['mean']) / train_stats['std']normed_train_data = norm(train_dataset)normed_test_data = norm(test_dataset) Model generation is facilitated by the powerful tools provided by the Keras and TensorFlow libraries. Let’s define a simple sequential model for our classification, with the following properties: Model: sequential Input Layer: 4 nodes layer 2 hidden layers: activation=’relu’ ; nodes = 16/32 2 Dropout layers: 0.2 Output layer: activation = ‘sigmoid’; nodes = 1; Model properties: loss=’binary_crossentropy’, optimizer=’adam’,metrics=[‘accuracy’] dumbo=(normed_test_data,test_labels)model = Sequential()epochs=700model.add(Dense(16, input_dim=4, activation='relu'))layers.Dropout(0.2)model.add(Dense(32, activation='relu'))layers.Dropout(0.2)model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='adam',metrics ['accuracy'])history = model.fit(normed_train_data, train_labels, epochs=epochs,validation_data=dumbo) Then we evaluate the quality of the model prediction on our entire test dataset: Qualitatively we can notice very good performances both on the training and on the validation set (associated with the simplicity of the studied case). Quantitively we get: Test loss: 0.4501 — Test accuracy: 0.9583 Train loss: 0.0891 —Train accuracy: 0.9688 Graphically, we get: We have an accuracy of 97% to correctly predict the outcome of the game based on the chosen game parameters! Obviously, the quality of the prediction will depend on the features chosen, the quality of the model and so on. Conclusions We have seen a simple application of riot API and we have developed a series of tools to analyze our skills in the game. We also predicted our future performance! This is a starting point to develop codes, applications etc. to take advantage of the huge amount of data generated in a League of Legends game. Thanks for reading
[ { "code": null, "e": 285, "s": 172, "text": "A simple python based tutorial for data analysis and machine learning for personal improvement through Riot API." }, { "code": null, "e": 610, "s": 285, "text": "If you are reading this article you might be a fan of League of Legends, a popular online game of the genre MOBA (multiplayer online battle arena). Or maybe you’re interested in the possible applications of machine learning and data analysis in the world of online gaming. This game is developed and published by Riot Games." }, { "code": null, "e": 932, "s": 610, "text": "With millions of players around the world, this game boasts a wide audience of amateurs and professional players. It takes advantage of the game’s constant evolution and statistical complexity. The basic principles of the game are (very) simple. With thousands of variables and possible scenarios, each game is different." }, { "code": null, "e": 1173, "s": 932, "text": "Given the plenty of data, the extraction of important ones can allow you to get interesting information about your style of play. You can extract information useful to improve your game-style or predict what will be your future performance." }, { "code": null, "e": 1358, "s": 1173, "text": "Many sites such as op.gg provide a huge amount of data, analysis and graphics. That’s great, but in case you want to develop custom or more complex models you’ll need some manual work." }, { "code": null, "e": 1483, "s": 1358, "text": "The Riot Games API is a REST API that provides useful data to the developers for building your own applications or websites." }, { "code": null, "e": 1655, "s": 1483, "text": "I recommend you to read the documentation before start programming to avoid violating the legal terms of service. You might also avoid problems with the data request rate." }, { "code": null, "e": 1696, "s": 1655, "text": "In the next sections we will see how to:" }, { "code": null, "e": 1734, "s": 1696, "text": "Extract useful data from the Riot API" }, { "code": null, "e": 1776, "s": 1734, "text": "Process data to obtain useful information" }, { "code": null, "e": 1808, "s": 1776, "text": "Create simple predictive models" }, { "code": null, "e": 2060, "s": 1808, "text": "Let’s start by installing and importing some basic libraries. In case you are working with a Google Colaboratory notebook, you will not have any problems, otherwise, you will need to install the individual libraries according to your operating system." }, { "code": null, "e": 2498, "s": 2060, "text": "!pip3 install riotwatcher!pip install -q seaborn!pip install -q git+https://github.com/tensorflow/docsimport numpy as npimport matplotlib.pyplot as pltimport pathlibimport pandas as pdimport seaborn as snsimport tensorflow as tfimport timefrom tensorflow import kerasfrom tensorflow.keras import layersimport tensorflow_docs as tfdocsimport tensorflow_docs.plotsimport tensorflow_docs.modelingfrom riotwatcher import LolWatcher, ApiError" }, { "code": null, "e": 2862, "s": 2498, "text": "For data extraction we use RiotWatcher, is a thin wrapper on top of the Riot Games API for League of Legends. It is necessary to use the Riot API key, to be generated again every 24 hours. Remember that this key is personal and should not be shared. Let’s start by extracting some information about a player (or summoner): let’s get the rank of the desired player" }, { "code": null, "e": 3087, "s": 2862, "text": "lol_watcher = LolWatcher('%YOUR RIOT API KEY%')my_region = 'euw1'me = lol_watcher.summoner.by_name(my_region, '%YOUR SUMMONER NAME%')my_ranked_stats = lol_watcher.league.by_summoner(my_region, me['id'])print(my_ranked_stats)" }, { "code": null, "e": 3225, "s": 3087, "text": "Let’s extract an updated version of champions, objects, summoner spells and any other desired properties and therefore our match history:" }, { "code": null, "e": 3586, "s": 3225, "text": "versions = lol_watcher.data_dragon.versions_for_region(my_region)champions_version = versions['n']['champion']summoner_spells_version=versions['n']['summoner']items_version=versions['n']['item']( ... )current_champ_list = lol_watcher.data_dragon.champions(champions_version)( ... )my_matches = lol_watcher.match.matchlist_by_account(my_region, me['accountId'])" }, { "code": null, "e": 4036, "s": 3586, "text": "We have at our disposal a huge amount of data, the importance of which is highly subjective. More features will lead to a more complex, but more accurate model. To obtain a really accurate analysis it is necessary to have information on as many games as possible to better fit in our models and make the results more plausible. Let’s extract data from the last 100 games and define a series of Pandas data-frames containing all the main information." }, { "code": null, "e": 5591, "s": 4036, "text": "n_games = 100Games = {}Game_duration=np.zeros(n_games)Damage = np.zeros(n_games)(...)j=0cont=0while cont<n_games: try: last_match = my_matches['matches'][cont] match_detail = lol_watcher.match.by_id(my_region, last_match['gameId']) participants = [] for row in match_detail['participants']: participants_row = {} participants_row['champion'] = row['championId'] participants_row['win'] = row['stats']['win'] participants_row['assists'] = row['stats']['assists'] ( ... ) participants.append(participants_row) Games[j] = pd.DataFrame(participants) champ_dict = {} for key in static_champ_list['data']: row = static_champ_list['data'][key] champ_dict[row['key']] = row['id'] summoners_dict = {} for key in static_summoners_list['data']: row = static_summoners_list['data'][key] summoners_dict[row['key']] = row['id'] Summoner_name = [] for row in match_detail['participantIdentities']: Summoner_name_row = {} Summoner_name_row=row['player']['summonerName'] Summoner_name.append(Summoner_name_row) i=0for row in participants: row['championName'] = champ_dict[str(row['champion'])] row['Summoner_name']=Summoner_name[i] row['Summoner Spell 1']=summoners_dict[str(row['spell1'])] row['Summoner Spell 2']=summoners_dict[str(row['spell2'])] i+=1 Games[j]= pd.DataFrame(participants) for index, row in Games[j].iterrows(): if row['Summoner_name']=='%YOUR SUMMONER NAME%': Damage[j]=row['totalDamageDealt'] Gold[j]=row['goldEarned'] ( ... ) time.sleep(10) j+=1 cont+=1 except: cont+=1" }, { "code": null, "e": 5827, "s": 5591, "text": "At this point we have extracted all the data we are interested in: let’s proceed with the data analysis. Warning: a 10-second pause has been inserted in each loop to not exceed the maximum number of hourly requests granted by Riot API." }, { "code": null, "e": 6646, "s": 5827, "text": "At this point we have at our disposal a large amount of data, apparently not significant: to obtain useful information you need to combine your interests in terms of “game properties” with modern algorithms of data analysis and machine learning, able to give effective answers. The data can give a lot of answers about the performance in-game, with the possibility to discover strengths/weaknesses or even predict the probability of winning based on your live game statistics! In the following paragraphs are presented as an example some simple analysis conducted on a reduced set of parameters to facilitate understanding, but you can easily generate more complex and interesting models. We can start by preparing a database that can be effectively used for data analysis: let’s see some simple features of our games:" }, { "code": null, "e": 6749, "s": 6646, "text": "dataset={}dataset['Total Damage']=Damagedataset['Gold']=Gold( ... )dataset['Victory']=Victory #Boolean" }, { "code": null, "e": 6947, "s": 6749, "text": "Whether our goal is to solve a regression problem (continuous output system) or a classification (discrete output system), it is necessary to divide the starting dataset into two separate datasets:" }, { "code": null, "e": 7185, "s": 6947, "text": "Training set: this dataset is used for the training of the model (i.e. Neural Network). E’ important to have good performances of forecast on the training set, but at the same time, it is necessary to avoid the phenomenon of overfitting." }, { "code": null, "e": 7263, "s": 7185, "text": "Test set: set used for model validation during the training iterating process" }, { "code": null, "e": 7555, "s": 7263, "text": "train_dataset_raw = dataset.sample(frac=0.8,random_state=0)test_dataset_raw = dataset.drop(train_dataset_raw.index)train_dataset=train_dataset_raw.iloc[:,range(0,4)]test_dataset=test_dataset_raw.iloc[:,range(0,4)]train_labels=train_dataset_raw.iloc[:,4]test_labels=test_dataset_raw.iloc[:,4]" }, { "code": null, "e": 7566, "s": 7555, "text": "Pair plots" }, { "code": null, "e": 7787, "s": 7566, "text": "A Pairplot plot pairwise relationships in a dataset. The Pairplot function creates a grid of Axes such that each variable in data will be shared in the y-axis across a single row and in the x-axis across a single column." }, { "code": null, "e": 7836, "s": 7787, "text": "sns.pairplot(train_dataset_raw, diag_kind=\"kde\")" }, { "code": null, "e": 8223, "s": 7836, "text": "Why analyze such a graph? Because it allows you to have quick qualitative information about the respective relationship between the chosen data. For example, we might note that an increase in total gold owned leads to greater total damage, a relationship between the number of wins and game parameters, as well as a probability distribution of the individual magnitudes in their domain." }, { "code": null, "e": 8248, "s": 8223, "text": "Cross-correlation matrix" }, { "code": null, "e": 8882, "s": 8248, "text": "For a more qualitative analysis of the correlation between data, we can refer to the correlation matrix. “There are several methods for calculating a correlation value. The most popular one is the Pearson Correlation Coefficient. Nevertheless, it should be noticed that it measures only a linear relationship between two variables. In other words, it may not be able to reveal a nonlinear relationship. The value of Pearson correlation ranges from -1 to +1, where +/-1 describes a perfect positive/negative correlation and 0 means no correlation. The correlation matrix is a symmetrical matrix with all diagonal elements equal to +1”" }, { "code": null, "e": 9183, "s": 8882, "text": "corr = dataset.corr()mask = np.triu(np.ones_like(corr, dtype=bool))f, ax = plt.subplots(figsize=(11, 9))cmap = sns.diverging_palette(230, 20, as_cmap=True)sb.heatmap(corr, mask=mask, cmap=cmap, vmax=0.9, center=0, vmin=-0.2,square=True, linewidths=.5, cbar_kws={\"shrink\": .5}, annot = True)plt.show()" }, { "code": null, "e": 9521, "s": 9183, "text": "Who knows the problem could realize that information like, for example, an increase of the damage with the possessed gold or the inverse trend between dead and Victory are correct, even if apparently trivial. However, the validation of these models with simple statements can lead to a more accurate application to more complex datasets." }, { "code": null, "e": 9595, "s": 9521, "text": "Estimation of the probability of victory: a simple classification problem" }, { "code": null, "e": 9635, "s": 9595, "text": "First of all, let’s normalize the data:" }, { "code": null, "e": 9777, "s": 9635, "text": "def norm(x):return (x - train_stats['mean']) / train_stats['std']normed_train_data = norm(train_dataset)normed_test_data = norm(test_dataset)" }, { "code": null, "e": 9973, "s": 9777, "text": "Model generation is facilitated by the powerful tools provided by the Keras and TensorFlow libraries. Let’s define a simple sequential model for our classification, with the following properties:" }, { "code": null, "e": 9991, "s": 9973, "text": "Model: sequential" }, { "code": null, "e": 10018, "s": 9991, "text": "Input Layer: 4 nodes layer" }, { "code": null, "e": 10069, "s": 10018, "text": "2 hidden layers: activation=’relu’ ; nodes = 16/32" }, { "code": null, "e": 10091, "s": 10069, "text": "2 Dropout layers: 0.2" }, { "code": null, "e": 10140, "s": 10091, "text": "Output layer: activation = ‘sigmoid’; nodes = 1;" }, { "code": null, "e": 10224, "s": 10140, "text": "Model properties: loss=’binary_crossentropy’, optimizer=’adam’,metrics=[‘accuracy’]" }, { "code": null, "e": 10630, "s": 10224, "text": "dumbo=(normed_test_data,test_labels)model = Sequential()epochs=700model.add(Dense(16, input_dim=4, activation='relu'))layers.Dropout(0.2)model.add(Dense(32, activation='relu'))layers.Dropout(0.2)model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='adam',metrics ['accuracy'])history = model.fit(normed_train_data, train_labels, epochs=epochs,validation_data=dumbo)" }, { "code": null, "e": 10711, "s": 10630, "text": "Then we evaluate the quality of the model prediction on our entire test dataset:" }, { "code": null, "e": 10884, "s": 10711, "text": "Qualitatively we can notice very good performances both on the training and on the validation set (associated with the simplicity of the studied case). Quantitively we get:" }, { "code": null, "e": 10926, "s": 10884, "text": "Test loss: 0.4501 — Test accuracy: 0.9583" }, { "code": null, "e": 10969, "s": 10926, "text": "Train loss: 0.0891 —Train accuracy: 0.9688" }, { "code": null, "e": 10990, "s": 10969, "text": "Graphically, we get:" }, { "code": null, "e": 11212, "s": 10990, "text": "We have an accuracy of 97% to correctly predict the outcome of the game based on the chosen game parameters! Obviously, the quality of the prediction will depend on the features chosen, the quality of the model and so on." }, { "code": null, "e": 11224, "s": 11212, "text": "Conclusions" }, { "code": null, "e": 11532, "s": 11224, "text": "We have seen a simple application of riot API and we have developed a series of tools to analyze our skills in the game. We also predicted our future performance! This is a starting point to develop codes, applications etc. to take advantage of the huge amount of data generated in a League of Legends game." } ]
Debugging Neural Networks with PyTorch and W&B | by Ayush Thakur | Towards Data Science
In this post, we’ll see what makes a neural network under perform and ways we can debug this by visualizing the gradients and other parameters associated with model training. We’ll also discuss the problem of vanishing and exploding gradients and methods to overcome them. Finally, we’ll see why proper weight initialization is useful, how to do it correctly, and dive into how regularization methods like dropout and batch normalization affect model performance. As shown in this piece, neural network bugs are really hard to catch because: 1. The code never crashes, raises an exception, or even slows down.2. The network still trains and the loss will still go down.3. The values converge after a few hours, but to really poor results I highly recommend reading A Recipe for Training Neural Networks by Andrej Karparthy if you’d like to dive deeper into this topic. There is no decisive set of steps to be followed while debugging neural networks. But here is a list of concepts that, if implemented properly, can help debug your neural networks. There is no decisive set of steps to be followed while debugging neural networks. But here is a list of concepts that, if implemented properly, can help debug your neural networks. 1. Decisions about data: We must understand the nuances of data — the type of data, the way it is stored, class balances for targets and features, value scale consistency of data, etc. 2. Data Preprocessing: We must think about data preprocessing and try to incorporate domain knowledge into it. There are usually two occasions when data preprocessing is used: Data cleaning: The objective task can be achieved easily if some parts of the data, known as artifacts, is removed. Data augmentation: When we have limited training data, we transform each data sample in numerous ways to be used for training the model (example scaling, shifting, rotating images).This post is not focusing on the issues caused by bad data preprocessing. 3. Overfitting on a small dataset: If we have a small dataset of 50–60 data samples, the model will overfit quickly i.e., the loss will be zero in 2–5 epochs. To overcome this, be sure to remove any regularization from the model. If your model is not overfitting, it might be because might be your model is not architected correctly or the choice of your loss is incorrect. Maybe your output layer is activated with sigmoid while you were trying to do multi-class classification. These errors can be easy to miss error. Check out my notebook demonstrating this here. So how can one avoid such errors? Keep reading. 1. Start with a small architecture: Using fancy regularizers and schedulers may be overkill. In case of an error, it’s easier to debug a small network. Common errors include forgetting to pass tensors from one layer to another, have insane input to output neurons ratio, etc. 2. Pretrained model(weights): If your model architecture is built on top of a standard backbone like VGG, Resnet, Inception, etc you can use pre-trained weights on a standard dataset — if you can, find one on the dataset that you are working with. One interesting recent paper, Transfusion: Understanding Transfer Learning for Medical Imaging shows that using even a few early layers from a pre-trained ImageNet model can improve both the speed of training and final accuracy of medical imaging models. Therefore, you should use a general-purpose pre-trained model, even if it is not in the domain of the problem you’re solving. The amount of improvement from an ImageNet pre-trained model when applied to medical imaging is not that great. Thus there isn’t much guarantee on a head start either. For more, I recommend reading this amazing blog post by Jeremy Howard. 1. Choosing the right loss function: First, make sure that you are using the right loss function for the given task. For a multi-class classifier, a binary loss function will not help improve the accuracy, so categorical cross-entropy is the right choice. 2. Determine theoretical loss: If your model started by guessing randomly (i.e. no pretrained model), check to see if the initial loss is close to your expected loss. If you’re using cross-entropy loss, check to see that your initial loss is approximately -log(1/num_classes. You can get some more suggestions here. 3. Learning Rate: This parameter determines the step size at each iteration while moving toward the minimum of a loss function. You can tweak the learning rate according to how steep or smooth your loss function is. But this can be a time and resource consuming step. Can you find the most optimal learning rate, automatically? Leslie N. Smith presented a very smart and simple approach to systematically find a learning rate in a short amount of time and minimal resources. All you need is a model and a training set. The model is initialized with a small learning rate and trained on a batch of data. The associated loss and learning rate is saved. The learning rate is then increased, either linearly or exponentially, and the model is updated with this learning rate. In this notebook, you’ll find an implementation of this approach in PyTorch. I have implemented a class LRfinder. The method range_test holds the logic described above. Using wandb.log()I was able to log the learning rate and corresponding loss. if logwandb: wandb.log({'lr': lr_schedule.get_lr()[0], 'loss': loss}) Use this LRFinder to automatically find the optimal learning rate for your model. lr_finder = LRFinder(net, optimizer, device)lr_finder.range_test(trainloader, end_lr=10, num_iter=100, logwandb=True) You can now head to your W&B run page and find the minima of the LR curve. Use this as your learning rate and train on the entire batch of training set. When the learning rate is too low the model is not able to learn anything and it remains plateaued. When the learning rate is just large enough it starts learning and you will find a sudden dip in the plot. The minima of the curve is what you are looking for as the optimal learning rate. When the learning rate is high the loss explodes i.e. sudden jump in loss. If you are using Keras to build your model you can make use of the learning rate finder as demonstrated in this blog by PyImageSearch. You can also refer this blog for an implementation in TensorFlow 2.0. 1. Problem of the vanishing gradients: There was a major problem 10 years ago in training a deep neural network due to the use of sigmoid/tanh activation functions. To understand this problem the reader is expected to have an understanding of feed forward and back propagation algorithms along with gradient-based optimization. I recommend that you watch this video or read this blog for a better understanding of this problem. In a nutshell, when back propagation is performed, the gradient of the loss with respect to weights of each layer is calculated and it tends to get smaller as we keep on moving backwards in the network. The gradient for each layer can be computed using the chain rule of differentiation. Since the derivative of sigmoid ranges only from 0–0.25 numerically the gradient computed is really small and thus negligible weight updates take place. Due to this problem, the model could not converge or it would take a long time to do so. Suppose you are building a not so traditional neural network architecture. The easiest way to debug such a network is to visualize the gradients. If you are building your network using PyTorch W&B automatically plots gradients for each layer. Check out my notebook here. You can find two models, NetwithIssueand Netin the notebook. The first model uses sigmoid as an activation function for each layer. The latter uses ReLU. The last layer in both the models uses a softmaxactivation function. W&B provides first class support for PyTorch. To automatically log gradients and store the network topology, you can call watch and pass in your PyTorch model. If you want to log histograms of parameter values as well, you can pass log='all'argument to the watch method. In the W&B project page look for the gradient plot in Vanishing_Grad_1, VG_Converge and VG_solved_Relu the run page. To do so click on the run name and then click on the Gradient section. In this run the model was trained for 40 epochs on MNIST handwritten dataset. It eventually converged with a train-test accuracy of over 80%. You can notice a zero gradient for most of the epochs. 2. Dead ReLU: ReLUs aren’t a magic bullet since they can “die” when fed with values less than zero. A large chunk of the network might stop learning if most of the neurons die within a short period of training. In such a situation, take a closer look at your initial weights or add a small initial bias to your weights. If that doesn’t work, you can try to experiment with Maxout, Leaky ReLUs and ReLU6 as illustrated in the MobileNetV2 paper. 3. Problem of exploding gradients: This problem occurs when the later layers learn slower compared to the initial layers, unlike the vanishing gradient problem where earlier layers learn slower than the later layers. This problem occurs when the gradient grows exponentially as we move backwards through the layers. Practically, when gradients explode, the gradients could become NaN because of the numerical overflow or we might see irregular oscillations in the training loss curve. In the case of vanishing gradients, the weight updates are very small while in case of exploding gradients these updates are huge because of which the local minima is missed and models do not converge. You can watch this video for a better understanding of this problem or go through this blog. Let’s try to visualize the gradients in case of the exploding gradients. Check out this notebook here where I intentionally initialized the weights with a big value of 100, such that they would explode. Notice how the gradients are increasing exponentially going backward. The gradient value for conv1 is in the order of 107 while for conv2 is 105. Bad weight initialization can be one reason for this problem. Exploding gradients are not usually encountered in the case of CNN based architectures. They’re more of a problem for Recurrent NNs. Check out this thread for more insight. Due to numerical instability caused by exploding gradient you may get NaN as your loss. This notebook here demonstrates this problem. There are two simple ways around this problem. They are: 1. Gradient Scaling2. Gradient Clipping I used Gradient Clipping to overcome this problem in the linked notebook. Gradient clipping will ‘clip’ the gradients or cap them to a threshold value to prevent the gradients from getting too large. In PyTorch you can do this with one line of code. torch.nn.utils.clip_grad_norm_(model.parameters(), 4.0) Here 4.0 is the threshold. This value worked for my demo use case. Check out the trainModified function in the notebook to see the implementation. 1. Weight Initialization: This is one of the most important aspects of training a neural network. Problems like image classification, sentiment analysis or playing Go can’t be solved using deterministic algorithms. You need a non deterministic algorithm to solve such problems. These algorithms use elements of randomness when making decisions during the execution of the algorithm. These algorithms make careful use of randomness. Artificial neural networks are trained using a stochastic optimization algorithm called stochastic gradient descent. Training a neural network is simply a non deterministic search for a ‘good’ solution. As the search process (training) unfolds, there is a risk that we are stuck in an unfavorable area of the search space. The idea of getting stuck and returning a ‘less-good’ solution is called being getting stuck in a local optima. At times vanishing/exploding gradients prevent the network from learning. To counter this weight initialization is one method of introducing careful randomness into the searching problem. This randomness is introduced in the beginning. Using mini-batches for training with shuffle=True is another method of introducing randomness during progression of search. For more clarity of the underlying concept check out this blog. A good initialization has many benefits. It helps the network achieve global minima for gradient based optimization algorithms (just a piece of the puzzle). It prevents vanishing/exploding gradient problems. A good initialization can speed up training time as well. This blog here explains the basic idea behind weight initialization well. The choice of your initialization method depends on your activation function. To learn more about initialization check out this article. When using ReLU or leaky ReLU, use He initialization also called Kaiming initialization. When using SELU or ELU, use LeCun initialization. When using softmax or tanh, use Glorot initialization also called Xavier initialization. Most initialization methods come in uniform and normal distribution flavors. Check out this PyTorch doc for more info. Check out my notebook here to see how you can initialize weights in PyTorch. Notice how the layers were initialized with kaiming_uniform. You’ll notice this model overfits. By simplifying the model you can easily overcome this problem. 2. Dropout and Batch Normalization: Dropout is a regularization technique that “drops out” or “deactivates” a few neurons in the neural network randomly, in order to avoid the problem of overfitting. During training some neurons in the layer after which the dropout is applied are “turned off”. An ensemble of neural networks with fewer parameters (simpler model) reduces overfitting. Dropout simulates this phenomenon, contrary to snapshot ensembles of networks, without additional computational expense of training and maintaining multiple models. It introduces noise into a neural network to force it to learn to generalize well enough to deal with noise. Batch Normalization is a technique to improve optimization. It’s a good practice to normalize the input data before training on it which prevents the learning algorithm from oscillating. We can say that the output of one layer is the input to the next layer. If this output can be normalized before being used as the input the learning process can be stabilized. This dramatically reduces the number of training epochs required to train deep networks. Batch Normalization makes normalization a part of the model architecture and is performed on mini-batches while training. Batch Normalization also allows the use of much higher learning rates and for us to be less careful about initialization. Let’s implement the above discussed concepts and see the results. Check out my notebook here to see how one can use Batch Normalization and Dropout in Pytorch. I started with a base model to set the benchmark for this study. The implemented architecture is simple and results in overfitting. Notice how test loss increases eventually. I then applied Dropout layers with a drop rate of 0.5 after Conv blocks. To initialize this layer in PyTorch simply call the Dropout method of torch.nn. self.drop = torch.nn.Dropout() Dropout prevented overfitting but the model didn’t converge quickly as expected. This means that ensemble networks take longer to learn. In the context of dropout not every neuron is available while learning. Next up is Batch Normalization. To initialize this layer in PyTorch simply call the BatchNorm2d method of torch.nn. self.bn = torch.nn.BatchNorm2d(32) Batch Normalization took fewer steps to converge the model. Since the model was simple, overfitting could not be avoided. Now let’s use both these layers together. If you are using BN and Dropout together follow this order (for more insight check out this paper). CONV/FC -> BatchNorm -> ReLU(or other activation) -> Dropout -> CONV/FC Notice that by using both Dropout and Batch Normalization overfitting was eliminated while the model converged quicker. When you have a large dataset, it’s important to optimize well, and not as important to regularize well, so batch normalization is more important for large datasets. You can of course use both batch normalization and dropout at the same time, though Batch Normalization also acts as a regularizer, in some cases eliminating the need for Dropout. The article Checklist for debugging neural networks would be a good next step.Unit testing neural networks is not easy. This article discusses How to unit test machine learning codeI highly recommend reading Why are deep neural networks hard to train?For a more in depth explanation on gradient clipping check out how to avoid exploding gradients in neural networks with gradient clipping?The effects of weight initialization on neural nets by Sayak Paul, where he discusses in depth the different effects of weight initialization. The article Checklist for debugging neural networks would be a good next step. Unit testing neural networks is not easy. This article discusses How to unit test machine learning code I highly recommend reading Why are deep neural networks hard to train? For a more in depth explanation on gradient clipping check out how to avoid exploding gradients in neural networks with gradient clipping? The effects of weight initialization on neural nets by Sayak Paul, where he discusses in depth the different effects of weight initialization. I hope that this blog will be helpful for everyone in the Machine Learning community. I’ve tried to share some insights of my own and lots of good reading material for deeper understanding of the topics. The most important aspect of debugging neural network is to track your experiments so you can reproduce them later. Weight and Biases is really handy when it comes to tracking your experiments. With all the latest ways to visualize your experiments, it’s getting easier day by day. I would like to thank Lavanya for the opportunity. I learned a lot in the process. Thank you Sayak Paul for the constant mentoring.
[ { "code": null, "e": 445, "s": 172, "text": "In this post, we’ll see what makes a neural network under perform and ways we can debug this by visualizing the gradients and other parameters associated with model training. We’ll also discuss the problem of vanishing and exploding gradients and methods to overcome them." }, { "code": null, "e": 636, "s": 445, "text": "Finally, we’ll see why proper weight initialization is useful, how to do it correctly, and dive into how regularization methods like dropout and batch normalization affect model performance." }, { "code": null, "e": 714, "s": 636, "text": "As shown in this piece, neural network bugs are really hard to catch because:" }, { "code": null, "e": 910, "s": 714, "text": "1. The code never crashes, raises an exception, or even slows down.2. The network still trains and the loss will still go down.3. The values converge after a few hours, but to really poor results" }, { "code": null, "e": 1041, "s": 910, "text": "I highly recommend reading A Recipe for Training Neural Networks by Andrej Karparthy if you’d like to dive deeper into this topic." }, { "code": null, "e": 1222, "s": 1041, "text": "There is no decisive set of steps to be followed while debugging neural networks. But here is a list of concepts that, if implemented properly, can help debug your neural networks." }, { "code": null, "e": 1403, "s": 1222, "text": "There is no decisive set of steps to be followed while debugging neural networks. But here is a list of concepts that, if implemented properly, can help debug your neural networks." }, { "code": null, "e": 1588, "s": 1403, "text": "1. Decisions about data: We must understand the nuances of data — the type of data, the way it is stored, class balances for targets and features, value scale consistency of data, etc." }, { "code": null, "e": 1764, "s": 1588, "text": "2. Data Preprocessing: We must think about data preprocessing and try to incorporate domain knowledge into it. There are usually two occasions when data preprocessing is used:" }, { "code": null, "e": 1880, "s": 1764, "text": "Data cleaning: The objective task can be achieved easily if some parts of the data, known as artifacts, is removed." }, { "code": null, "e": 2135, "s": 1880, "text": "Data augmentation: When we have limited training data, we transform each data sample in numerous ways to be used for training the model (example scaling, shifting, rotating images).This post is not focusing on the issues caused by bad data preprocessing." }, { "code": null, "e": 2702, "s": 2135, "text": "3. Overfitting on a small dataset: If we have a small dataset of 50–60 data samples, the model will overfit quickly i.e., the loss will be zero in 2–5 epochs. To overcome this, be sure to remove any regularization from the model. If your model is not overfitting, it might be because might be your model is not architected correctly or the choice of your loss is incorrect. Maybe your output layer is activated with sigmoid while you were trying to do multi-class classification. These errors can be easy to miss error. Check out my notebook demonstrating this here." }, { "code": null, "e": 2750, "s": 2702, "text": "So how can one avoid such errors? Keep reading." }, { "code": null, "e": 3026, "s": 2750, "text": "1. Start with a small architecture: Using fancy regularizers and schedulers may be overkill. In case of an error, it’s easier to debug a small network. Common errors include forgetting to pass tensors from one layer to another, have insane input to output neurons ratio, etc." }, { "code": null, "e": 3894, "s": 3026, "text": "2. Pretrained model(weights): If your model architecture is built on top of a standard backbone like VGG, Resnet, Inception, etc you can use pre-trained weights on a standard dataset — if you can, find one on the dataset that you are working with. One interesting recent paper, Transfusion: Understanding Transfer Learning for Medical Imaging shows that using even a few early layers from a pre-trained ImageNet model can improve both the speed of training and final accuracy of medical imaging models. Therefore, you should use a general-purpose pre-trained model, even if it is not in the domain of the problem you’re solving. The amount of improvement from an ImageNet pre-trained model when applied to medical imaging is not that great. Thus there isn’t much guarantee on a head start either. For more, I recommend reading this amazing blog post by Jeremy Howard." }, { "code": null, "e": 4150, "s": 3894, "text": "1. Choosing the right loss function: First, make sure that you are using the right loss function for the given task. For a multi-class classifier, a binary loss function will not help improve the accuracy, so categorical cross-entropy is the right choice." }, { "code": null, "e": 4466, "s": 4150, "text": "2. Determine theoretical loss: If your model started by guessing randomly (i.e. no pretrained model), check to see if the initial loss is close to your expected loss. If you’re using cross-entropy loss, check to see that your initial loss is approximately -log(1/num_classes. You can get some more suggestions here." }, { "code": null, "e": 4794, "s": 4466, "text": "3. Learning Rate: This parameter determines the step size at each iteration while moving toward the minimum of a loss function. You can tweak the learning rate according to how steep or smooth your loss function is. But this can be a time and resource consuming step. Can you find the most optimal learning rate, automatically?" }, { "code": null, "e": 5238, "s": 4794, "text": "Leslie N. Smith presented a very smart and simple approach to systematically find a learning rate in a short amount of time and minimal resources. All you need is a model and a training set. The model is initialized with a small learning rate and trained on a batch of data. The associated loss and learning rate is saved. The learning rate is then increased, either linearly or exponentially, and the model is updated with this learning rate." }, { "code": null, "e": 5484, "s": 5238, "text": "In this notebook, you’ll find an implementation of this approach in PyTorch. I have implemented a class LRfinder. The method range_test holds the logic described above. Using wandb.log()I was able to log the learning rate and corresponding loss." }, { "code": null, "e": 5555, "s": 5484, "text": "if logwandb: wandb.log({'lr': lr_schedule.get_lr()[0], 'loss': loss})" }, { "code": null, "e": 5637, "s": 5555, "text": "Use this LRFinder to automatically find the optimal learning rate for your model." }, { "code": null, "e": 5755, "s": 5637, "text": "lr_finder = LRFinder(net, optimizer, device)lr_finder.range_test(trainloader, end_lr=10, num_iter=100, logwandb=True)" }, { "code": null, "e": 5908, "s": 5755, "text": "You can now head to your W&B run page and find the minima of the LR curve. Use this as your learning rate and train on the entire batch of training set." }, { "code": null, "e": 6272, "s": 5908, "text": "When the learning rate is too low the model is not able to learn anything and it remains plateaued. When the learning rate is just large enough it starts learning and you will find a sudden dip in the plot. The minima of the curve is what you are looking for as the optimal learning rate. When the learning rate is high the loss explodes i.e. sudden jump in loss." }, { "code": null, "e": 6477, "s": 6272, "text": "If you are using Keras to build your model you can make use of the learning rate finder as demonstrated in this blog by PyImageSearch. You can also refer this blog for an implementation in TensorFlow 2.0." }, { "code": null, "e": 6905, "s": 6477, "text": "1. Problem of the vanishing gradients: There was a major problem 10 years ago in training a deep neural network due to the use of sigmoid/tanh activation functions. To understand this problem the reader is expected to have an understanding of feed forward and back propagation algorithms along with gradient-based optimization. I recommend that you watch this video or read this blog for a better understanding of this problem." }, { "code": null, "e": 7435, "s": 6905, "text": "In a nutshell, when back propagation is performed, the gradient of the loss with respect to weights of each layer is calculated and it tends to get smaller as we keep on moving backwards in the network. The gradient for each layer can be computed using the chain rule of differentiation. Since the derivative of sigmoid ranges only from 0–0.25 numerically the gradient computed is really small and thus negligible weight updates take place. Due to this problem, the model could not converge or it would take a long time to do so." }, { "code": null, "e": 7706, "s": 7435, "text": "Suppose you are building a not so traditional neural network architecture. The easiest way to debug such a network is to visualize the gradients. If you are building your network using PyTorch W&B automatically plots gradients for each layer. Check out my notebook here." }, { "code": null, "e": 7929, "s": 7706, "text": "You can find two models, NetwithIssueand Netin the notebook. The first model uses sigmoid as an activation function for each layer. The latter uses ReLU. The last layer in both the models uses a softmaxactivation function." }, { "code": null, "e": 8200, "s": 7929, "text": "W&B provides first class support for PyTorch. To automatically log gradients and store the network topology, you can call watch and pass in your PyTorch model. If you want to log histograms of parameter values as well, you can pass log='all'argument to the watch method." }, { "code": null, "e": 8388, "s": 8200, "text": "In the W&B project page look for the gradient plot in Vanishing_Grad_1, VG_Converge and VG_solved_Relu the run page. To do so click on the run name and then click on the Gradient section." }, { "code": null, "e": 8585, "s": 8388, "text": "In this run the model was trained for 40 epochs on MNIST handwritten dataset. It eventually converged with a train-test accuracy of over 80%. You can notice a zero gradient for most of the epochs." }, { "code": null, "e": 9029, "s": 8585, "text": "2. Dead ReLU: ReLUs aren’t a magic bullet since they can “die” when fed with values less than zero. A large chunk of the network might stop learning if most of the neurons die within a short period of training. In such a situation, take a closer look at your initial weights or add a small initial bias to your weights. If that doesn’t work, you can try to experiment with Maxout, Leaky ReLUs and ReLU6 as illustrated in the MobileNetV2 paper." }, { "code": null, "e": 9809, "s": 9029, "text": "3. Problem of exploding gradients: This problem occurs when the later layers learn slower compared to the initial layers, unlike the vanishing gradient problem where earlier layers learn slower than the later layers. This problem occurs when the gradient grows exponentially as we move backwards through the layers. Practically, when gradients explode, the gradients could become NaN because of the numerical overflow or we might see irregular oscillations in the training loss curve. In the case of vanishing gradients, the weight updates are very small while in case of exploding gradients these updates are huge because of which the local minima is missed and models do not converge. You can watch this video for a better understanding of this problem or go through this blog." }, { "code": null, "e": 10012, "s": 9809, "text": "Let’s try to visualize the gradients in case of the exploding gradients. Check out this notebook here where I intentionally initialized the weights with a big value of 100, such that they would explode." }, { "code": null, "e": 10220, "s": 10012, "text": "Notice how the gradients are increasing exponentially going backward. The gradient value for conv1 is in the order of 107 while for conv2 is 105. Bad weight initialization can be one reason for this problem." }, { "code": null, "e": 10527, "s": 10220, "text": "Exploding gradients are not usually encountered in the case of CNN based architectures. They’re more of a problem for Recurrent NNs. Check out this thread for more insight. Due to numerical instability caused by exploding gradient you may get NaN as your loss. This notebook here demonstrates this problem." }, { "code": null, "e": 10584, "s": 10527, "text": "There are two simple ways around this problem. They are:" }, { "code": null, "e": 10624, "s": 10584, "text": "1. Gradient Scaling2. Gradient Clipping" }, { "code": null, "e": 10874, "s": 10624, "text": "I used Gradient Clipping to overcome this problem in the linked notebook. Gradient clipping will ‘clip’ the gradients or cap them to a threshold value to prevent the gradients from getting too large. In PyTorch you can do this with one line of code." }, { "code": null, "e": 10930, "s": 10874, "text": "torch.nn.utils.clip_grad_norm_(model.parameters(), 4.0)" }, { "code": null, "e": 11077, "s": 10930, "text": "Here 4.0 is the threshold. This value worked for my demo use case. Check out the trainModified function in the notebook to see the implementation." }, { "code": null, "e": 11712, "s": 11077, "text": "1. Weight Initialization: This is one of the most important aspects of training a neural network. Problems like image classification, sentiment analysis or playing Go can’t be solved using deterministic algorithms. You need a non deterministic algorithm to solve such problems. These algorithms use elements of randomness when making decisions during the execution of the algorithm. These algorithms make careful use of randomness. Artificial neural networks are trained using a stochastic optimization algorithm called stochastic gradient descent. Training a neural network is simply a non deterministic search for a ‘good’ solution." }, { "code": null, "e": 12368, "s": 11712, "text": "As the search process (training) unfolds, there is a risk that we are stuck in an unfavorable area of the search space. The idea of getting stuck and returning a ‘less-good’ solution is called being getting stuck in a local optima. At times vanishing/exploding gradients prevent the network from learning. To counter this weight initialization is one method of introducing careful randomness into the searching problem. This randomness is introduced in the beginning. Using mini-batches for training with shuffle=True is another method of introducing randomness during progression of search. For more clarity of the underlying concept check out this blog." }, { "code": null, "e": 12708, "s": 12368, "text": "A good initialization has many benefits. It helps the network achieve global minima for gradient based optimization algorithms (just a piece of the puzzle). It prevents vanishing/exploding gradient problems. A good initialization can speed up training time as well. This blog here explains the basic idea behind weight initialization well." }, { "code": null, "e": 12845, "s": 12708, "text": "The choice of your initialization method depends on your activation function. To learn more about initialization check out this article." }, { "code": null, "e": 12934, "s": 12845, "text": "When using ReLU or leaky ReLU, use He initialization also called Kaiming initialization." }, { "code": null, "e": 12984, "s": 12934, "text": "When using SELU or ELU, use LeCun initialization." }, { "code": null, "e": 13073, "s": 12984, "text": "When using softmax or tanh, use Glorot initialization also called Xavier initialization." }, { "code": null, "e": 13192, "s": 13073, "text": "Most initialization methods come in uniform and normal distribution flavors. Check out this PyTorch doc for more info." }, { "code": null, "e": 13269, "s": 13192, "text": "Check out my notebook here to see how you can initialize weights in PyTorch." }, { "code": null, "e": 13428, "s": 13269, "text": "Notice how the layers were initialized with kaiming_uniform. You’ll notice this model overfits. By simplifying the model you can easily overcome this problem." }, { "code": null, "e": 14087, "s": 13428, "text": "2. Dropout and Batch Normalization: Dropout is a regularization technique that “drops out” or “deactivates” a few neurons in the neural network randomly, in order to avoid the problem of overfitting. During training some neurons in the layer after which the dropout is applied are “turned off”. An ensemble of neural networks with fewer parameters (simpler model) reduces overfitting. Dropout simulates this phenomenon, contrary to snapshot ensembles of networks, without additional computational expense of training and maintaining multiple models. It introduces noise into a neural network to force it to learn to generalize well enough to deal with noise." }, { "code": null, "e": 14783, "s": 14087, "text": "Batch Normalization is a technique to improve optimization. It’s a good practice to normalize the input data before training on it which prevents the learning algorithm from oscillating. We can say that the output of one layer is the input to the next layer. If this output can be normalized before being used as the input the learning process can be stabilized. This dramatically reduces the number of training epochs required to train deep networks. Batch Normalization makes normalization a part of the model architecture and is performed on mini-batches while training. Batch Normalization also allows the use of much higher learning rates and for us to be less careful about initialization." }, { "code": null, "e": 15075, "s": 14783, "text": "Let’s implement the above discussed concepts and see the results. Check out my notebook here to see how one can use Batch Normalization and Dropout in Pytorch. I started with a base model to set the benchmark for this study. The implemented architecture is simple and results in overfitting." }, { "code": null, "e": 15271, "s": 15075, "text": "Notice how test loss increases eventually. I then applied Dropout layers with a drop rate of 0.5 after Conv blocks. To initialize this layer in PyTorch simply call the Dropout method of torch.nn." }, { "code": null, "e": 15302, "s": 15271, "text": "self.drop = torch.nn.Dropout()" }, { "code": null, "e": 15511, "s": 15302, "text": "Dropout prevented overfitting but the model didn’t converge quickly as expected. This means that ensemble networks take longer to learn. In the context of dropout not every neuron is available while learning." }, { "code": null, "e": 15627, "s": 15511, "text": "Next up is Batch Normalization. To initialize this layer in PyTorch simply call the BatchNorm2d method of torch.nn." }, { "code": null, "e": 15662, "s": 15627, "text": "self.bn = torch.nn.BatchNorm2d(32)" }, { "code": null, "e": 15784, "s": 15662, "text": "Batch Normalization took fewer steps to converge the model. Since the model was simple, overfitting could not be avoided." }, { "code": null, "e": 15926, "s": 15784, "text": "Now let’s use both these layers together. If you are using BN and Dropout together follow this order (for more insight check out this paper)." }, { "code": null, "e": 15998, "s": 15926, "text": "CONV/FC -> BatchNorm -> ReLU(or other activation) -> Dropout -> CONV/FC" }, { "code": null, "e": 16118, "s": 15998, "text": "Notice that by using both Dropout and Batch Normalization overfitting was eliminated while the model converged quicker." }, { "code": null, "e": 16464, "s": 16118, "text": "When you have a large dataset, it’s important to optimize well, and not as important to regularize well, so batch normalization is more important for large datasets. You can of course use both batch normalization and dropout at the same time, though Batch Normalization also acts as a regularizer, in some cases eliminating the need for Dropout." }, { "code": null, "e": 16996, "s": 16464, "text": "The article Checklist for debugging neural networks would be a good next step.Unit testing neural networks is not easy. This article discusses How to unit test machine learning codeI highly recommend reading Why are deep neural networks hard to train?For a more in depth explanation on gradient clipping check out how to avoid exploding gradients in neural networks with gradient clipping?The effects of weight initialization on neural nets by Sayak Paul, where he discusses in depth the different effects of weight initialization." }, { "code": null, "e": 17075, "s": 16996, "text": "The article Checklist for debugging neural networks would be a good next step." }, { "code": null, "e": 17179, "s": 17075, "text": "Unit testing neural networks is not easy. This article discusses How to unit test machine learning code" }, { "code": null, "e": 17250, "s": 17179, "text": "I highly recommend reading Why are deep neural networks hard to train?" }, { "code": null, "e": 17389, "s": 17250, "text": "For a more in depth explanation on gradient clipping check out how to avoid exploding gradients in neural networks with gradient clipping?" }, { "code": null, "e": 17532, "s": 17389, "text": "The effects of weight initialization on neural nets by Sayak Paul, where he discusses in depth the different effects of weight initialization." }, { "code": null, "e": 18018, "s": 17532, "text": "I hope that this blog will be helpful for everyone in the Machine Learning community. I’ve tried to share some insights of my own and lots of good reading material for deeper understanding of the topics. The most important aspect of debugging neural network is to track your experiments so you can reproduce them later. Weight and Biases is really handy when it comes to tracking your experiments. With all the latest ways to visualize your experiments, it’s getting easier day by day." } ]
Ext.js - Questions and Answers
Ext JS stands for extended JavaScript. It is a JavaScript framework to develop rich UI web based desktop applications. It is a Sencha product which is extended from YUI (Yahoo user interface). These are the main files to include in HTML page to run Ext JS code − Ext-all.js Ext-all.css Customizable UI widgets with collection of rich UI such as Grids, pivot grids, forms, charts, trees. Code compatibility of new versions with the older one. A flexible layout manager helps to organize the display of data and content across multiple browsers, devices, and screen sizes. Advance data package decouples the UI widgets from the data layer. The data package allows client-side collection of data using highly functional models that enable features such as sorting and filtering. It is protocol agnostic, and can access data from any back-end source. Customizable Themes Ext JS widgets are available in multiple out-of-the-box themes that are consistent across platforms. Streamlines cross-platform development across desktops, tablets, and smartphones — for both modern and legacy browsers. Streamlines cross-platform development across desktops, tablets, and smartphones — for both modern and legacy browsers. Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins. Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins. Reduces the cost of web application development. Reduces the cost of web application development. Empowers teams to create apps with a compelling user experience. Empowers teams to create apps with a compelling user experience. It has set of widgets for making UI powerful and easy. It has set of widgets for making UI powerful and easy. It follows MVC architecture so highly readable code. It follows MVC architecture so highly readable code. The size of library is large around 500 KB which makes initial loading time more and makes application slow. The size of library is large around 500 KB which makes initial loading time more and makes application slow. HTML is full of <DIV> tags makes it complex and difficult to debug. HTML is full of <DIV> tags makes it complex and difficult to debug. According to general public license policy it is free for open source applications but paid for commercial applications. According to general public license policy it is free for open source applications but paid for commercial applications. Some times for loading even simple things requires few lines of coding which is simpler in plain html or Jquery. Some times for loading even simple things requires few lines of coding which is simpler in plain html or Jquery. Need quite experienced developer for developing Ext JS applications. Need quite experienced developer for developing Ext JS applications. Ext JS supports cross browser compatibility, it supports all major browsers as − IE 6 and above Firefox 3.6 and above Chrome10 and above Safari 4 and above Opera 11 and above Ext JS 4+ supports MVC (Model view controller) architecture. From Ext JS 5 it started supporting MVVM (Model View Viewmodel) also. Ext JS 6 is the latest version of Ext JS which has major benefit that it can be used for both desktop and as well as mobile applications. Basically it is a merge of Ext JS (desktop applications) and Sencha touch (mobile application). Ext JS is a JavaScript framework so to start using it you should use have prior knowledge of HTML and JS (not expert level but should have basic understanding). Then it takes to understand the basic so give it time and learn gradually. Both the frameworks are quite different we can compare Ext JS and jQuery UI as Ext JS is full-fledged UI rich framework. But still Ext JS has much more components then jQuery UI. Ext JS 1.1 The first version of Ext JS was developed by Jack Slocum in 2006. It was a set of utility classes which is an extension of YUI. He named the library as YUI-ext. Ext JS 2.0 Ext JS version 2.0 was released in 2007. This version had new API documentation for desktop Application with limited features. This version doesn't had backward compatibility with previous version of Ext JS. Ext JS 3.0 Ext JS version 3.0 was released in 2009. This version added new features as chart and list view but at the cost of speed. It had backwards compatible with version 2.0. Ext JS 4.0 After the release of Ext JS 3 the developers of Ext JS had the major challenge of ramping up the speed. Ext JS version 4.0 was released in 2011. It had the complete revised structure which followed by MVC architecture and a speedy application. Ext JS 5.0 Ext JS version 5.0 was released in 2014. The major change in this release was to change the MVC architecture to MVVM architecture. It includes the ability to build desktop apps on touch-enabled devices, two-way data binding, responsive layouts and many more features. Ext JS 6.0 Ext JS 6 merges the Ext JS (for desktop application) and sencha touch (for mobile application) framework. Ext JS has various UI components some of the majorly used components are − Grid Form Message Box Progress Bar Tool Tip Window HTML Editor Charts xType defines the type of Ext JS UI component, which is determined during rendering of the component. E.g. textField, Numeric, button etc. This is the validation type can be customized easily. Few vType provided by Ext JS are − alphanumText − This returns false if the text entered has any symbol other than alphabate or numeric value. emailText − This returns false, if text is not a valid email address. Yes Ext JS can be integrated with Ajax. Implementation as: suppose on some text box after blur it has to validate the data from server for that we can have an Ajax call onblur/onchange to the text box id to check whether the data entered in the text box is present in server/database. Yes Ext JS can be integrated with other server side framework such as Java, .net, Ruby on rails, PHP, ColdFusion etc. Ext JS can be implemented on any popular integrated development environment (IDE) such as Eclipse, Aptana, Sublime, Webstrom etc. These are few ways to access DOM elements in Ext JS − Ext.get() Ext.getElementById() Ext.fly() Ext.select() MVVM architecture is Model View Viewmodel. In MVVM architecture controller of MVC is replaced by ViewModel. ViewModel − It is basically medicates the changes between view and model. It binds the data from model to view. At the same time it does not have any direct interaction with view it has only knowledge of model. Ext.getCmp('buttonId').on('click', function(){ // statement to perform logic }); Ext.onReady() is the first method which is called when the DOM is fully loaded so that whatever element you want to refer will be available when script runs. Ext.select('div').on('click', function(){ // statement to perform logic }); Different type of alert boxes in Ext JS are − Ext.MessageBox.alert(); Ext.MessageBox.confirm(); Ext.MessageBox.wait(); Ext.MessageBox.promt(); Ext.MessageBox.show(); Base classes for Store is Ext.data.Store For model is Ext.data.Model For Controller is Ext.app.controller These are the different ways for event handling − Using Listeners Attaching events later Using custom events Store.getCount() − For cached records Store.getTotalCount() − For total no of records in the DB. Store.getModifiedRecords()method is used to get modified records. Store.commitChanges() method to update store changes. If we have grid Id : Ext.getCmp('gridId').getStore().getAt(index); If we have store Id: Ext.getStore('storeId').getAt(index); Store.load(); Base class for Grid - Ext.grid.GridPanel For form – Ext.form.Panel For panel – Ext.panel.Panel For chart – Ext.chart.Chart For tree – Ext.tree.Panel Different type of layouts are − Absolute Accordion Anchor Border Auto hBox vBox Card(TabPanel) Card(Wizard) Column Fit Table This can be done using pagingToolbar() as − new Ext.PagingToolbar ({ pageSize: 25, store: store, displayInfo: true, displayMsg: 'Displaying topics {0} - {1} of {2}', emptyMsg: 'No topics to display', }); // trigger the data store load store.load({params:{start:0, limit:25}}); dockedItems: [{ xtype: 'toolbar', items: [{ id:'buttonId', handler: function() { Ext.Msg.alert('title','alertMsg'); }); }] }] Loadmask is used to prevent any other operation by showing loading(or Custom message) to the user until data gets rendered to the grid. Loadmask: true; is the property to show loadmask while data getting rendered to the grid. Renderer is used when we want to manipulate the data which we get from store to show manipulated data based on some criteria. It is a column property can be used as − renderer: function(value, metadata, record, rowIndex, colIndex, store){ // logic to perform } Ext.getCmp('id').getValue(); Hidden: true; Sortable: true; which is default true. grid.getStore().on ({ beforeload : function(store) { // perform some operation }, load : { fn : function(store) { //perform some operation }, scope : this } store.load(); }); Ext JS 6 has toolkit package with which it can include visual elements of both the frameworks (Ext JS and Sencha Touch). It can be added as − 'toolkit': 'classic', // or 'modern' If toolkit is classic it includes Ext JS desktop application framework. And if toolkit is modern then it includes sencha touch mobile application framework. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) Print Add Notes Bookmark this page
[ { "code": null, "e": 2142, "s": 2023, "text": "Ext JS stands for extended JavaScript. It is a JavaScript framework to develop rich UI web based desktop applications." }, { "code": null, "e": 2216, "s": 2142, "text": "It is a Sencha product which is extended from YUI (Yahoo user interface)." }, { "code": null, "e": 2286, "s": 2216, "text": "These are the main files to include in HTML page to run Ext JS code −" }, { "code": null, "e": 2297, "s": 2286, "text": "Ext-all.js" }, { "code": null, "e": 2309, "s": 2297, "text": "Ext-all.css" }, { "code": null, "e": 2410, "s": 2309, "text": "Customizable UI widgets with collection of rich UI such as Grids, pivot grids, forms, charts, trees." }, { "code": null, "e": 2465, "s": 2410, "text": "Code compatibility of new versions with the older one." }, { "code": null, "e": 2594, "s": 2465, "text": "A flexible layout manager helps to organize the display of data and content across multiple browsers, devices, and screen sizes." }, { "code": null, "e": 2799, "s": 2594, "text": "Advance data package decouples the UI widgets from the data layer. The data package allows client-side collection of data using highly functional models that enable features such as sorting and filtering." }, { "code": null, "e": 2870, "s": 2799, "text": "It is protocol agnostic, and can access data from any back-end source." }, { "code": null, "e": 2991, "s": 2870, "text": "Customizable Themes Ext JS widgets are available in multiple out-of-the-box themes that are consistent across platforms." }, { "code": null, "e": 3111, "s": 2991, "text": "Streamlines cross-platform development across desktops, tablets, and smartphones — for both modern and legacy browsers." }, { "code": null, "e": 3231, "s": 3111, "text": "Streamlines cross-platform development across desktops, tablets, and smartphones — for both modern and legacy browsers." }, { "code": null, "e": 3352, "s": 3231, "text": "Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins." }, { "code": null, "e": 3473, "s": 3352, "text": "Increases the productivity of development teams by integrating into enterprise development environments via IDE plugins." }, { "code": null, "e": 3522, "s": 3473, "text": "Reduces the cost of web application development." }, { "code": null, "e": 3571, "s": 3522, "text": "Reduces the cost of web application development." }, { "code": null, "e": 3636, "s": 3571, "text": "Empowers teams to create apps with a compelling user experience." }, { "code": null, "e": 3701, "s": 3636, "text": "Empowers teams to create apps with a compelling user experience." }, { "code": null, "e": 3756, "s": 3701, "text": "It has set of widgets for making UI powerful and easy." }, { "code": null, "e": 3811, "s": 3756, "text": "It has set of widgets for making UI powerful and easy." }, { "code": null, "e": 3864, "s": 3811, "text": "It follows MVC architecture so highly readable code." }, { "code": null, "e": 3917, "s": 3864, "text": "It follows MVC architecture so highly readable code." }, { "code": null, "e": 4026, "s": 3917, "text": "The size of library is large around 500 KB which makes initial loading time more and makes application slow." }, { "code": null, "e": 4135, "s": 4026, "text": "The size of library is large around 500 KB which makes initial loading time more and makes application slow." }, { "code": null, "e": 4203, "s": 4135, "text": "HTML is full of <DIV> tags makes it complex and difficult to debug." }, { "code": null, "e": 4271, "s": 4203, "text": "HTML is full of <DIV> tags makes it complex and difficult to debug." }, { "code": null, "e": 4392, "s": 4271, "text": "According to general public license policy it is free for open source applications but paid for commercial applications." }, { "code": null, "e": 4513, "s": 4392, "text": "According to general public license policy it is free for open source applications but paid for commercial applications." }, { "code": null, "e": 4626, "s": 4513, "text": "Some times for loading even simple things requires few lines of coding which is simpler in plain html or Jquery." }, { "code": null, "e": 4739, "s": 4626, "text": "Some times for loading even simple things requires few lines of coding which is simpler in plain html or Jquery." }, { "code": null, "e": 4808, "s": 4739, "text": "Need quite experienced developer for developing Ext JS applications." }, { "code": null, "e": 4877, "s": 4808, "text": "Need quite experienced developer for developing Ext JS applications." }, { "code": null, "e": 4958, "s": 4877, "text": "Ext JS supports cross browser compatibility, it supports all major browsers as −" }, { "code": null, "e": 4973, "s": 4958, "text": "IE 6 and above" }, { "code": null, "e": 4995, "s": 4973, "text": "Firefox 3.6 and above" }, { "code": null, "e": 5014, "s": 4995, "text": "Chrome10 and above" }, { "code": null, "e": 5033, "s": 5014, "text": "Safari 4 and above" }, { "code": null, "e": 5052, "s": 5033, "text": "Opera 11 and above" }, { "code": null, "e": 5183, "s": 5052, "text": "Ext JS 4+ supports MVC (Model view controller) architecture. From Ext JS 5 it started supporting MVVM (Model View Viewmodel) also." }, { "code": null, "e": 5417, "s": 5183, "text": "Ext JS 6 is the latest version of Ext JS which has major benefit that it can be used for both desktop and as well as mobile applications. Basically it is a merge of Ext JS (desktop applications) and Sencha touch (mobile application)." }, { "code": null, "e": 5653, "s": 5417, "text": "Ext JS is a JavaScript framework so to start using it you should use have prior knowledge of HTML and JS (not expert level but should have basic understanding). Then it takes to understand the basic so give it time and learn gradually." }, { "code": null, "e": 5832, "s": 5653, "text": "Both the frameworks are quite different we can compare Ext JS and jQuery UI as Ext JS is full-fledged UI rich framework. But still Ext JS has much more components then jQuery UI." }, { "code": null, "e": 5843, "s": 5832, "text": "Ext JS 1.1" }, { "code": null, "e": 6004, "s": 5843, "text": "The first version of Ext JS was developed by Jack Slocum in 2006. It was a set of utility classes which is an extension of YUI. He named the library as YUI-ext." }, { "code": null, "e": 6015, "s": 6004, "text": "Ext JS 2.0" }, { "code": null, "e": 6223, "s": 6015, "text": "Ext JS version 2.0 was released in 2007. This version had new API documentation for desktop Application with limited features. This version doesn't had backward compatibility with previous version of Ext JS." }, { "code": null, "e": 6234, "s": 6223, "text": "Ext JS 3.0" }, { "code": null, "e": 6402, "s": 6234, "text": "Ext JS version 3.0 was released in 2009. This version added new features as chart and list view but at the cost of speed. It had backwards compatible with version 2.0." }, { "code": null, "e": 6413, "s": 6402, "text": "Ext JS 4.0" }, { "code": null, "e": 6657, "s": 6413, "text": "After the release of Ext JS 3 the developers of Ext JS had the major challenge of ramping up the speed. Ext JS version 4.0 was released in 2011. It had the complete revised structure which followed by MVC architecture and a speedy application." }, { "code": null, "e": 6668, "s": 6657, "text": "Ext JS 5.0" }, { "code": null, "e": 6936, "s": 6668, "text": "Ext JS version 5.0 was released in 2014. The major change in this release was to change the MVC architecture to MVVM architecture. It includes the ability to build desktop apps on touch-enabled devices, two-way data binding, responsive layouts and many more features." }, { "code": null, "e": 6947, "s": 6936, "text": "Ext JS 6.0" }, { "code": null, "e": 7053, "s": 6947, "text": "Ext JS 6 merges the Ext JS (for desktop application) and sencha touch (for mobile application) framework." }, { "code": null, "e": 7128, "s": 7053, "text": "Ext JS has various UI components some of the majorly used components are −" }, { "code": null, "e": 7133, "s": 7128, "text": "Grid" }, { "code": null, "e": 7138, "s": 7133, "text": "Form" }, { "code": null, "e": 7150, "s": 7138, "text": "Message Box" }, { "code": null, "e": 7163, "s": 7150, "text": "Progress Bar" }, { "code": null, "e": 7172, "s": 7163, "text": "Tool Tip" }, { "code": null, "e": 7179, "s": 7172, "text": "Window" }, { "code": null, "e": 7191, "s": 7179, "text": "HTML Editor" }, { "code": null, "e": 7198, "s": 7191, "text": "Charts" }, { "code": null, "e": 7337, "s": 7198, "text": "xType defines the type of Ext JS UI component, which is determined during rendering of the component. E.g. textField, Numeric, button etc." }, { "code": null, "e": 7426, "s": 7337, "text": "This is the validation type can be customized easily. Few vType provided by Ext JS are −" }, { "code": null, "e": 7534, "s": 7426, "text": "alphanumText − This returns false if the text entered has any symbol other than alphabate or numeric value." }, { "code": null, "e": 7604, "s": 7534, "text": "emailText − This returns false, if text is not a valid email address." }, { "code": null, "e": 7889, "s": 7604, "text": "Yes Ext JS can be integrated with Ajax. Implementation as: suppose on some text box after blur it has to validate the data from server for that we can have an Ajax call onblur/onchange to the text box id to check whether the data entered in the text box is present in server/database." }, { "code": null, "e": 8007, "s": 7889, "text": "Yes Ext JS can be integrated with other server side framework such as Java, .net, Ruby on rails, PHP, ColdFusion etc." }, { "code": null, "e": 8137, "s": 8007, "text": "Ext JS can be implemented on any popular integrated development environment (IDE) such as Eclipse, Aptana, Sublime, Webstrom etc." }, { "code": null, "e": 8191, "s": 8137, "text": "These are few ways to access DOM elements in Ext JS −" }, { "code": null, "e": 8201, "s": 8191, "text": "Ext.get()" }, { "code": null, "e": 8222, "s": 8201, "text": "Ext.getElementById()" }, { "code": null, "e": 8232, "s": 8222, "text": "Ext.fly()" }, { "code": null, "e": 8245, "s": 8232, "text": "Ext.select()" }, { "code": null, "e": 8353, "s": 8245, "text": "MVVM architecture is Model View Viewmodel. In MVVM architecture controller of MVC is replaced by ViewModel." }, { "code": null, "e": 8564, "s": 8353, "text": "ViewModel − It is basically medicates the changes between view and model. It binds the data from model to view. At the same time it does not have any direct interaction with view it has only knowledge of model." }, { "code": null, "e": 8645, "s": 8564, "text": "Ext.getCmp('buttonId').on('click', function(){\n// statement to perform logic\n});" }, { "code": null, "e": 8803, "s": 8645, "text": "Ext.onReady() is the first method which is called when the DOM is fully loaded so that whatever element you want to refer will be available when script runs." }, { "code": null, "e": 8879, "s": 8803, "text": "Ext.select('div').on('click', function(){\n// statement to perform logic\n});" }, { "code": null, "e": 8925, "s": 8879, "text": "Different type of alert boxes in Ext JS are −" }, { "code": null, "e": 8949, "s": 8925, "text": "Ext.MessageBox.alert();" }, { "code": null, "e": 8975, "s": 8949, "text": "Ext.MessageBox.confirm();" }, { "code": null, "e": 8998, "s": 8975, "text": "Ext.MessageBox.wait();" }, { "code": null, "e": 9022, "s": 8998, "text": "Ext.MessageBox.promt();" }, { "code": null, "e": 9045, "s": 9022, "text": "Ext.MessageBox.show();" }, { "code": null, "e": 9086, "s": 9045, "text": "Base classes for Store is Ext.data.Store" }, { "code": null, "e": 9114, "s": 9086, "text": "For model is Ext.data.Model" }, { "code": null, "e": 9151, "s": 9114, "text": "For Controller is Ext.app.controller" }, { "code": null, "e": 9201, "s": 9151, "text": "These are the different ways for event handling −" }, { "code": null, "e": 9217, "s": 9201, "text": "Using Listeners" }, { "code": null, "e": 9240, "s": 9217, "text": "Attaching events later" }, { "code": null, "e": 9260, "s": 9240, "text": "Using custom events" }, { "code": null, "e": 9298, "s": 9260, "text": "Store.getCount() − For cached records" }, { "code": null, "e": 9357, "s": 9298, "text": "Store.getTotalCount() − For total no of records in the DB." }, { "code": null, "e": 9423, "s": 9357, "text": "Store.getModifiedRecords()method is used to get modified records." }, { "code": null, "e": 9477, "s": 9423, "text": "Store.commitChanges() method to update store changes." }, { "code": null, "e": 9544, "s": 9477, "text": "If we have grid Id : Ext.getCmp('gridId').getStore().getAt(index);" }, { "code": null, "e": 9603, "s": 9544, "text": "If we have store Id: Ext.getStore('storeId').getAt(index);" }, { "code": null, "e": 9617, "s": 9603, "text": "Store.load();" }, { "code": null, "e": 9658, "s": 9617, "text": "Base class for Grid - Ext.grid.GridPanel" }, { "code": null, "e": 9684, "s": 9658, "text": "For form – Ext.form.Panel" }, { "code": null, "e": 9712, "s": 9684, "text": "For panel – Ext.panel.Panel" }, { "code": null, "e": 9740, "s": 9712, "text": "For chart – Ext.chart.Chart" }, { "code": null, "e": 9766, "s": 9740, "text": "For tree – Ext.tree.Panel" }, { "code": null, "e": 9798, "s": 9766, "text": "Different type of layouts are −" }, { "code": null, "e": 9807, "s": 9798, "text": "Absolute" }, { "code": null, "e": 9817, "s": 9807, "text": "Accordion" }, { "code": null, "e": 9824, "s": 9817, "text": "Anchor" }, { "code": null, "e": 9831, "s": 9824, "text": "Border" }, { "code": null, "e": 9836, "s": 9831, "text": "Auto" }, { "code": null, "e": 9841, "s": 9836, "text": "hBox" }, { "code": null, "e": 9846, "s": 9841, "text": "vBox" }, { "code": null, "e": 9861, "s": 9846, "text": "Card(TabPanel)" }, { "code": null, "e": 9874, "s": 9861, "text": "Card(Wizard)" }, { "code": null, "e": 9881, "s": 9874, "text": "Column" }, { "code": null, "e": 9885, "s": 9881, "text": "Fit" }, { "code": null, "e": 9891, "s": 9885, "text": "Table" }, { "code": null, "e": 9935, "s": 9891, "text": "This can be done using pagingToolbar() as −" }, { "code": null, "e": 10183, "s": 9935, "text": "new Ext.PagingToolbar ({\n pageSize: 25,\n store: store,\n displayInfo: true,\n displayMsg: 'Displaying topics {0} - {1} of {2}',\n emptyMsg: 'No topics to display',\n});\n// trigger the data store load\nstore.load({params:{start:0, limit:25}});" }, { "code": null, "e": 10349, "s": 10183, "text": "dockedItems: [{\n xtype: 'toolbar',\n items: [{ \n id:'buttonId', \n handler: function() { \n Ext.Msg.alert('title','alertMsg');\n });\n }]\n}]\t" }, { "code": null, "e": 10575, "s": 10349, "text": "Loadmask is used to prevent any other operation by showing loading(or Custom message) to the user until data gets rendered to the grid. Loadmask: true; is the property to show loadmask while data getting rendered to the grid." }, { "code": null, "e": 10742, "s": 10575, "text": "Renderer is used when we want to manipulate the data which we get from store to show manipulated data based on some criteria. It is a column property can be used as −" }, { "code": null, "e": 10837, "s": 10742, "text": "renderer: function(value, metadata, record, rowIndex, colIndex, store){\n// logic to perform\n} " }, { "code": null, "e": 10866, "s": 10837, "text": "Ext.getCmp('id').getValue();" }, { "code": null, "e": 10880, "s": 10866, "text": "Hidden: true;" }, { "code": null, "e": 10919, "s": 10880, "text": "Sortable: true; which is default true." }, { "code": null, "e": 11142, "s": 10919, "text": "grid.getStore().on ({\n beforeload : function(store) {\n // perform some operation\n },\n load : {\n fn : function(store) {\n //perform some operation\n },\n scope : this\n }\n store.load();\n});" }, { "code": null, "e": 11263, "s": 11142, "text": "Ext JS 6 has toolkit package with which it can include visual elements of both the frameworks (Ext JS and Sencha Touch)." }, { "code": null, "e": 11284, "s": 11263, "text": "It can be added as −" }, { "code": null, "e": 11322, "s": 11284, "text": "'toolkit': 'classic', // or 'modern'" }, { "code": null, "e": 11394, "s": 11322, "text": "If toolkit is classic it includes Ext JS desktop application framework." }, { "code": null, "e": 11479, "s": 11394, "text": "And if toolkit is modern then it includes sencha touch mobile application framework." }, { "code": null, "e": 11766, "s": 11479, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 12096, "s": 11766, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 12103, "s": 12096, "text": " Print" }, { "code": null, "e": 12114, "s": 12103, "text": " Add Notes" } ]
10 Jupyter Lab Extensions to Boost Your Productivity | by Christopher Tao | Towards Data Science
If you are a Data Scientist or a Data Engineer using Python as your primary programming language, I believe you must use Jupyter Notebook. As the “next-generation” web-based application for Jupyter Notebook, Jupyter Lab provides much more convenient features than its old bother. One of them is the extensions. Now, even the Jupyter Lab development team is excited to have such a robust and thrive third-party extension community. In this article, I’ll introduce 10 Jupyter Lab extensions that I found are very useful to dramatically improve the productivity of a typical data scientist or data engineer. Most of the online resource will tell you to run the command like the following to install a Jupyter Lab extension. jupyter labextension install @jupyterlab/... Well, using the command line is also my favourite. However, if you are a user of VS Code, Sublime or Atom, you might also want to directly search what you want to install in a “manager”. Jupyter Lab does provide this feature. As shown in the screenshot, you can go to the 4th tab on the left navigation, which is the extension manager. Then, you can search whatever you want to get the right extension for your needs. So, you don’t even need to know the extension beforehand. Now, let’s have a look at what are the recommended extensions! blog.jupyter.org We all love Jupyter because of its interactive. However, sometimes, the debugging feature is necessary for coding. For example, we may want to run a for-loop step by step to see what is exactly happening inside. Most of the IDE tools supports this debugging feature with “step over” and “ step into”, but unfortunately not in Jupyter naturally. @jupyterlab/debugger is such an extension allows us to supplement this missing feature in Jupyter Lab. github.com Have a long notebook? Want to make your notebook more beautiful for a presentation? Or, Just want to have a table of content for your notebook? @jupyterlab/toc comes to help. With this extension, the table of content will be automatically generated based on the markdown cells with headings (make sure use the sharp signs ## to specify your heading levels). This is also a good manner of using Jupyter Notebook that makes your work more systematic and organised. github.com Diagram.net (formerly Draw.IO) is my favourite tool for drawing diagrams. If you are one of my followers, I can tell you that most of the diagrams in my articles are drawn using this. It is indeed a perfect open-source alternative to MS Visio. Now, with jupyterlab-drawio, we can bring this perfect tool on Jupyter Lab. Please go check it out an enjoy drawing :) github.com One of the amazing features of Jupyter Notebook/Lab is that it provides lots of useful magic commands. For example, we can use %timeit to test how long our code will take for running. It will run our code snippet hundreds or thousands of times and get the average to make sure to give a fair and accurate result. However, sometimes we don’t need it to be such scientific. Also, it would be good to know how much time for each cell for running. In this case, it is absolutely overkilling to use %timeit for every cell. jupyterlab-execute-time can help in this case. As shown in the screenshot, it shows not only the elapse time of executing the cell, but also the last executed time. I promise you that this is a very convenient feature to indicate the order of your execution for those cells. github.com As a Data Scientist or Data Engineer, you must have to deal with spreadsheets sometimes. However, Jupyter does not natively support to read Excel files, which forces us to open multiple tools to switch between the Jupyter for coding and Excel for viewing. jupyterlab-spreadsheet solves this problem perfectly. It embedded the xls/xlsx spreadsheet viewing feature in the Jupyter Lab, so we can have all we need in a single place. github.com Python is not an execution effective programming language, which means that it may consume more CPU/memory resources compare the others. Also, one of the most common use cases for Python is Data Science. Therefore, we might want to monitor our system hardware resource to be aware that our Python code may freeze the operating system. jupyterlab-topbar-extension is the extension you may want to have. It will display the CPU and memory usage on a top bar of the Jupyter Lab UI so that we can monitor them in real-time. github.com While I love Jupyter, it does not do the code auto-completion as well as the other classic IDE tools do. The code auto-completion is very limited and slow. You may ever hear of Kite, which is a free AI-powered code completion service. It is available in almost all the popular IDEs such as Sublime, VS Code and PyCharm. In fact, you can use this service in Jupyter Lab, too. With this extension, we can code in Jupyter Lab more fluently. github.com If you are a Data Scientist who were switched from R studio or Matlab, you might be very familiar with the variables inspector that these tools provided. This feature is unfortunately not available in Jupyter Lab by default. However, the extension jupyterlab-variableInspector brings this feature back to it. github.com Matplotlib is a must-learn Python library if you are a Data Scientist. It is a basic but powerful tool for Data Visualisation in Python. However, when we use Jupyter Lab, the interactive feature has gone. The jupyter-matplotlib extension can make your Matplotlib interactive again. Simply enable it using a magic command %matplotlib widget, your fancy 3D chart will become interactive. plotly.com While Matplotlib is the most basic and powerful library for Data Visualisation, Plotly is my favourite library in this area. It wrapped many common charts that we can generate amazing charts in a few lines of code. To make Jupyter Lab seamlessly support and be able to display interactive Plotly charts, jupyterlab-plotly needs to be installed. Of course, there are much more wonderful Jupyter Lab extensions available in the community. In this article, I have introduced 10 of them based on my preferences. These extensions help me to improve my productivity a lot in the past several years, and now I recommend them to you! medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 483, "s": 172, "text": "If you are a Data Scientist or a Data Engineer using Python as your primary programming language, I believe you must use Jupyter Notebook. As the “next-generation” web-based application for Jupyter Notebook, Jupyter Lab provides much more convenient features than its old bother. One of them is the extensions." }, { "code": null, "e": 777, "s": 483, "text": "Now, even the Jupyter Lab development team is excited to have such a robust and thrive third-party extension community. In this article, I’ll introduce 10 Jupyter Lab extensions that I found are very useful to dramatically improve the productivity of a typical data scientist or data engineer." }, { "code": null, "e": 893, "s": 777, "text": "Most of the online resource will tell you to run the command like the following to install a Jupyter Lab extension." }, { "code": null, "e": 938, "s": 893, "text": "jupyter labextension install @jupyterlab/..." }, { "code": null, "e": 1164, "s": 938, "text": "Well, using the command line is also my favourite. However, if you are a user of VS Code, Sublime or Atom, you might also want to directly search what you want to install in a “manager”. Jupyter Lab does provide this feature." }, { "code": null, "e": 1414, "s": 1164, "text": "As shown in the screenshot, you can go to the 4th tab on the left navigation, which is the extension manager. Then, you can search whatever you want to get the right extension for your needs. So, you don’t even need to know the extension beforehand." }, { "code": null, "e": 1477, "s": 1414, "text": "Now, let’s have a look at what are the recommended extensions!" }, { "code": null, "e": 1494, "s": 1477, "text": "blog.jupyter.org" }, { "code": null, "e": 1839, "s": 1494, "text": "We all love Jupyter because of its interactive. However, sometimes, the debugging feature is necessary for coding. For example, we may want to run a for-loop step by step to see what is exactly happening inside. Most of the IDE tools supports this debugging feature with “step over” and “ step into”, but unfortunately not in Jupyter naturally." }, { "code": null, "e": 1942, "s": 1839, "text": "@jupyterlab/debugger is such an extension allows us to supplement this missing feature in Jupyter Lab." }, { "code": null, "e": 1953, "s": 1942, "text": "github.com" }, { "code": null, "e": 2128, "s": 1953, "text": "Have a long notebook? Want to make your notebook more beautiful for a presentation? Or, Just want to have a table of content for your notebook? @jupyterlab/toc comes to help." }, { "code": null, "e": 2416, "s": 2128, "text": "With this extension, the table of content will be automatically generated based on the markdown cells with headings (make sure use the sharp signs ## to specify your heading levels). This is also a good manner of using Jupyter Notebook that makes your work more systematic and organised." }, { "code": null, "e": 2427, "s": 2416, "text": "github.com" }, { "code": null, "e": 2671, "s": 2427, "text": "Diagram.net (formerly Draw.IO) is my favourite tool for drawing diagrams. If you are one of my followers, I can tell you that most of the diagrams in my articles are drawn using this. It is indeed a perfect open-source alternative to MS Visio." }, { "code": null, "e": 2790, "s": 2671, "text": "Now, with jupyterlab-drawio, we can bring this perfect tool on Jupyter Lab. Please go check it out an enjoy drawing :)" }, { "code": null, "e": 2801, "s": 2790, "text": "github.com" }, { "code": null, "e": 3114, "s": 2801, "text": "One of the amazing features of Jupyter Notebook/Lab is that it provides lots of useful magic commands. For example, we can use %timeit to test how long our code will take for running. It will run our code snippet hundreds or thousands of times and get the average to make sure to give a fair and accurate result." }, { "code": null, "e": 3319, "s": 3114, "text": "However, sometimes we don’t need it to be such scientific. Also, it would be good to know how much time for each cell for running. In this case, it is absolutely overkilling to use %timeit for every cell." }, { "code": null, "e": 3366, "s": 3319, "text": "jupyterlab-execute-time can help in this case." }, { "code": null, "e": 3594, "s": 3366, "text": "As shown in the screenshot, it shows not only the elapse time of executing the cell, but also the last executed time. I promise you that this is a very convenient feature to indicate the order of your execution for those cells." }, { "code": null, "e": 3605, "s": 3594, "text": "github.com" }, { "code": null, "e": 3861, "s": 3605, "text": "As a Data Scientist or Data Engineer, you must have to deal with spreadsheets sometimes. However, Jupyter does not natively support to read Excel files, which forces us to open multiple tools to switch between the Jupyter for coding and Excel for viewing." }, { "code": null, "e": 4034, "s": 3861, "text": "jupyterlab-spreadsheet solves this problem perfectly. It embedded the xls/xlsx spreadsheet viewing feature in the Jupyter Lab, so we can have all we need in a single place." }, { "code": null, "e": 4045, "s": 4034, "text": "github.com" }, { "code": null, "e": 4380, "s": 4045, "text": "Python is not an execution effective programming language, which means that it may consume more CPU/memory resources compare the others. Also, one of the most common use cases for Python is Data Science. Therefore, we might want to monitor our system hardware resource to be aware that our Python code may freeze the operating system." }, { "code": null, "e": 4565, "s": 4380, "text": "jupyterlab-topbar-extension is the extension you may want to have. It will display the CPU and memory usage on a top bar of the Jupyter Lab UI so that we can monitor them in real-time." }, { "code": null, "e": 4576, "s": 4565, "text": "github.com" }, { "code": null, "e": 4732, "s": 4576, "text": "While I love Jupyter, it does not do the code auto-completion as well as the other classic IDE tools do. The code auto-completion is very limited and slow." }, { "code": null, "e": 4951, "s": 4732, "text": "You may ever hear of Kite, which is a free AI-powered code completion service. It is available in almost all the popular IDEs such as Sublime, VS Code and PyCharm. In fact, you can use this service in Jupyter Lab, too." }, { "code": null, "e": 5014, "s": 4951, "text": "With this extension, we can code in Jupyter Lab more fluently." }, { "code": null, "e": 5025, "s": 5014, "text": "github.com" }, { "code": null, "e": 5334, "s": 5025, "text": "If you are a Data Scientist who were switched from R studio or Matlab, you might be very familiar with the variables inspector that these tools provided. This feature is unfortunately not available in Jupyter Lab by default. However, the extension jupyterlab-variableInspector brings this feature back to it." }, { "code": null, "e": 5345, "s": 5334, "text": "github.com" }, { "code": null, "e": 5550, "s": 5345, "text": "Matplotlib is a must-learn Python library if you are a Data Scientist. It is a basic but powerful tool for Data Visualisation in Python. However, when we use Jupyter Lab, the interactive feature has gone." }, { "code": null, "e": 5731, "s": 5550, "text": "The jupyter-matplotlib extension can make your Matplotlib interactive again. Simply enable it using a magic command %matplotlib widget, your fancy 3D chart will become interactive." }, { "code": null, "e": 5742, "s": 5731, "text": "plotly.com" }, { "code": null, "e": 5957, "s": 5742, "text": "While Matplotlib is the most basic and powerful library for Data Visualisation, Plotly is my favourite library in this area. It wrapped many common charts that we can generate amazing charts in a few lines of code." }, { "code": null, "e": 6087, "s": 5957, "text": "To make Jupyter Lab seamlessly support and be able to display interactive Plotly charts, jupyterlab-plotly needs to be installed." }, { "code": null, "e": 6368, "s": 6087, "text": "Of course, there are much more wonderful Jupyter Lab extensions available in the community. In this article, I have introduced 10 of them based on my preferences. These extensions help me to improve my productivity a lot in the past several years, and now I recommend them to you!" }, { "code": null, "e": 6379, "s": 6368, "text": "medium.com" } ]
GDB - Debugging Symbols
A Debugging Symbol Table maps instructions in the compiled binary program to their corresponding variable, function, or line in the source code. This mapping could be something like: Program instruction ⇒ item name, item type, original file, line number defined. Program instruction ⇒ item name, item type, original file, line number defined. Symbol tables may be embedded into the program or stored as a separate file. So if you plan to debug your program, then it is required to create a symbol table which will have the required information to debug the program. We can infer the following facts about symbol tables: A symbol table works for a particular version of the program – if the program changes, a new table must be created. A symbol table works for a particular version of the program – if the program changes, a new table must be created. Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information. Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information. If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author. If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author. To let GDB be able to read all that information line by line from the symbol table, we need to compile it a bit differently. Normally we compile our programs as: gcc hello.cc -o hello Instead of doing this, we need to compile with the -g flag as shown below: gcc -g hello.cc -o hello Print Add Notes Bookmark this page
[ { "code": null, "e": 1892, "s": 1709, "text": "A Debugging Symbol Table maps instructions in the compiled binary program to their corresponding variable, function, or line in the source code. This mapping could be something like:" }, { "code": null, "e": 1972, "s": 1892, "text": "Program instruction ⇒ item name, item type, original file, line number defined." }, { "code": null, "e": 2052, "s": 1972, "text": "Program instruction ⇒ item name, item type, original file, line number defined." }, { "code": null, "e": 2275, "s": 2052, "text": "Symbol tables may be embedded into the program or stored as a separate file. So if you plan to debug your program, then it is required to create a symbol table which will have the required information to debug the program." }, { "code": null, "e": 2329, "s": 2275, "text": "We can infer the following facts about symbol tables:" }, { "code": null, "e": 2445, "s": 2329, "text": "A symbol table works for a particular version of the program – if the program changes, a new table must be created." }, { "code": null, "e": 2561, "s": 2445, "text": "A symbol table works for a particular version of the program – if the program changes, a new table must be created." }, { "code": null, "e": 2705, "s": 2561, "text": "Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information." }, { "code": null, "e": 2849, "s": 2705, "text": "Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information." }, { "code": null, "e": 2965, "s": 2849, "text": "If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author." }, { "code": null, "e": 3081, "s": 2965, "text": "If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author." }, { "code": null, "e": 3243, "s": 3081, "text": "To let GDB be able to read all that information line by line from the symbol table, we need to compile it a bit differently. Normally we compile our programs as:" }, { "code": null, "e": 3267, "s": 3243, "text": "gcc hello.cc -o hello \n" }, { "code": null, "e": 3342, "s": 3267, "text": "Instead of doing this, we need to compile with the -g flag as shown below:" }, { "code": null, "e": 3369, "s": 3342, "text": "gcc -g hello.cc -o hello \n" }, { "code": null, "e": 3376, "s": 3369, "text": " Print" }, { "code": null, "e": 3387, "s": 3376, "text": " Add Notes" } ]
How to Run a Cron Job Every Day on a Linux System
This article will teach you on, how to schedule a corn job for executing a script or command or shell script at a particular time every day. As a system administrator, we know the importance of running the routine maintenance jobs in the background automatically. The Linux corn utility will help us to maintain these jobs to run in the background. MIN HOUR Day of month Month Day of Week Command 0-59 0-23 1-31 1-12 0-6 Any Linux command or script To see a list of cron jobs which exists on the machine, run the below command – # crontab -l no crontab for root To add the new cron job run the below command – #crontab -e no crontab for root - using an empty one Select an editor. To change later, run 'select-editor'. 1. /bin/ed 2. /bin/nano <---- easiest 3. /usr/bin/vim.basic 4. /usr/bin/vim.tiny Choose 1-4 [2]:2 # Edit this file to introduce tasks to be run by cron. # # Each task to run has to be defined through a single line # indicating with different fields when the task will be run # and what command to run for the task # # To define the time you can provide concrete values for # minute (m), hour (h), day of month (dom), month (mon), # and day of week (dow) or use '*' in these fields (for 'any').# # Notice that tasks will be started based on the cron's system # daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through # email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command Add the below example to execute the specified log backup shell script at 11:00 on every day. We can specify the comma-separated value in a field specifies that the script needs to be executed in all the mentioned time. 00 11 * * * /home/backups/scripts/log_backup.sh Conclusion: At the end of the configuration you are able to run a script or command at a specific time every day, like this we can specify the time for multiple execution with comma separated values.
[ { "code": null, "e": 1411, "s": 1062, "text": "This article will teach you on, how to schedule a corn job for executing a script or command or shell script at a particular time every day. As a system administrator, we know the importance of running the routine maintenance jobs in the background automatically. The Linux corn utility will help us to maintain these jobs to run in the background." }, { "code": null, "e": 1511, "s": 1411, "text": "MIN HOUR Day of month Month Day of Week Command\n0-59 0-23 1-31 1-12 0-6 Any Linux command or script" }, { "code": null, "e": 1591, "s": 1511, "text": "To see a list of cron jobs which exists on the machine, run the below command –" }, { "code": null, "e": 1624, "s": 1591, "text": "# crontab -l\nno crontab for root" }, { "code": null, "e": 1672, "s": 1624, "text": "To add the new cron job run the below command –" }, { "code": null, "e": 2757, "s": 1672, "text": "#crontab -e\nno crontab for root - using an empty one\nSelect an editor. To change later, run 'select-editor'.\n1. /bin/ed\n2. /bin/nano <---- easiest\n3. /usr/bin/vim.basic\n4. /usr/bin/vim.tiny\nChoose 1-4 [2]:2\n# Edit this file to introduce tasks to be run by cron.\n#\n# Each task to run has to be defined through a single line\n# indicating with different fields when the task will be run\n# and what command to run for the task\n#\n# To define the time you can provide concrete values for\n# minute (m), hour (h), day of month (dom), month (mon),\n# and day of week (dow) or use '*' in these fields (for 'any').#\n# Notice that tasks will be started based on the cron's system\n# daemon's notion of time and timezones.\n#\n# Output of the crontab jobs (including errors) is sent through\n# email to the user the crontab file belongs to (unless redirected).\n#\n# For example, you can run a backup of all your user accounts\n# at 5 a.m every week with:\n# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/\n#\n# For more information see the manual pages of crontab(5) and cron(8)\n#\n# m h dom mon dow command" }, { "code": null, "e": 2977, "s": 2757, "text": "Add the below example to execute the specified log backup shell script at 11:00 on every day. We can specify the comma-separated value in a field specifies that the script needs to be executed in all the mentioned time." }, { "code": null, "e": 3025, "s": 2977, "text": "00 11 * * * /home/backups/scripts/log_backup.sh" }, { "code": null, "e": 3225, "s": 3025, "text": "Conclusion: At the end of the configuration you are able to run a script or command at a specific time every day, like this we can specify the time for multiple execution with comma separated values." } ]
Ruby/TK - Text Widget
A Text widget provides users with an area so that they can enter multiple lines of text. Text widgets are part of the classic Tk widgets, not the themed Tk widgets. Text widgets support three different kinds of annotations on the text − Tags − Allow different portions of the text to be displayed with different fonts and colors. In addition, Tcl commands can be associated with tags so that scripts are invoked when particular actions such as keystrokes and mouse button presses occur in particular ranges of the text. Tags − Allow different portions of the text to be displayed with different fonts and colors. In addition, Tcl commands can be associated with tags so that scripts are invoked when particular actions such as keystrokes and mouse button presses occur in particular ranges of the text. Marks − The second form of annotation consists of marks, which are floating markers in the text. Marks are used to keep track of various interesting positions in the text as it is edited. Marks − The second form of annotation consists of marks, which are floating markers in the text. Marks are used to keep track of various interesting positions in the text as it is edited. Embedded windows − The third form of annotation allows arbitrary windows to be embedded in a text widget. Embedded windows − The third form of annotation allows arbitrary windows to be embedded in a text widget. A label can display a textual string, bitmap or image. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wraplength option) and one of the characters may optionally be underlined using the underline option. Here is a simple syntax to create this widget − TkText.new(root) { .....Standard Options.... .....Widget-specific Options.... } background borderwidth cursor exportselection font foreground highlightbackground highlightcolor highlightthickness insertbackground insertborderwidth insertofftime insertontime insertwidth padx pady relief selectbackground selectborderwidth selectforeground setgrid takefocus xscrollcommand yscrollcommand These options have been described in previous chapter. height => Integer Specifies the desired height for the window, in units of characters. Must be at least one. spacing1 => Integer Requests additional space above each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the first line on the display. This option may be overriden with spacing1 options in tags. spacing2 => Integer For lines that wrap (so that they cover more than one line on the display) this option specifies additional space to provide between the display lines that represent a single line of text. The value may have any of the standard forms for screen distances. This option may be overriden with spacing options in tags. spacing3 => Integer Requests additional space below each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the last line on the display. This option may be overriden with spacing3 options in tags. state => String Specifies one of two states for the text: normal or disabled. If the text is disabled then characters may not be inserted or deleted and no insertion cursor will be displayed, even if the input focus is in the widget. tabs => String Specifies a set of tab stops for the window. The option's value consists of a list of screen distances giving the positions of the tab stops. Each position may optionally be followed in the next list element by one of the keywords left, right, center, or numeric, which specifies how to justify text relative to the tab stop. Left is the default. width => Integer Specifies the desired width for the window in units of characters. If the font doesn't have a uniform width then the width of the character "0" is used in translating from character units to screen units. wrap => String Specifies how to handle lines in the text that are too long to be displayed in a single line of the text's window. The value must be none or char or word. The following useful methods are available to manipulate the content of a text − delete(index1, ?index2?) − Deletes a range of characters from the text. If both index1 and index2 are specified, then deletes all the characters starting with the one given by index1 and stopping just before index2. If index2 doesn't specify a position later in the text than index1 then no characters are deleted. If index2 isn't specified then the single character at index1 is deleted. delete(index1, ?index2?) − Deletes a range of characters from the text. If both index1 and index2 are specified, then deletes all the characters starting with the one given by index1 and stopping just before index2. If index2 doesn't specify a position later in the text than index1 then no characters are deleted. If index2 isn't specified then the single character at index1 is deleted. get(index1, ?index2?) − Returns a range of characters from the text. The return value will be all the characters in the text starting with the one whose index is index1 and ending just before the one whose index is index2 (the character at index2 will not be returned). If index2 is omitted then the single character at index1 is returned. get(index1, ?index2?) − Returns a range of characters from the text. The return value will be all the characters in the text starting with the one whose index is index1 and ending just before the one whose index is index2 (the character at index2 will not be returned). If index2 is omitted then the single character at index1 is returned. index(index) − Returns the position corresponding to index in the form line.char where line is the line number and char is the character number. index(index) − Returns the position corresponding to index in the form line.char where line is the line number and char is the character number. insert(index, chars, ?tagList, chars, tagList, ...?) − Inserts all of the chars arguments just before the character at index. If index refers to the end of the text (the character after the last newline) then the new text is inserted just before the last newline instead. If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text. If tagList is specified then it consists of a list of tag names; the new characters will receive all of the tags in this list and no others, regardless of the tags present around the insertion point. If multiple chars-tagList argument pairs are present, they produce the same effect as if a separate insert widget command had been issued for each pair, in order. The last tagList argument may be omitted. insert(index, chars, ?tagList, chars, tagList, ...?) − Inserts all of the chars arguments just before the character at index. If index refers to the end of the text (the character after the last newline) then the new text is inserted just before the last newline instead. If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text. If tagList is specified then it consists of a list of tag names; the new characters will receive all of the tags in this list and no others, regardless of the tags present around the insertion point. If multiple chars-tagList argument pairs are present, they produce the same effect as if a separate insert widget command had been issued for each pair, in order. The last tagList argument may be omitted. xview(option, args) − This command is used to query and change the horizontal position of the text in the widget's window. xview(option, args) − This command is used to query and change the horizontal position of the text in the widget's window. yview(?args?) − This command is used to query and change the vertical position of the text in the widget's window. yview(?args?) − This command is used to query and change the vertical position of the text in the widget's window. Ruby/Tk automatically creates class bindings for texts. Here are few important bindings listed. Clicking mouse button 1 positions the insertion cursor just before the character underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Dragging with mouse button 1 strokes out a selection between the insertion cursor and the character under the mouse. Clicking mouse button 1 positions the insertion cursor just before the character underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Dragging with mouse button 1 strokes out a selection between the insertion cursor and the character under the mouse. Double-clicking with mouse button 1 selects the word under the mouse and positions the insertion cursor at the beginning of the word. Dragging after a double click will stroke out a selection consisting of whole words. Double-clicking with mouse button 1 selects the word under the mouse and positions the insertion cursor at the beginning of the word. Dragging after a double click will stroke out a selection consisting of whole words. Triple-clicking with mouse button 1 selects the line under the mouse and positions the insertion cursor at the beginning of the line. Dragging after a triple click will stroke out a selection consisting of whole lines. Triple-clicking with mouse button 1 selects the line under the mouse and positions the insertion cursor at the beginning of the line. Dragging after a triple click will stroke out a selection consisting of whole lines. Clicking mouse button 1 with the Control key down will reposition the insertion cursor without affecting the selection. Clicking mouse button 1 with the Control key down will reposition the insertion cursor without affecting the selection. The Left and Right keys move the insertion cursor one character to the left or right; they also clear any selection in the text. The Left and Right keys move the insertion cursor one character to the left or right; they also clear any selection in the text. The Up and Down keys move the insertion cursor one line up or down and clear any selection in the text. If Up or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character. The Up and Down keys move the insertion cursor one line up or down and clear any selection in the text. If Up or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character. Control-x deletes whatever is selected in the text widget. Control-x deletes whatever is selected in the text widget. Control-o opens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor. Control-o opens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor. Control-d deletes the character to the right of the insertion cursor. Control-d deletes the character to the right of the insertion cursor. require 'tk' root = TkRoot.new root.title = "Window" text = TkText.new(root) do width 30 height 20 borderwidth 1 font TkFont.new('times 12 bold') pack("side" => "right", "padx"=> "5", "pady"=> "5") end text.insert 'end', "Hello!\n\ntext widget example" Tk.mainloop This will produce the following result − 46 Lectures 9.5 hours Eduonix Learning Solutions 97 Lectures 7.5 hours Skillbakerystudios 227 Lectures 40 hours YouAccel 19 Lectures 10 hours Programming Line 51 Lectures 5 hours Stone River ELearning 39 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2459, "s": 2294, "text": "A Text widget provides users with an area so that they can enter multiple lines of text. Text widgets are part of the classic Tk widgets, not the themed Tk widgets." }, { "code": null, "e": 2531, "s": 2459, "text": "Text widgets support three different kinds of annotations on the text −" }, { "code": null, "e": 2814, "s": 2531, "text": "Tags − Allow different portions of the text to be displayed with different fonts and colors. In addition, Tcl commands can be associated with tags so that scripts are invoked when particular actions such as keystrokes and mouse button presses occur in particular ranges of the text." }, { "code": null, "e": 3097, "s": 2814, "text": "Tags − Allow different portions of the text to be displayed with different fonts and colors. In addition, Tcl commands can be associated with tags so that scripts are invoked when particular actions such as keystrokes and mouse button presses occur in particular ranges of the text." }, { "code": null, "e": 3285, "s": 3097, "text": "Marks − The second form of annotation consists of marks, which are floating markers in the text. Marks are used to keep track of various interesting positions in the text as it is edited." }, { "code": null, "e": 3473, "s": 3285, "text": "Marks − The second form of annotation consists of marks, which are floating markers in the text. Marks are used to keep track of various interesting positions in the text as it is edited." }, { "code": null, "e": 3579, "s": 3473, "text": "Embedded windows − The third form of annotation allows arbitrary windows to be embedded in a text widget." }, { "code": null, "e": 3685, "s": 3579, "text": "Embedded windows − The third form of annotation allows arbitrary windows to be embedded in a text widget." }, { "code": null, "e": 4006, "s": 3685, "text": "A label can display a textual string, bitmap or image. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wraplength option) and one of the characters may optionally be underlined using the underline option." }, { "code": null, "e": 4054, "s": 4006, "text": "Here is a simple syntax to create this widget −" }, { "code": null, "e": 4141, "s": 4054, "text": "TkText.new(root) {\n .....Standard Options....\n .....Widget-specific Options....\n}\n" }, { "code": null, "e": 4152, "s": 4141, "text": "background" }, { "code": null, "e": 4164, "s": 4152, "text": "borderwidth" }, { "code": null, "e": 4171, "s": 4164, "text": "cursor" }, { "code": null, "e": 4187, "s": 4171, "text": "exportselection" }, { "code": null, "e": 4192, "s": 4187, "text": "font" }, { "code": null, "e": 4203, "s": 4192, "text": "foreground" }, { "code": null, "e": 4223, "s": 4203, "text": "highlightbackground" }, { "code": null, "e": 4238, "s": 4223, "text": "highlightcolor" }, { "code": null, "e": 4257, "s": 4238, "text": "highlightthickness" }, { "code": null, "e": 4274, "s": 4257, "text": "insertbackground" }, { "code": null, "e": 4292, "s": 4274, "text": "insertborderwidth" }, { "code": null, "e": 4306, "s": 4292, "text": "insertofftime" }, { "code": null, "e": 4319, "s": 4306, "text": "insertontime" }, { "code": null, "e": 4331, "s": 4319, "text": "insertwidth" }, { "code": null, "e": 4336, "s": 4331, "text": "padx" }, { "code": null, "e": 4341, "s": 4336, "text": "pady" }, { "code": null, "e": 4348, "s": 4341, "text": "relief" }, { "code": null, "e": 4365, "s": 4348, "text": "selectbackground" }, { "code": null, "e": 4383, "s": 4365, "text": "selectborderwidth" }, { "code": null, "e": 4400, "s": 4383, "text": "selectforeground" }, { "code": null, "e": 4408, "s": 4400, "text": "setgrid" }, { "code": null, "e": 4418, "s": 4408, "text": "takefocus" }, { "code": null, "e": 4433, "s": 4418, "text": "xscrollcommand" }, { "code": null, "e": 4448, "s": 4433, "text": "yscrollcommand" }, { "code": null, "e": 4503, "s": 4448, "text": "These options have been described in previous chapter." }, { "code": null, "e": 4522, "s": 4503, "text": "height => Integer" }, { "code": null, "e": 4613, "s": 4522, "text": "Specifies the desired height for the window, in units of characters. Must be at least one." }, { "code": null, "e": 4634, "s": 4613, "text": "spacing1 => Integer" }, { "code": null, "e": 4886, "s": 4634, "text": "Requests additional space above each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the first line on the display. This option may be overriden with spacing1 options in tags." }, { "code": null, "e": 4907, "s": 4886, "text": "spacing2 => Integer" }, { "code": null, "e": 5222, "s": 4907, "text": "For lines that wrap (so that they cover more than one line on the display) this option specifies additional space to provide between the display lines that represent a single line of text. The value may have any of the standard forms for screen distances. This option may be overriden with spacing options in tags." }, { "code": null, "e": 5243, "s": 5222, "text": "spacing3 => Integer" }, { "code": null, "e": 5494, "s": 5243, "text": "Requests additional space below each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the last line on the display. This option may be overriden with spacing3 options in tags." }, { "code": null, "e": 5511, "s": 5494, "text": "state => String" }, { "code": null, "e": 5729, "s": 5511, "text": "Specifies one of two states for the text: normal or disabled. If the text is disabled then characters may not be inserted or deleted and no insertion cursor will be displayed, even if the input focus is in the widget." }, { "code": null, "e": 5745, "s": 5729, "text": "tabs => String" }, { "code": null, "e": 6092, "s": 5745, "text": "Specifies a set of tab stops for the window. The option's value consists of a list of screen distances giving the positions of the tab stops. Each position may optionally be followed in the next list element by one of the keywords left, right, center, or numeric, which specifies how to justify text relative to the tab stop. Left is the default." }, { "code": null, "e": 6111, "s": 6092, "text": "width => Integer" }, { "code": null, "e": 6316, "s": 6111, "text": "Specifies the desired width for the window in units of characters. If the font doesn't have a uniform width then the width of the character \"0\" is used in translating from character units to screen units." }, { "code": null, "e": 6332, "s": 6316, "text": "wrap => String" }, { "code": null, "e": 6488, "s": 6332, "text": "Specifies how to handle lines in the text that are too long to be displayed in a single line of the text's window. The value must be none or char or word. " }, { "code": null, "e": 6569, "s": 6488, "text": "The following useful methods are available to manipulate the content of a text −" }, { "code": null, "e": 6958, "s": 6569, "text": "delete(index1, ?index2?) − Deletes a range of characters from the text. If both index1 and index2 are specified, then deletes all the characters starting with the one given by index1 and stopping just before index2. If index2 doesn't specify a position later in the text than index1 then no characters are deleted. If index2 isn't specified then the single character at index1 is deleted." }, { "code": null, "e": 7347, "s": 6958, "text": "delete(index1, ?index2?) − Deletes a range of characters from the text. If both index1 and index2 are specified, then deletes all the characters starting with the one given by index1 and stopping just before index2. If index2 doesn't specify a position later in the text than index1 then no characters are deleted. If index2 isn't specified then the single character at index1 is deleted." }, { "code": null, "e": 7687, "s": 7347, "text": "get(index1, ?index2?) − Returns a range of characters from the text. The return value will be all the characters in the text starting with the one whose index is index1 and ending just before the one whose index is index2 (the character at index2 will not be returned). If index2 is omitted then the single character at index1 is returned." }, { "code": null, "e": 8027, "s": 7687, "text": "get(index1, ?index2?) − Returns a range of characters from the text. The return value will be all the characters in the text starting with the one whose index is index1 and ending just before the one whose index is index2 (the character at index2 will not be returned). If index2 is omitted then the single character at index1 is returned." }, { "code": null, "e": 8172, "s": 8027, "text": "index(index) − Returns the position corresponding to index in the form line.char where line is the line number and char is the character number." }, { "code": null, "e": 8317, "s": 8172, "text": "index(index) − Returns the position corresponding to index in the form line.char where line is the line number and char is the character number." }, { "code": null, "e": 9275, "s": 8317, "text": "insert(index, chars, ?tagList, chars, tagList, ...?) − Inserts all of the chars arguments just before the character at index. If index refers to the end of the text (the character after the last newline) then the new text is inserted just before the last newline instead. If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text. If tagList is specified then it consists of a list of tag names; the new characters will receive all of the tags in this list and no others, regardless of the tags present around the insertion point. If multiple chars-tagList argument pairs are present, they produce the same effect as if a separate insert widget command had been issued for each pair, in order. The last tagList argument may be omitted." }, { "code": null, "e": 10233, "s": 9275, "text": "insert(index, chars, ?tagList, chars, tagList, ...?) − Inserts all of the chars arguments just before the character at index. If index refers to the end of the text (the character after the last newline) then the new text is inserted just before the last newline instead. If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text. If tagList is specified then it consists of a list of tag names; the new characters will receive all of the tags in this list and no others, regardless of the tags present around the insertion point. If multiple chars-tagList argument pairs are present, they produce the same effect as if a separate insert widget command had been issued for each pair, in order. The last tagList argument may be omitted." }, { "code": null, "e": 10356, "s": 10233, "text": "xview(option, args) − This command is used to query and change the horizontal position of the text in the widget's window." }, { "code": null, "e": 10479, "s": 10356, "text": "xview(option, args) − This command is used to query and change the horizontal position of the text in the widget's window." }, { "code": null, "e": 10594, "s": 10479, "text": "yview(?args?) − This command is used to query and change the vertical position of the text in the widget's window." }, { "code": null, "e": 10709, "s": 10594, "text": "yview(?args?) − This command is used to query and change the vertical position of the text in the widget's window." }, { "code": null, "e": 10805, "s": 10709, "text": "Ruby/Tk automatically creates class bindings for texts. Here are few important bindings listed." }, { "code": null, "e": 11109, "s": 10805, "text": "Clicking mouse button 1 positions the insertion cursor just before the character underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Dragging with mouse button 1 strokes out a selection between the insertion cursor and the character under the mouse." }, { "code": null, "e": 11413, "s": 11109, "text": "Clicking mouse button 1 positions the insertion cursor just before the character underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Dragging with mouse button 1 strokes out a selection between the insertion cursor and the character under the mouse." }, { "code": null, "e": 11632, "s": 11413, "text": "Double-clicking with mouse button 1 selects the word under the mouse and positions the insertion cursor at the beginning of the word. Dragging after a double click will stroke out a selection consisting of whole words." }, { "code": null, "e": 11851, "s": 11632, "text": "Double-clicking with mouse button 1 selects the word under the mouse and positions the insertion cursor at the beginning of the word. Dragging after a double click will stroke out a selection consisting of whole words." }, { "code": null, "e": 12070, "s": 11851, "text": "Triple-clicking with mouse button 1 selects the line under the mouse and positions the insertion cursor at the beginning of the line. Dragging after a triple click will stroke out a selection consisting of whole lines." }, { "code": null, "e": 12289, "s": 12070, "text": "Triple-clicking with mouse button 1 selects the line under the mouse and positions the insertion cursor at the beginning of the line. Dragging after a triple click will stroke out a selection consisting of whole lines." }, { "code": null, "e": 12409, "s": 12289, "text": "Clicking mouse button 1 with the Control key down will reposition the insertion cursor without affecting the selection." }, { "code": null, "e": 12529, "s": 12409, "text": "Clicking mouse button 1 with the Control key down will reposition the insertion cursor without affecting the selection." }, { "code": null, "e": 12658, "s": 12529, "text": "The Left and Right keys move the insertion cursor one character to the left or right; they also clear any selection in the text." }, { "code": null, "e": 12787, "s": 12658, "text": "The Left and Right keys move the insertion cursor one character to the left or right; they also clear any selection in the text." }, { "code": null, "e": 13032, "s": 12787, "text": "The Up and Down keys move the insertion cursor one line up or down and clear any selection in the text. If Up or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character." }, { "code": null, "e": 13277, "s": 13032, "text": "The Up and Down keys move the insertion cursor one line up or down and clear any selection in the text. If Up or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character." }, { "code": null, "e": 13336, "s": 13277, "text": "Control-x deletes whatever is selected in the text widget." }, { "code": null, "e": 13395, "s": 13336, "text": "Control-x deletes whatever is selected in the text widget." }, { "code": null, "e": 13525, "s": 13395, "text": "Control-o opens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor." }, { "code": null, "e": 13655, "s": 13525, "text": "Control-o opens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor." }, { "code": null, "e": 13725, "s": 13655, "text": "Control-d deletes the character to the right of the insertion cursor." }, { "code": null, "e": 13795, "s": 13725, "text": "Control-d deletes the character to the right of the insertion cursor." }, { "code": null, "e": 14078, "s": 13795, "text": "require 'tk'\n\nroot = TkRoot.new\nroot.title = \"Window\"\n\ntext = TkText.new(root) do\n width 30\n height 20\n borderwidth 1\n font TkFont.new('times 12 bold')\n pack(\"side\" => \"right\", \"padx\"=> \"5\", \"pady\"=> \"5\")\nend\ntext.insert 'end', \"Hello!\\n\\ntext widget example\"\nTk.mainloop" }, { "code": null, "e": 14119, "s": 14078, "text": "This will produce the following result −" }, { "code": null, "e": 14154, "s": 14119, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 14182, "s": 14154, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14217, "s": 14182, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 14237, "s": 14217, "text": " Skillbakerystudios" }, { "code": null, "e": 14272, "s": 14237, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 14282, "s": 14272, "text": " YouAccel" }, { "code": null, "e": 14316, "s": 14282, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 14334, "s": 14316, "text": " Programming Line" }, { "code": null, "e": 14367, "s": 14334, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 14390, "s": 14367, "text": " Stone River ELearning" }, { "code": null, "e": 14425, "s": 14390, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14448, "s": 14425, "text": " Stone River ELearning" }, { "code": null, "e": 14455, "s": 14448, "text": " Print" }, { "code": null, "e": 14466, "s": 14455, "text": " Add Notes" } ]
Split a document by its subdocuments in MongoDB
To split a document by its subdocuments, use $unwind in MongoDB. Let us create a collection with documents − > db.demo276.insertOne({"Name":"Chris","Subjects":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e48f953dd099650a5401a51") } Display all documents from a collection with the help of find() method − > db.demo276.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB" ] } Following is the query to split a document by its subdocuments − > db.demo276.aggregate( [ { $unwind : "$Subjects" } ] ) This will produce the following output − { "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : "MySQL" } { "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : "MongoDB" }
[ { "code": null, "e": 1171, "s": 1062, "text": "To split a document by its subdocuments, use $unwind in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1329, "s": 1171, "text": "> db.demo276.insertOne({\"Name\":\"Chris\",\"Subjects\":[\"MySQL\",\"MongoDB\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e48f953dd099650a5401a51\")\n}" }, { "code": null, "e": 1402, "s": 1329, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1432, "s": 1402, "text": "> db.demo276.find().pretty();" }, { "code": null, "e": 1473, "s": 1432, "text": "This will produce the following output −" }, { "code": null, "e": 1601, "s": 1473, "text": "{\n \"_id\" : ObjectId(\"5e48f953dd099650a5401a51\"),\n \"Name\" : \"Chris\",\n \"Subjects\" : [\n \"MySQL\",\n \"MongoDB\"\n ]\n}" }, { "code": null, "e": 1666, "s": 1601, "text": "Following is the query to split a document by its subdocuments −" }, { "code": null, "e": 1722, "s": 1666, "text": "> db.demo276.aggregate( [ { $unwind : \"$Subjects\" } ] )" }, { "code": null, "e": 1763, "s": 1722, "text": "This will produce the following output −" }, { "code": null, "e": 1943, "s": 1763, "text": "{ \"_id\" : ObjectId(\"5e48f953dd099650a5401a51\"), \"Name\" : \"Chris\", \"Subjects\" : \"MySQL\" }\n{ \"_id\" : ObjectId(\"5e48f953dd099650a5401a51\"), \"Name\" : \"Chris\", \"Subjects\" : \"MongoDB\" }" } ]
Maven - Quick Guide
Maven is a project management and comprehension tool that provides developers a complete build lifecycle framework. Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle. In case of multiple development teams environment, Maven can set-up the way to work as per standards in a very short time. As most of the project setups are simple and reusable, Maven makes life of developer easy while creating reports, checks, build and testing automation setups. Maven provides developers ways to manage the following − Builds Documentation Reporting Dependencies SCMs Releases Distribution Mailing list To summarize, Maven simplifies and standardizes the project build process. It handles compilation, distribution, documentation, team collaboration and other tasks seamlessly. Maven increases reusability and takes care of most of the build related tasks. Maven was originally designed to simplify building processes in Jakarta Turbine project. There were several projects and each project contained slightly different ANT build files. JARs were checked into CVS. Apache group then developed Maven which can build multiple projects together, publish projects information, deploy projects, share JARs across several projects and help in collaboration of teams. The primary goal of Maven is to provide developer with the following − A comprehensive model for projects, which is reusable, maintainable, and easier to comprehend. A comprehensive model for projects, which is reusable, maintainable, and easier to comprehend. Plugins or tools that interact with this declarative model. Plugins or tools that interact with this declarative model. Maven project structure and contents are declared in an xml file, pom.xml, referred as Project Object Model (POM), which is the fundamental unit of the entire Maven system. In later chapters, we will explain POM in detail. Maven uses Convention over Configuration, which means developers are not required to create build process themselves. Developers do not have to mention each and every configuration detail. Maven provides sensible default behavior for projects. When a Maven project is created, Maven creates default project structure. Developer is only required to place files accordingly and he/she need not to define any configuration in pom.xml. As an example, following table shows the default values for project source code files, resource files and other configurations. Assuming, ${basedir} denotes the project location − In order to build the project, Maven provides developers with options to mention life-cycle goals and project dependencies (that rely on Maven plugin capabilities and on its default conventions). Much of the project management and build related tasks are maintained by Maven plugins. Developers can build any given Maven project without the need to understand how the individual plugins work. We will discuss Maven Plugins in detail in the later chapters. Simple project setup that follows best practices. Simple project setup that follows best practices. Consistent usage across all projects. Consistent usage across all projects. Dependency management including automatic updating. Dependency management including automatic updating. A large and growing repository of libraries. A large and growing repository of libraries. Extensible, with the ability to easily write plugins in Java or scripting languages. Extensible, with the ability to easily write plugins in Java or scripting languages. Instant access to new features with little or no extra configuration. Instant access to new features with little or no extra configuration. Model-based builds − Maven is able to build any number of projects into predefined output types such as jar, war, metadata. Model-based builds − Maven is able to build any number of projects into predefined output types such as jar, war, metadata. Coherent site of project information − Using the same metadata as per the build process, maven is able to generate a website and a PDF including complete documentation. Coherent site of project information − Using the same metadata as per the build process, maven is able to generate a website and a PDF including complete documentation. Release management and distribution publication − Without additional configuration, maven will integrate with your source control system such as CVS and manages the release of a project. Release management and distribution publication − Without additional configuration, maven will integrate with your source control system such as CVS and manages the release of a project. Backward Compatibility − You can easily port the multiple modules of a project into Maven 3 from older versions of Maven. It can support the older versions also. Backward Compatibility − You can easily port the multiple modules of a project into Maven 3 from older versions of Maven. It can support the older versions also. Automatic parent versioning − No need to specify the parent in the sub module for maintenance. Automatic parent versioning − No need to specify the parent in the sub module for maintenance. Parallel builds − It analyzes the project dependency graph and enables you to build schedule modules in parallel. Using this, you can achieve the performance improvements of 20-50%. Parallel builds − It analyzes the project dependency graph and enables you to build schedule modules in parallel. Using this, you can achieve the performance improvements of 20-50%. Better Error and Integrity Reporting − Maven improved error reporting, and it provides you with a link to the Maven wiki page where you will get full description of the error. Better Error and Integrity Reporting − Maven improved error reporting, and it provides you with a link to the Maven wiki page where you will get full description of the error. First of all, open the console and execute a java command based on the operating system you are working on. Let's verify the output for all the operating systems − java 11.0.11 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) java 11.0.11 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) java 11.0.11 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link http://www.oracle.com. We are assuming Java 11.0.11 as the installed version for this tutorial. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example. Append Java compiler location to the System Path. Verify Java installation using the command java -version as explained above. Download Maven 3.8.4 from https://maven.apache.org/download.cgi. Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-3.8.4 will be created from the archive. Add M2_HOME, M2, MAVEN_OPTS to environment variables. Set the environment variables using system properties. M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 M2=%M2_HOME%\bin MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin export MAVEN_OPTS=-Xms256m -Xmx512m Now append M2 variable to System Path. Now open console and execute the following mvn command. Finally, verify the output of the above commands, which should be as follows − Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.8.4 Java version: 11.0.11, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk11.0.11\ Default locale: en_IN, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /usr/local/java-current/jre Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Java version: 11.0.11 Java home: /Library/Java/Home/jre POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml. The POM contains information about the project and various configuration detail used by Maven to build the project(s). POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are following − project dependencies plugins goals build profiles project version developers mailing list Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its version as these attributes help in uniquely identifying the project in repository. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.project-group</groupId> <artifactId>project</artifactId> <version>1.0</version> </project> It should be noted that there should be a single POM file for each project. All POM files require the project element and three mandatory fields: groupId, artifactId, version. All POM files require the project element and three mandatory fields: groupId, artifactId, version. Projects notation in repository is groupId:artifactId:version. Projects notation in repository is groupId:artifactId:version. Minimal requirements for a POM − Minimal requirements for a POM − Project root This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification. Model version Model version should be 4.0.0. groupId This is an Id of project's group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects. artifactId This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact's location within the repository. version This is the version of the project. Along with the groupId, It is used within an artifact's repository to separate versions from each other. For example − com.company.bank:consumer-banking:1.0 com.company.bank:consumer-banking:1.1. The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default. Maven use the effective POM (configuration from super pom plus project configuration) to execute relevant goal. It helps developers to specify minimum configuration detail in his/her pom.xml. Although configurations can be overridden easily. An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom. In example below, We've created a pom.xml in C:\MVN\project folder. Now open command console, go the folder containing pom.xml and execute the following mvn command. C:\MVN\project>mvn help:effective-pom Maven will start processing and display the effective-pom. C:\MVN>mvn help:effective-pom [INFO] Scanning for projects... [INFO] [INFO] ---------------< com.companyname.project-group:project >---------------- [INFO] Building project 1.0 [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ project --- [INFO] Effective POMs, after inheritance, interpolation, and profiles are applied: [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.261 s [INFO] Finished at: 2021-12-10T19:54:53+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> Effective POM displayed as result in console, after inheritance, interpolation, and profiles are applied. <?xml version="1.0" encoding="Cp1252"?> <!-- ====================================================================== --> <!-- --> <!-- Generated by Maven Help Plugin on 2021-12-10T19:54:52+05:30 --> <!-- See: http://maven.apache.org/plugins/maven-help-plugin/ --> <!-- --> <!-- ====================================================================== --> <!-- ====================================================================== --> <!-- --> <!-- Effective POM for project --> <!-- 'com.companyname.project-group:project:jar:1.0' --> <!-- --> <!-- ====================================================================== --> <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.companyname.project-group</groupId> <artifactId>project</artifactId> <version>1.0</version> <repositories> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>Central Repository</name> <url>https://repo.maven.apache.org/maven2</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <releases> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>Central Repository</name> <url>https://repo.maven.apache.org/maven2</url> </pluginRepository> </pluginRepositories> <build> <sourceDirectory>C:\MVN\src\main\java</sourceDirectory> <scriptSourceDirectory>C:\MVN\src\main\scripts</scriptSourceDirectory> <testSourceDirectory>C:\MVN\src\test\java</testSourceDirectory> <outputDirectory>C:\MVN\target\classes</outputDirectory> <testOutputDirectory>C:\MVN\target\test-classes</testOutputDirectory> <resources> <resource> <directory>C:\MVN\src\main\resources</directory> </resource> </resources> <testResources> <testResource> <directory>C:\MVN\src\test\resources</directory> </testResource> </testResources> <directory>C:\MVN\target</directory> <finalName>project-1.0</finalName> <pluginManagement> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.3</version> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-5</version> </plugin> <plugin> <artifactId>maven-dependency-plugin</artifactId> <version>2.8</version> </plugin> <plugin> <artifactId>maven-release-plugin</artifactId> <version>2.5.3</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>2.5</version> <executions> <execution> <id>default-clean</id> <phase>clean</phase> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>default-testResources</id> <phase>process-test-resources</phase> <goals> <goal>testResources</goal> </goals> </execution> <execution> <id>default-resources</id> <phase>process-resources</phase> <goals> <goal>resources</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>default-jar</id> <phase>package</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <executions> <execution> <id>default-compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>default-testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <executions> <execution> <id>default-test</id> <phase>test</phase> <goals> <goal>test</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>default-install</id> <phase>install</phase> <goals> <goal>install</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.7</version> <executions> <execution> <id>default-deploy</id> <phase>deploy</phase> <goals> <goal>deploy</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.3</version> <executions> <execution> <id>default-site</id> <phase>site</phase> <goals> <goal>site</goal> </goals> <configuration> <outputDirectory>C:\MVN\target\site</outputDirectory> <reportPlugins> <reportPlugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> </reportPlugin> </reportPlugins> </configuration> </execution> <execution> <id>default-deploy</id> <phase>site-deploy</phase> <goals> <goal>deploy</goal> </goals> <configuration> <outputDirectory>C:\MVN\target\site</outputDirectory> <reportPlugins> <reportPlugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> </reportPlugin> </reportPlugins> </configuration> </execution> </executions> <configuration> <outputDirectory>C:\MVN\target\site</outputDirectory> <reportPlugins> <reportPlugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> </reportPlugin> </reportPlugins> </configuration> </plugin> </plugins> </build> <reporting> <outputDirectory>C:\MVN\target\site</outputDirectory> </reporting> </project> In above pom.xml, you can see the default project source folders structure, output directory, plug-ins required, repositories, reporting directory, which Maven will be using while executing the desired goals. Maven pom.xml is also not required to be written manually. Maven provides numerous archetype plugins to create projects, which in order, create the project structure and pom.xml A Build Lifecycle is a well-defined sequence of phases, which define the order in which the goals are to be executed. Here phase represents a stage in life cycle. As an example, a typical Maven Build Lifecycle consists of the following sequence of phases. There are always pre and post phases to register goals, which must run prior to, or after a particular phase. When Maven starts building a project, it steps through a defined sequence of phases and executes goals, which are registered with each phase. Maven has the following three standard lifecycles − clean default(or build) site A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation. The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases while the dependency:copy-dependencies is a goal. mvn clean dependency:copy-dependencies package Here the clean phase will be executed first, followed by the dependency:copy-dependencies goal, and finally package phase will be executed. When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases. pre-clean clean post-clean Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory. Thus, when mvn clean command executes, Maven deletes the build directory. We can customize this behavior by mentioning goals in any of the above phases of clean life cycle. In the following example, We'll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases. This will allow us to echo text messages displaying the phases of the clean lifecycle. We've created a pom.xml in C:\MVN\project folder. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.1</version> <executions> <execution> <id>id.pre-clean</id> <phase>pre-clean</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>pre-clean phase</echo> </tasks> </configuration> </execution> <execution> <id>id.clean</id> <phase>clean</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>clean phase</echo> </tasks> </configuration> </execution> <execution> <id>id.post-clean</id> <phase>post-clean</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>post-clean phase</echo> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> Now open command console, go to the folder containing pom.xml and execute the following mvn command. C:\MVN\project>mvn post-clean Maven will start processing and displaying all the phases of clean life cycle. C:\MVN>mvn post-clean [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.projectgroup:project >---------------- [INFO] Building project 1.0 [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.pre-clean) @ project --- [INFO] Executing tasks [echo] pre-clean phase [INFO] Executed tasks [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project --- [INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project --- [INFO] Executing tasks [echo] clean phase [INFO] Executed tasks [INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.post-clean) @ project --- [INFO] Executing tasks [echo] post-clean phase [INFO] Executed tasks [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.740 s [INFO] Finished at: 2021-12-10T20:03:53+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> You can try tuning mvn clean command, which will display pre-clean and clean. Nothing will be executed for post-clean phase. This is the primary life cycle of Maven and is used to build the application. It has the following 21 phases. validate Validates whether project is correct and all necessary information is available to complete the build process. initialize Initializes build state, for example set properties. generate-sources Generate any source code to be included in compilation phase. process-sources Process the source code, for example, filter any value. generate-resources Generate resources to be included in the package. process-resources Copy and process the resources into the destination directory, ready for packaging phase. compile Compile the source code of the project. process-classes Post-process the generated files from compilation, for example to do bytecode enhancement/optimization on Java classes. generate-test-sources Generate any test source code to be included in compilation phase. process-test-sources Process the test source code, for example, filter any values. test-compile Compile the test source code into the test destination directory. process-test-classes Process the generated files from test code file compilation. test Run tests using a suitable unit testing framework (Junit is one). prepare-package Perform any operations necessary to prepare a package before the actual packaging. package Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR file. pre-integration-test Perform actions required before integration tests are executed. For example, setting up the required environment. integration-test Process and deploy the package if necessary into an environment where integration tests can be run. post-integration-test Perform actions required after integration tests have been executed. For example, cleaning up the environment. verify Run any check-ups to verify the package is valid and meets quality criteria. install Install the package into the local repository, which can be used as a dependency in other projects locally. deploy Copies the final package to the remote repository for sharing with other developers and projects. There are few important concepts related to Maven Lifecycles, which are worth to mention − When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute. When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute. Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR). Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR). In the following example, we will attach maven-antrun-plugin:run goal to few of the phases of Build lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle. We've updated pom.xml in C:\MVN\project folder. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.1</version> <executions> <execution> <id>id.validate</id> <phase>validate</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>validate phase</echo> </tasks> </configuration> </execution> <execution> <id>id.compile</id> <phase>compile</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>compile phase</echo> </tasks> </configuration> </execution> <execution> <id>id.test</id> <phase>test</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>test phase</echo> </tasks> </configuration> </execution> <execution> <id>id.package</id> <phase>package</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>package phase</echo> </tasks> </configuration> </execution> <execution> <id>id.deploy</id> <phase>deploy</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>deploy phase</echo> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> Now open command console, go the folder containing pom.xml and execute the following mvn command. C:\MVN\project>mvn compile Maven will start processing and display phases of build life cycle up to the compile phase. C:\MVN>mvn compile [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.projectgroup:project >---------------- [INFO] Building project 1.0 [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.validate) @ project --- [INFO] Executing tasks [echo] validate phase [INFO] Executed tasks [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ project --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ project --- [INFO] No sources to compile [INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.compile) @ project --- [INFO] Executing tasks [echo] compile phase [INFO] Executed tasks [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.033 s [INFO] Finished at: 2021-12-10T20:05:46+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases − pre-site site post-site site-deploy In the following example, we will attach maven-antrun-plugin:run goal to all the phases of Site lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle. We've updated pom.xml in C:\MVN\project folder. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.9</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.1</version> <executions> <execution> <id>id.pre-site</id> <phase>pre-site</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>pre-site phase</echo> </tasks> </configuration> </execution> <execution> <id>id.site</id> <phase>site</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>site phase</echo> </tasks> </configuration> </execution> <execution> <id>id.post-site</id> <phase>post-site</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>post-site phase</echo> </tasks> </configuration> </execution> <execution> <id>id.site-deploy</id> <phase>site-deploy</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>site-deploy phase</echo> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> Now open the command console, go the folder containing pom.xml and execute the following mvn command. C:\MVN\project>mvn site Maven will start processing and displaying the phases of site life cycle up to site phase. C:\MVN>mvn site [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.projectgroup:project >---------------- [INFO] Building project 1.0 [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-antrun-plugin:3.0.0:run (id.pre-site) @ project --- [INFO] Executing tasks [WARNING] [echo] pre-site phase [INFO] Executed tasks [INFO] [INFO] --- maven-site-plugin:3.7:site (default-site) @ project --- [WARNING] Input file encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [WARNING] No project URL defined - decoration links will not be relativized! [INFO] Rendering site with org.apache.maven.skins:maven-default-skin:jar:1.2 skin. [INFO] [INFO] --- maven-antrun-plugin:3.0.0:run (id.site) @ project --- [INFO] Executing tasks [WARNING] [echo] site phase [INFO] Executed tasks [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.323 s [INFO] Finished at: 2021-12-10T20:22:31+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> A Build profile is a set of configuration values, which can be used to set or override default values of Maven build. Using a build profile, you can customize build for different environments such as Production v/s Development environments. Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are triggered in variety of ways. Profiles modify the POM at build time, and are used to give parameters different target environments (for example, the path of the database server in the development, testing, and production environments). Build profiles are majorly of three types. A Maven Build Profile can be activated in various ways. Explicitly using command console input. Through maven settings. Based on environment variables (User/System variables). OS Settings (for example, Windows family). Present/missing files. Let us assume the following directory structure of your project − Now, under src/main/resources, there are three environment specific files − env.properties default configuration used if no profile is mentioned. env.test.properties test configuration when test profile is used. env.prod.properties production configuration when prod profile is used. In the following example, we will attach maven-antrun-plugin:run goal to test the phase. This will allow us to echo text messages for different profiles. We will be using pom.xml to define different profiles and will activate profile at command console using maven command. Assume, we've created the following pom.xml in C:\MVN\project folder. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <profiles> <profile> <id>test</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.1</version> <executions> <execution> <phase>test</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>Using env.test.properties</echo> <copy file="src/main/resources/env.test.properties" tofile="${project.build.outputDirectory}/env.properties"/> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> Now open the command console, go to the folder containing pom.xml and execute the following mvn command. Pass the profile name as argument using -P option. C:\MVN\project>mvn test -Ptest Maven will start processing and displaying the result of test build profile. C:\MVN>mvn test -Ptest [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.projectgroup:project >---------------- [INFO] Building project 1.0 [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ project --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 3 resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ project --- [INFO] No sources to compile [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ project --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ project --- [INFO] No sources to compile [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ project --- [INFO] No tests to run. [INFO] [INFO] --- maven-antrun-plugin:1.1:run (default) @ project --- [INFO] Executing tasks [echo] Using env.test.properties [INFO] Executed tasks [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.011 s [INFO] Finished at: 2021-12-10T20:29:39+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> Now as an exercise, you can perform the following steps − Add another profile element to profiles element of pom.xml (copy existing profile element and paste it where profile elements ends). Add another profile element to profiles element of pom.xml (copy existing profile element and paste it where profile elements ends). Update id of this profile element from test to normal. Update id of this profile element from test to normal. Update task section to echo env.properties and copy env.properties to target directory. Update task section to echo env.properties and copy env.properties to target directory. Again repeat the above three steps, update id to prod and task section for env.prod.properties. Again repeat the above three steps, update id to prod and task section for env.prod.properties. That's all. Now you've three build profiles ready (normal/test/prod). That's all. Now you've three build profiles ready (normal/test/prod). Now open the command console, go to the folder containing pom.xml and execute the following mvn commands. Pass the profile names as argument using -P option. C:\MVN\project>mvn test -Pnormal C:\MVN\project>mvn test -Pprod Check the output of the build to see the difference. Open Maven settings.xml file available in %USER_HOME%/.m2 directory where %USER_HOME% represents the user home directory. If settings.xml file is not there, then create a new one. Add test profile as an active profile using active Profiles node as shown below in example. <settings 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 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <mirrors> <mirror> <id>maven.dev.snaponglobal.com</id> <name>Internal Artifactory Maven repository</name> <url>http://repo1.maven.org/maven2/</url> <mirrorOf>*</mirrorOf> </mirror> </mirrors> <activeProfiles> <activeProfile>test</activeProfile> </activeProfiles> </settings> Now open command console, go to the folder containing pom.xml and execute the following mvn command. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile. C:\MVN\project>mvn test Now remove active profile from maven settings.xml and update the test profile mentioned in pom.xml. Add activation element to profile element as shown below. The test profile will trigger when the system property "env" is specified with the value "test". Create an environment variable "env" and set its value as "test". <profile> <id>test</id> <activation> <property> <name>env</name> <value>test</value> </property> </activation> </profile> Let's open command console, go to the folder containing pom.xml and execute the following mvn command. C:\MVN\project>mvn test Activation element to include os detail as shown below. This test profile will trigger when the system is windows XP. <profile> <id>test</id> <activation> <os> <name>Windows XP</name> <family>Windows</family> <arch>x86</arch> <version>5.1.2600</version> </os> </activation> </profile> Now open command console, go to the folder containing pom.xml and execute the following mvn commands. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile. C:\MVN\project>mvn test Now activation element to include OS details as shown below. The test profile will trigger when target/generated-sources/axistools/wsdl2java/com/companyname/group is missing. <profile> <id>test</id> <activation> <file> <missing>target/generated-sources/axistools/wsdl2java/ com/companyname/group</missing> </file> </activation> </profile> Now open the command console, go to the folder containing pom.xml and execute the following mvn commands. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile. C:\MVN\project>mvn test In Maven terminology, a repository is a directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily. Maven repository are of three types. The following illustration will give an idea regarding these three types. local central remote Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time. Maven local repository keeps your project's all dependencies (library jars, plugin jars etc.). When you run a Maven build, then Maven automatically downloads all the dependency jars into the local repository. It helps to avoid references to dependencies stored on remote machine every time a project is build. Maven local repository by default get created by Maven in %USER_HOME% directory. To override the default location, mention another path in Maven settings.xml file available at %M2_HOME%\conf directory. <settings xmlns = "http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <localRepository>C:/MyLocalRepository</localRepository> </settings> When you run Maven command, Maven will download dependencies to your custom path. Maven central repository is repository provided by Maven community. It contains a large number of commonly used libraries. When Maven does not find any dependency in local repository, it starts searching in central repository using following URL − https://repo1.maven.org/maven2/ Key concepts of Central repository are as follows − This repository is managed by Maven community. It is not required to be configured. It requires internet access to be searched. To browse the content of central maven repository, maven community has provided a URL − https://search.maven.org/#browse. Using this library, a developer can search all the available libraries in central repository. Sometimes, Maven does not find a mentioned dependency in central repository as well. It then stops the build process and output error message to console. To prevent such situation, Maven provides concept of Remote Repository, which is developer's own custom repository containing required libraries or other project jars. For example, using below mentioned POM.xml, Maven will download dependency (not available in central repository) from Remote Repositories mentioned in the same pom.xml. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>com.companyname.common-lib</groupId> <artifactId>common-lib</artifactId> <version>1.0.0</version> </dependency> <dependencies> <repositories> <repository> <id>companyname.lib1</id> <url>http://download.companyname.org/maven2/lib1</url> </repository> <repository> <id>companyname.lib2</id> <url>http://download.companyname.org/maven2/lib2</url> </repository> </repositories> </project> When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence − Step 1 − Search dependency in local repository, if not found, move to step 2 else perform the further processing. Step 1 − Search dependency in local repository, if not found, move to step 2 else perform the further processing. Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference. Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference. Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency). Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency). Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency). Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency). Maven is actually a plugin execution framework where every task is actually done by plugins. Maven Plugins are generally used to − create jar file create war file compile code files unit testing of code create project documentation create project reports A plugin generally provides a set of goals, which can be executed using the following syntax − mvn [plugin-name]:[goal-name] For example, a Java project can be compiled with the maven-compiler-plugin's compile-goal by running the following command. mvn compiler:compile Maven provided the following two types of Plugins − Build plugins They execute during the build process and should be configured in the <build/> element of pom.xml. Reporting plugins They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml. Following is the list of few common plugins − clean Cleans up target after the build. Deletes the target directory. compiler Compiles Java source files. surefire Runs the JUnit unit tests. Creates test reports. jar Builds a JAR file from the current project. war Builds a WAR file from the current project. javadoc Generates Javadoc for the project. antrun Runs a set of ant tasks from any phase mentioned of the build. Example We've used maven-antrun-plugin extensively in our examples to print data on console. Refer Build Profiles chapter. Let us understand it in a better way and create a pom.xml in C:\MVN\project folder. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.1</version> <executions> <execution> <id>id.clean</id> <phase>clean</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo>clean phase</echo> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> Next, open the command console and go to the folder containing pom.xml and execute the following mvn command. C:\MVN\project>mvn clean Maven will start processing and displaying the clean phase of clean life cycle. C:\MVN>mvn clean [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.projectgroup:project >---------------- [INFO] Building project 1.0 [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project --- [INFO] Deleting C:\MVN\target [INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project --- [INFO] Executing tasks [echo] clean phase [INFO] Executed tasks [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.266 s [INFO] Finished at: 2021-12-13T13:58:10+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> The above example illustrates the following key concepts − Plugins are specified in pom.xml using plugins element. Plugins are specified in pom.xml using plugins element. Each plugin can have multiple goals. Each plugin can have multiple goals. You can define phase from where plugin should starts its processing using its phase element. We've used clean phase. You can define phase from where plugin should starts its processing using its phase element. We've used clean phase. You can configure tasks to be executed by binding them to goals of plugin. We've bound echo task with run goal of maven-antrun-plugin. You can configure tasks to be executed by binding them to goals of plugin. We've bound echo task with run goal of maven-antrun-plugin. Maven will then download the plugin if not available in local repository and start its processing. Maven will then download the plugin if not available in local repository and start its processing. Maven uses archetype plugins to create projects. To create a simple java application, we'll use maven-archetype-quickstart plugin. In example below, we'll create a maven based java application project in C:\MVN folder. Let's open the command console, go to the C:\MVN directory and execute the following mvn command. Make sure that C:\MVN directory is empty before running the command. C:\MVN>mvn archetype:generate -DgroupId = com.companyname.bank -DartifactId = consumerBanking -DarchetypeArtifactId = maven-archetype-quickstart -DinteractiveMode = false Maven will start processing and will create the complete java application project structure. C:\MVN>mvn archetype:generate -DgroupId=com.companyname.bank -DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false [INFO] Scanning for projects... [INFO] [INFO] ------------------< org.apache.maven:standalone-pom >------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] --------------------------------[ pom ]--------------------------------- [INFO] [INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Batch mode [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: basedir, Value: C:\MVN [INFO] Parameter: package, Value: com.companyname.bank [INFO] Parameter: groupId, Value: com.companyname.bank [INFO] Parameter: artifactId, Value: consumerBanking [INFO] Parameter: packageName, Value: com.companyname.bank [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:\MVN\consumerBanking [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.396 s [INFO] Finished at: 2021-12-13T15:13:00+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> Now go to C:/MVN directory. You'll see a java application project created, named consumer Banking (as specified in artifactId). Maven uses a standard directory layout as shown below − Using the above example, we can understand the following key concepts − consumerBanking contains src folder and pom.xml src/main/java contains java code files under the package structure (com/companyName/bank). src/main/test contains test java code files under the package structure (com/companyName/bank). src/main/resources it contains images/properties files (In above example, we need to create this structure manually). If you observe, you will find that Maven also created a sample Java Source file and Java Test file. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, you will see App.java. package com.companyname.bank; /** * Hello world! * */ public class App { public static void main( String[] args ){ System.out.println( "Hello World!" ); } } Open C:\MVN\consumerBanking\src\test\java\com\companyname\bank folder to see AppTest.java. package com.companyname.bank; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } } Developers are required to place their files as mentioned in table above and Maven handles all the build related complexities. In the next chapter, we'll discuss how to build and test the project using maven Build and Test Project. What we learnt in Project Creation chapter is how to create a Java application using Maven. Now we'll see how to build and test the application. Go to C:/MVN directory where you've created your java application. Open consumerBanking folder. You will see the POM.xml file with the following contents. Update it to reflect the current java version. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> </dependency> </dependencies> </project> Here you can see, Maven already added Junit as test framework. By default, Maven adds a source file App.java and a test file AppTest.java in its default directory structure, as discussed in the previous chapter. Let's open the command console, go the C:\MVN\consumerBanking directory and execute the following mvn command. C:\MVN\consumerBanking>mvn clean package Maven will start building the project. C:\MVN\consumerBanking>mvn clean package [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.bank:consumerBanking >---------------- [INFO] Building consumerBanking 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking --- [INFO] Deleting C:\MVN\consumerBanking\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking --- [INFO] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.companyname.bank.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking --- [INFO] Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.663 s [INFO] Finished at: 2021-12-13T17:34:27+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN\consumerBanking> You've built your project and created final jar file, following are the key learning concepts − We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package). We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package). Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar. Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar. Test reports are available in consumerBanking\target\surefire-reports folder. Test reports are available in consumerBanking\target\surefire-reports folder. Maven compiles the source code file(s) and then tests the source code file(s). Maven compiles the source code file(s) and then tests the source code file(s). Then Maven runs the test cases. Then Maven runs the test cases. Finally, Maven creates the package. Finally, Maven creates the package. Now open the command console, go the C:\MVN\consumerBanking\target\classes directory and execute the following java command. >java com.companyname.bank.App You will see the result as follows − Hello World! Let's see how we can add additional Java files in our project. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, create Util class in it as Util.java. package com.companyname.bank; public class Util { public static void printMessage(String message){ System.out.println(message); } } Update the App class to use Util class. package com.companyname.bank; /** * Hello world! * */ public class App { public static void main( String[] args ){ Util.printMessage("Hello World!"); } } Now open the command console, go the C:\MVN\consumerBanking directory and execute the following mvn command. >mvn clean compile After Maven build is successful, go to the C:\MVN\consumerBanking\target\classes directory and execute the following java command. >java -cp com.companyname.bank.App You will see the result as follows − Hello World! As you know, Maven does the dependency management using the concept of Repositories. But what happens if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency. For example, let us do the following changes to the project created in ‘Creating Java Project’ chapter. Add lib folder to the src folder. Add lib folder to the src folder. Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations. Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations. Now our project structure should look like the following − Here you are having your own library, specific to the project, which is an usual case and it contains jars, which may not be available in any repository for maven to download from. If your code is using this library with Maven, then Maven build will fail as it cannot download or refer to this library during compilation phase. To handle the situation, let's add this external dependency to maven pom.xml using the following way. <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 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.bank</groupId> <artifactId>consumerBanking</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>consumerBanking</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>ldapjdk</groupId> <artifactId>ldapjdk</artifactId> <scope>system</scope> <version>1.0</version> <systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath> </dependency> </dependencies> </project> Look at the second dependency element under dependencies in the above example, which clears the following key concepts about External Dependency. External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies. External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies. Specify groupId same as the name of the library. Specify groupId same as the name of the library. Specify artifactId same as the name of the library. Specify artifactId same as the name of the library. Specify scope as system. Specify scope as system. Specify system path relative to the project location. Specify system path relative to the project location. Hope now you are clear about external dependencies and you will be able to specify external dependencies in your Maven project. This tutorial will teach you how to create documentation of the application in one go. So let's start, go to C:/MVN directory where you had created your java consumerBanking application using the examples given in the previous chapters. Open consumerBanking folder and execute the following mvn command. Update, the pom.xml in C:\MVN\consumerBanking folder as shown below. <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 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.bank</groupId> <artifactId>consumerBanking</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>consumerBanking</name> <url>http://maven.apache.org</url> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.9</version> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> C:\MVN\consumerBanking>mvn site Maven will start building the project. [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.bank:consumerBanking >---------------- [INFO] Building consumerBanking 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-site-plugin:3.7:site (default-site) @ consumerBanking --- [WARNING] Input file encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Relativizing decoration links with respect to localized project URL: http://maven.apache.org [INFO] Rendering site with org.apache.maven.skins:maven-default-skin:jar:1.2 skin. [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 5.850 s [INFO] Finished at: 2021-12-13T17:49:56+05:30 [INFO] ------------------------------------------------------------------------ Your project documentation is now ready. Maven has created a site within the target directory. Open C:\MVN\consumerBanking\target\site folder. Click on index.html to see the documentation. Maven creates the documentation using a documentation-processing engine called Doxia which reads multiple source formats into a common document model. To write documentation for your project, you can write your content in a following few commonly used formats which are parsed by Doxia. https://jakarta.apache.org/site https://maven.apache.org Maven provides users, a very large list of different types of project templates (614 in numbers) using the concept of Archetype. Maven helps users to quickly start a new java project using the following command. mvn archetype:generate Archetype is a Maven plugin whose task is to create a project structure as per its template. We are going to use quickstart archetype plugin to create a simple java application here. Let's open the command console, go to the C:\ > MVN directory and execute the following mvn command. C:\MVN>mvn archetype:generate Maven will start processing and will ask to choose the required archetype. C:\MVN>mvn archetype:generate [INFO] Scanning for projects... [INFO] [INFO] ------------------< org.apache.maven:standalone-pom >------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] --------------------------------[ pom ]--------------------------------- [INFO] [INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Interactive mode [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) Choose archetype: 1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype (Blank multi project for Spring Boot + Elm) 2: remote -> am.ik.archetype:graalvm-blank-archetype (Blank project for GraalVM) ... 3021: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-) Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1843: Press Enter to choose to default option (1843: maven-archetype-quickstart) Maven will ask for particular version of archetype. Choose org.apache.maven.archetypes:maven-archetype-quickstart version: 1: 1.0-alpha-1 2: 1.0-alpha-2 3: 1.0-alpha-3 4: 1.0-alpha-4 5: 1.0 6: 1.1 7: 1.3 8: 1.4 Choose a number: 8: Press Enter to choose to default option (8: maven-archetype-quickstart:1.4) Maven will ask for the project detail. Enter project detail as asked. Press Enter if the default value is provided. You can override them by entering your own value. Define value for property 'groupId': : com.companyname.insurance Define value for property 'artifactId': : health Define value for property 'version': 1.0-SNAPSHOT: Define value for property 'package': com.companyname.insurance: Maven will ask for the project detail confirmation. Press enter or press Y. Confirm properties configuration: groupId: com.companyname.insurance artifactId: health version: 1.0-SNAPSHOT package: com.companyname.insurance Y: Now Maven will start creating the project structure and will display the following − [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: com.companyname.insurance [INFO] Parameter: artifactId, Value: health [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: package, Value: com.companyname.insurance [INFO] Parameter: packageInPathFormat, Value: com/companyname/insurance [INFO] Parameter: package, Value: com.companyname.insurance [INFO] Parameter: groupId, Value: com.companyname.insurance [INFO] Parameter: artifactId, Value: health [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Project created from Archetype in dir: C:\MVN\health [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 04:44 min [INFO] Finished at: 2021-12-13T18:52:59+05:30 [INFO] ------------------------------------------------------------------------ Now go to C:\ > MVN directory. You'll see a java application project created, named health, which was given as artifactId at the time of project creation. Maven will create a standard directory layout for the project as shown below − Maven generates a POM.xml file for the project as listed below − <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.insurance</groupId> <artifactId>health</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>health</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> Maven generates sample java source file, App.java for the project as listed below − Location: C:\ > MVN > health > src > main > java > com > companyname > insurance > App.java. package com.companyname.insurance; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } } Maven generates sample java source test file, AppTest.java for the project as listed below − Location: C:\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java. package com.companyname.insurance; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } } Now you can see the power of Maven. You can create any kind of project using single command in maven and can kick-start your development. maven-archetype-archetype An archetype, which contains a sample archetype. maven-archetype-j2ee-simple An archetype, which contains a simplified sample J2EE application. maven-archetype-mojo An archetype, which contains a sample a sample Maven plugin. maven-archetype-plugin An archetype, which contains a sample Maven plugin. maven-archetype-plugin-site An archetype, which contains a sample Maven plugin site. maven-archetype-portlet An archetype, which contains a sample JSR-268 Portlet. maven-archetype-quickstart An archetype, which contains a sample Maven project. maven-archetype-simple An archetype, which contains a simple Maven project. maven-archetype-site An archetype, which contains a sample Maven site to demonstrates some of the supported document types like APT, XDoc, and FML and demonstrates how to i18n your site. maven-archetype-site-simple An archetype, which contains a sample Maven site. maven-archetype-webapp An archetype, which contains a sample Maven Webapp project. A large software application generally consists of multiple modules and it is common scenario where multiple teams are working on different modules of same application. For example, consider a team is working on the front end of the application as app-ui project (app-ui.jar:1.0) and they are using data-service project (data-service.jar:1.0). Now it may happen that team working on data-service is undergoing bug fixing or enhancements at rapid pace and they are releasing the library to remote repository almost every other day. Now if data-service team uploads a new version every other day, then following problems will arise − data-service team should tell app-ui team every time when they have released an updated code. data-service team should tell app-ui team every time when they have released an updated code. app-ui team required to update their pom.xml regularly to get the updated version. app-ui team required to update their pom.xml regularly to get the updated version. To handle such kind of situation, SNAPSHOT concept comes into play. SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build. Now data-service team will release SNAPSHOT of its updated code every time to repository, say data-service: 1.0-SNAPSHOT, replacing an older SNAPSHOT jar. In case of Version, if Maven once downloaded the mentioned version, say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1. In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) every time app-ui team build their project. app-ui project is using 1.0-SNAPSHOT of data-service. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>app-ui</groupId> <artifactId>app-ui</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>health</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>data-service</groupId> <artifactId>data-service</artifactId> <version>1.0-SNAPSHOT</version> <scope>test</scope> </dependency> </dependencies> </project> data-service project is releasing 1.0-SNAPSHOT for every minor change. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>data-service</groupId> <artifactId>data-service</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>health</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project> Although, in case of SNAPSHOT, Maven automatically fetches the latest SNAPSHOT on daily basis, you can force maven to download latest snapshot build using -U switch to any maven command. mvn clean package -U Let's open the command console, go to the C:\ > MVN > app-ui directory and execute the following mvn command. C:\MVN\app-ui>mvn clean package -U Maven will start building the project after downloading the latest SNAPSHOT of data-service. [INFO] Scanning for projects... [INFO]-------------------------------------------- [INFO] Building consumerBanking [INFO] task-segment: [clean, package] [INFO]-------------------------------------------- [INFO] Downloading data-service:1.0-SNAPSHOT [INFO] 290K downloaded. [INFO] [clean:clean {execution: default-clean}] [INFO] Deleting directory C:\MVN\app-ui\target [INFO] [resources:resources {execution: default-resources}] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\app-ui\src\main\resources [INFO] [compiler:compile {execution:default-compile}] [INFO] Compiling 1 source file to C:\MVN\app-ui\target\classes [INFO] [resources:testResources {execution: default-testResources}] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\app-ui\src\test\resources [INFO] [compiler:testCompile {execution: default-testCompile}] [INFO] Compiling 1 source file to C:\MVN\app-ui\target\test-classes [INFO] [surefire:test {execution: default-test}] [INFO] Surefire report directory: C:\MVN\app-ui\target\ surefire-reports -------------------------------------------------- T E S T S -------------------------------------------------- Running com.companyname.bank.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\app-ui\target\ app-ui-1.0-SNAPSHOT.jar [INFO]-------------------------------------------------------- [INFO] BUILD SUCCESSFUL [INFO]-------------------------------------------------------- [INFO] Total time: 2 seconds [INFO] Finished at: 2015-09-27T12:30:02+05:30 [INFO] Final Memory: 16M/89M [INFO]------------------------------------------------------------------------ Build Automation defines the scenario where dependent project(s) build process gets started once the project build is successfully completed, in order to ensure that dependent project(s) is/are stable. Example Consider a team is developing a project bus-core-api on which two other projects app-web-ui and app-desktop-ui are dependent. app-web-ui project is using 1.0-SNAPSHOT of bus-core-api project. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>app-web-ui</groupId> <artifactId>app-web-ui</artifactId> <version>1.0</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>bus-core-api</groupId> <artifactId>bus-core-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project> app-desktop-ui project is using 1.0-SNAPSHOT of bus-core-api project. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>app_desktop_ui</groupId> <artifactId>app_desktop_ui</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>app_desktop_ui</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>bus_core_api</groupId> <artifactId>bus_core_api</artifactId> <version>1.0-SNAPSHOT</version> <scope>system</scope> <systemPath>C:\MVN\bus_core_api\target\bus_core_api-1.0-SNAPSHOT.jar</systemPath> </dependency> </dependencies> </project> bus-core-api project − <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>bus_core_api</groupId> <artifactId>bus_core_api</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> </project> Now, teams of app-web-ui and app-desktop-ui projects require that their build process should kick off whenever bus-core-api project changes. Using snapshot, ensures that the latest bus-core-api project should be used but to meet the above requirement we need to do something extra. We can proceed with the following two ways − Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds. Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds. Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically. Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically. Update bus-core-api project pom.xml. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>bus-core-api</groupId> <artifactId>bus-core-api</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <build> <plugins> <plugin> <artifactId>maven-invoker-plugin</artifactId> <version>1.6</version> <configuration> <debug>true</debug> <pomIncludes> <pomInclude>app-web-ui/pom.xml</pomInclude> <pomInclude>app-desktop-ui/pom.xml</pomInclude> </pomIncludes> </configuration> <executions> <execution> <id>build</id> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> <build> </project> Let's open the command console, go to the C:\ > MVN > bus-core-api directory and execute the following mvn command. >mvn clean package -U Maven will start building the project bus-core-api. [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------ [INFO] Building bus-core-api [INFO] task-segment: [clean, package] [INFO] ------------------------------------------------------------------ ... [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\bus-core-ui\target\ bus-core-ui-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------ Once bus-core-api build is successful, Maven will start building the app-web-ui project. [INFO] ------------------------------------------------------------------ [INFO] Building app-web-ui [INFO] task-segment: [package] [INFO] ------------------------------------------------------------------ ... [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\app-web-ui\target\ app-web-ui-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------ Once app-web-ui build is successful, Maven will start building the app-desktop-ui project. [INFO] ------------------------------------------------------------------ [INFO] Building app-desktop-ui [INFO] task-segment: [package] [INFO] ------------------------------------------------------------------ ... [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\app-desktop-ui\target\ app-desktop-ui-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------- [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------- Using a CI Server is more preferable to developers. It is not required to update the bus-core-api project, every time a new project (for example, app-mobile-ui) is added, as dependent project on bus-core-api project. Hudsion is a continuous integration tool written in java, which in a servlet container, such as, Apache tomcat and glassfish application server. Hudson automatically manages build automation using Maven dependency management. The following snapshot will define the role of Hudson tool. Hudson considers each project build as job. Once a project code is checked-in to SVN (or any Source Management Tool mapped to Hudson), Hudson starts its build job and once this job gets completed, it start other dependent jobs (other dependent projects) automatically. In the above example, when bus-core-ui source code is updated in SVN, Hudson starts its build. Once build is successful, Hudson looks for dependent projects automatically, and starts building app-web-ui and app-desktop-ui projects. One of the core features of Maven is Dependency Management. Managing dependencies is a difficult task once we've to deal with multi-module projects (consisting of hundreds of modules/sub-projects). Maven provides a high degree of control to manage such scenarios. It is pretty often a case, when a library, say A, depends upon other library, say B. In case another project C wants to use A, then that project requires to use library B too. Maven helps to avoid such requirements to discover all the libraries required. Maven does so by reading project files (pom.xml) of dependencies, figure out their dependencies and so on. We only need to define direct dependency in each project pom. Maven handles the rest automatically. With transitive dependencies, the graph of included libraries can quickly grow to a large extent. Cases can arise when there are duplicate libraries. Maven provides few features to control extent of transitive dependencies. Dependency mediation Determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used. Dependency management Directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependency Management section and directly control which version of B is to be used when it is ever referenced. Dependency scope Includes dependencies as per the current stage of the build. Excluded dependencies Any transitive dependency can be excluded using "exclusion" element. As example, A depends upon B and B depends upon C, then A can mark C as excluded. Optional dependencies Any transitive dependency can be marked as optional using "optional" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C. Transitive Dependencies Discovery can be restricted using various Dependency Scope as mentioned below. compile This scope indicates that dependency is available in classpath of project. It is default scope. provided This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime. runtime This scope indicates that dependency is not required for compilation, but is required during execution. test This scope indicates that the dependency is only available for the test compilation and execution phases. system This scope indicates that you have to provide the system path. import This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section. Usually, we have a set of project under a common project. In such case, we can create a common pom having all the common dependencies and then make this pom, the parent of sub-project's poms. Following example will help you understand this concept. Following are the detail of the above dependency graph − App-UI-WAR depends upon App-Core-lib and App-Data-lib. Root is parent of App-Core-lib and App-Data-lib. Root defines Lib1, lib2, Lib3 as dependencies in its dependency section. App-UI-WAR <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>App-UI-WAR</artifactId> <version>1.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.companyname.groupname</groupId> <artifactId>App-Core-lib</artifactId> <version>1.0</version> </dependency> </dependencies> <dependencies> <dependency> <groupId>com.companyname.groupname</groupId> <artifactId>App-Data-lib</artifactId> <version>1.0</version> </dependency> </dependencies> </project> App-Core-lib <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>Root</artifactId> <groupId>com.companyname.groupname</groupId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>App-Core-lib</artifactId> <version>1.0</version> <packaging>jar</packaging> </project> App-Data-lib <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>Root</artifactId> <groupId>com.companyname.groupname</groupId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>App-Data-lib</artifactId> <version>1.0</version> <packaging>jar</packaging> </project> Root <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>Root</artifactId> <version>1.0</version> <packaging>pom</packaging> <dependencies> <dependency> <groupId>com.companyname.groupname1</groupId> <artifactId>Lib1</artifactId> <version>1.0</version> </dependency> </dependencies> <dependencies> <dependency> <groupId>com.companyname.groupname2</groupId> <artifactId>Lib2</artifactId> <version>2.1</version> </dependency> </dependencies> <dependencies> <dependency> <groupId>com.companyname.groupname3</groupId> <artifactId>Lib3</artifactId> <version>1.1</version> </dependency> </dependencies> </project> Now when we build App-UI-WAR project, Maven will discover all the dependencies by traversing the dependency graph and build the application. From above example, we can learn the following key concepts − Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM). Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM). There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail. There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail. In project development, normally a deployment process consists of the following steps − Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it. Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it. Download the complete source code from SVN. Download the complete source code from SVN. Build the application. Build the application. Store the build output either WAR or EAR file to a common network location. Store the build output either WAR or EAR file to a common network location. Get the file from network and deploy the file to the production site. Get the file from network and deploy the file to the production site. Updated the documentation with date and updated version number of the application. Updated the documentation with date and updated version number of the application. There are normally multiple people involved in the above mentioned deployment process. One team may handle check-in of code, other may handle build and so on. It is very likely that any step may be missed out due to manual efforts involved and owing to multi-team environment. For example, older build may not be replaced on network machine and deployment team deployed the older build again. Automate the deployment process by combining the following − Maven, to build and release projects. SubVersion, source code repository, to manage source code. Remote Repository Manager (Jfrog/Nexus) to manage project binaries. We will be using Maven Release plug-in to create an automated release process. For Example: bus-core-api project POM.xml. <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>bus-core-api</groupId> <artifactId>bus-core-api</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <scm> <url>http://www.svn.com</url> <connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/ Framework</connection> <developerConnection>scm:svn:${username}/${password}@localhost:8080: common_core_api:1101:code</developerConnection> </scm> <distributionManagement> <repository> <id>Core-API-Java-Release</id> <name>Release repository</name> <url>http://localhost:8081/nexus/content/repositories/ Core-Api-Release</url> </repository> </distributionManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.0-beta-9</version> <configuration> <useReleaseProfile>false</useReleaseProfile> <goals>deploy</goals> <scmCommentPrefix>[bus-core-api-release-checkin]-< /scmCommentPrefix> </configuration> </plugin> </plugins> </build> </project> In Pom.xml, following are the important elements we have used − SCM Configures the SVN location from where Maven will check out the source code. Repositories Location where built WAR/EAR/JAR or any other artifact will be stored after code build is successful. Plugin maven-release-plugin is configured to automate the deployment process. The Maven does the following useful tasks using maven-release-plugin. mvn release:clean It cleans the workspace in case the last release process was not successful. mvn release:rollback Rollback the changes done to workspace code and configuration in case the last release process was not successful. mvn release:prepare Performs multiple number of operations, such as − Checks whether there are any uncommitted local changes or not. Checks whether there are any uncommitted local changes or not. Ensures that there are no SNAPSHOT dependencies. Ensures that there are no SNAPSHOT dependencies. Changes the version of the application and removes SNAPSHOT from the version to make release. Changes the version of the application and removes SNAPSHOT from the version to make release. Update pom files to SVN. Update pom files to SVN. Run test cases. Run test cases. Commit the modified POM files. Commit the modified POM files. Tag the code in subversion Tag the code in subversion Increment the version number and append SNAPSHOT for future release. Increment the version number and append SNAPSHOT for future release. Commit the modified POM files to SVN. Commit the modified POM files to SVN. mvn release:perform Checks out the code using the previously defined tag and run the Maven deploy goal, to deploy the war or built artifact to repository. Let's open the command console, go to the C:\ > MVN >bus-core-api directory and execute the following mvn command. >mvn release:prepare Maven will start building the project. Once build is successful run the following mvn command. >mvn release:perform Once build is successful you can verify the uploaded JAR file in your repository. This chapter teaches you how to manage a web based project using Maven. Here you will learn how to create/build/deploy and run a web application. To create a simple java web application, we will use maven-archetype-webapp plugin. So, let's open the command console, go to the C:\MVN directory and execute the following mvn command. C:\MVN>mvn archetype:generate -DgroupId = com.companyname.automobile -DartifactId = trucks -DarchetypeArtifactId = maven-archetype-webapp -DinteractiveMode = false Maven will start processing and will create the complete web based java application project structure as follows − C:\MVN>mvn archetype:generate -DgroupId=com.companyname.automobile -DartifactId=trucks -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false [INFO] Scanning for projects... [INFO] [INFO] ------------------< org.apache.maven:standalone-pom >------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] --------------------------------[ pom ]--------------------------------- ... [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: basedir, Value: C:\MVN [INFO] Parameter: package, Value: com.companyname.automobile [INFO] Parameter: groupId, Value: com.companyname.automobile [INFO] Parameter: artifactId, Value: trucks [INFO] Parameter: packageName, Value: com.companyname.automobile [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:\MVN\trucks [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 10.381 s [INFO] Finished at: 2021-12-13T19:00:13+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN> Now go to C:/MVN directory. You'll see a java application project created, named trucks (as specified in artifactId) as specified in the following snapshot. The following directory structure is generally used for web applications − Maven uses a standard directory layout. Using the above example, we can understand the following key concepts − trucks contains src folder and pom.xml. src/main/webapp contains index.jsp and WEB-INF folder. src/main/webapp/WEB-INF contains web.xml src/main/resources it contains images/properties files. <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 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.automobile</groupId> <artifactId>trucks</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>trucks Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>trucks</finalName> </build> </project> If you observe, you will find that Maven also created a sample JSP Source file. Open C:\ > MVN > trucks > src > main > webapp > folder to see index.jsp with the following code − <html> <body> <h2>Hello World!</h2> </body> </html> Let's open the command console, go to the C:\MVN\trucks directory and execute the following mvn command. C:\MVN\trucks>mvn clean package Maven will start building the project. C:\MVN\trucks>mvn clean package [INFO] Scanning for projects... [INFO] [INFO] -----------------< com.companyname.automobile:trucks >------------------ [INFO] Building trucks Maven Webapp 1.0-SNAPSHOT [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ trucks --- [INFO] Deleting C:\MVN\trucks\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ trucks --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ trucks --- [INFO] No sources to compile [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ trucks --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\trucks\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ trucks --- [INFO] No sources to compile [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ trucks --- [INFO] No tests to run. [INFO] [INFO] --- maven-war-plugin:2.2:war (default-war) @ trucks --- WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/intel/.m2/repository/com/thoughtworks/xstream/xstream/1.3.1/xstream-1.3.1.jar) to field java.util.Properties.defaults WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release [INFO] Packaging webapp [INFO] Assembling webapp [trucks] in [C:\MVN\trucks\target\trucks] [INFO] Processing war project [INFO] Copying webapp resources [C:\MVN\trucks\src\main\webapp] [INFO] Webapp assembled in [50 msecs] [INFO] Building war: C:\MVN\trucks\target\trucks.war [INFO] WEB-INF\web.xml already added, skipping [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.494 s [INFO] Finished at: 2021-12-13T19:02:15+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN\trucks> Now copy the trucks.war created in C:\ > MVN > trucks > target > folder to your webserver webapp directory and restart the webserver. Run the web-application using URL: http://<server-name>:<port-number>/trucks/index.jsp. Verify the output. Eclipse provides an excellent plugin m2eclipse which seamlessly integrates Maven and Eclipse together. Some of features of m2eclipse are listed below − You can run Maven goals from Eclipse. You can run Maven goals from Eclipse. You can view the output of Maven commands inside the Eclipse, using its own console. You can view the output of Maven commands inside the Eclipse, using its own console. You can update maven dependencies with IDE. You can update maven dependencies with IDE. You can Launch Maven builds from within Eclipse. You can Launch Maven builds from within Eclipse. It does the dependency management for Eclipse build path based on Maven's pom.xml. It does the dependency management for Eclipse build path based on Maven's pom.xml. It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository (requires dependency project be in same workspace). It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository (requires dependency project be in same workspace). It automatic downloads the required dependencies and sources from the remote Maven repositories. It automatic downloads the required dependencies and sources from the remote Maven repositories. It provides wizards for creating new Maven projects, pom.xml and to enable Maven support on existing projects It provides wizards for creating new Maven projects, pom.xml and to enable Maven support on existing projects It provides quick search for dependencies in remote Maven repositories. It provides quick search for dependencies in remote Maven repositories. Use one of the following links to install m2eclipse − Installing m2eclipse in Eclipse 3.5 (Gallileo) Installing m2eclipse in Eclipse 3.6 (Helios) Following example will help you to leverage benefits of integrating Eclipse and maven. Open Eclipse. Open Eclipse. Select File > Import > option. Select File > Import > option. Select Maven Projects Option. Click on Next Button. Select Maven Projects Option. Click on Next Button. Select Project location, where a project was created using Maven. We've created a Java Project consumer Banking in the previous chapters. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven. Select Project location, where a project was created using Maven. We've created a Java Project consumer Banking in the previous chapters. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven. Click Finish Button. Click Finish Button. Now, you can see the maven project in eclipse. Now, have a look at consumer Banking project properties. You can see that Eclipse has added Maven dependencies to java build path. Now, it is time to build this project using maven capability of eclipse. Right Click on consumerBanking project to open context menu. Select Run as option. Then maven package option. Maven will start building the project. You can see the output in Eclipse Console as follows − [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.bank:consumerBanking >---------------- [INFO] Building consumerBanking 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking --- [INFO] Deleting C:\MVN\consumerBanking\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking --- [INFO] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.companyname.bank.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking --- [INFO] Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.663 s [INFO] Finished at: 2021-12-13T17:34:27+05:30 [INFO] ------------------------------------------------------------------------ Now, right click on App.java. Select Run As option. Then select Java Application. You will see the result as follows − Hello World! NetBeans 6.7 and newer has in-built support for Maven. In case of previous version, Maven plugin is available in plugin Manager. We are using NetBeans 6.9 in this example. Some of features of NetBeans are listed below − You can run Maven goals from NetBeans. You can run Maven goals from NetBeans. You can view the output of Maven commands inside the NetBeans using its own console. You can view the output of Maven commands inside the NetBeans using its own console. You can update maven dependencies with IDE. You can update maven dependencies with IDE. You can Launch Maven builds from within NetBeans. You can Launch Maven builds from within NetBeans. NetBeans does the dependency management automatically based on Maven's pom.xml. NetBeans does the dependency management automatically based on Maven's pom.xml. NetBeans resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace). NetBeans resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace). NetBeans automatic downloads required dependencies and sources from the remote Maven repositories. NetBeans automatic downloads required dependencies and sources from the remote Maven repositories. NetBeans provides wizards for creating new Maven projects, pom.xml. NetBeans provides wizards for creating new Maven projects, pom.xml. NetBeans provides a Maven Repository browser that enables you to view your local repository and registered external Maven repositories. NetBeans provides a Maven Repository browser that enables you to view your local repository and registered external Maven repositories. Following example will help you to leverage benefits of integrating NetBeans and Maven. Open NetBeans. Open NetBeans. Select File Menu > Open Project option. Select File Menu > Open Project option. Select Project location, where a project was created using Maven. We've created a Java Project consumerBanking. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven. Select Project location, where a project was created using Maven. We've created a Java Project consumerBanking. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven. Now, you can see the maven project in NetBeans. Have a look at consumerBanking project Libraries and Test Libraries. You can see that NetBeans has added Maven dependencies to its build path. Now, Its time to build this project using maven capability of NetBeans. Right Click on consumerBanking project to open context menu. Select Clean and Build as option. Maven will start building the project. You can see the output in NetBeans Console as follows − NetBeans: Executing 'mvn.bat -Dnetbeans.execution = true clean install' NetBeans: JAVA_HOME = C:\Program Files\Java\jdk1.6.0_21 Scanning for projects... ------------------------------------------------------------------------ Building consumerBanking task-segment: [clean, install] ------------------------------------------------------------------------ [clean:clean] [resources:resources] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources [compiler:compile] Compiling 2 source files to C:\MVN\consumerBanking\target\classes [resources:testResources] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources [compiler:testCompile] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes [surefire:test] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.companyname.bank.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [jar:jar] Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar [install:install] Installing C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar to C:\Users\GB3824\.m2\repository\com\companyname\bank\consumerBanking\ 1.0-SNAPSHOT\consumerBanking-1.0-SNAPSHOT.jar ------------------------------------------------------------------------ BUILD SUCCESSFUL ------------------------------------------------------------------------ Total time: 9 seconds Finished at: Thu Jul 19 12:57:28 IST 2012 Final Memory: 16M/85M ------------------------------------------------------------------------ Now, right click on App.java. Select Run File as option. You will see the result in the NetBeans Console. NetBeans: Executing 'mvn.bat -Dexec.classpathScope = runtime -Dexec.args = -classpath %classpath com.companyname.bank.App -Dexec.executable = C:\Program Files\Java\jdk1.6.0_21\bin\java.exe -Dnetbeans.execution = true process-classes org.codehaus.mojo:exec-maven-plugin:1.1.1:exec' NetBeans: JAVA_HOME = C:\Program Files\Java\jdk1.6.0_21 Scanning for projects... ------------------------------------------------------------------------ Building consumerBanking task-segment: [process-classes, org.codehaus.mojo:exec-maven-plugin:1.1.1:exec] ------------------------------------------------------------------------ [resources:resources] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources [compiler:compile] Nothing to compile - all classes are up to date [exec:exec] Hello World! ------------------------------------------------------------------------ BUILD SUCCESSFUL ------------------------------------------------------------------------ Total time: 1 second Finished at: Thu Jul 19 14:18:13 IST 2012 Final Memory: 7M/64M ------------------------------------------------------------------------ IntelliJ IDEA has in-built support for Maven. We are using IntelliJ IDEA Community Edition 11.1 in this example. Some of the features of IntelliJ IDEA are listed below − You can run Maven goals from IntelliJ IDEA. You can run Maven goals from IntelliJ IDEA. You can view the output of Maven commands inside the IntelliJ IDEA using its own console. You can view the output of Maven commands inside the IntelliJ IDEA using its own console. You can update maven dependencies within IDE. You can update maven dependencies within IDE. You can Launch Maven builds from within IntelliJ IDEA. You can Launch Maven builds from within IntelliJ IDEA. IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml. IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml. IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace). IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace). IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories. IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories. IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml. IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml. Following example will help you to leverage benefits of integrating IntelliJ IDEA and Maven. We will import Maven project using New Project Wizard. Open IntelliJ IDEA. Open IntelliJ IDEA. Select File Menu > New Project Option. Select File Menu > New Project Option. Select import project from existing model. Select import project from existing model. Select Maven option Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven. Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven. Select Maven project to import. Enter name of the project and click finish. Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section. Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section. Now, it is time to build this project using capability of IntelliJ IDEA. Select consumerBanking project. Select consumerBanking project. Select Buid menu > Rebuild Project Option Select Buid menu > Rebuild Project Option You can see the output in IntelliJ IDEA Console 4:01:56 PM Compilation completed successfully Select consumerBanking project. Select consumerBanking project. Right click on App.java to open context menu. Right click on App.java to open context menu. select Run App.main() select Run App.main() You will see the result in IntelliJ IDEA Console. "C:\Program Files\Java\jdk1.6.0_21\bin\java" -Didea.launcher.port=7533 "-Didea.launcher.bin.path= C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 11.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.6.0_21\jre\lib\charsets.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\deploy.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\javaws.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\jce.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\jsse.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\management-agent.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\plugin.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\resources.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\rt.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\dnsns.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\localedata.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunjce_provider.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunmscapi.jar; C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunpkcs11.jar C:\MVN\consumerBanking\target\classes; C:\Program Files\JetBrains\ IntelliJ IDEA Community Edition 11.1.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.companyname.bank.App Hello World! Process finished with exit code 0 34 Lectures 4 hours Karthikeya T 14 Lectures 1.5 hours Quaatso Learning Print Add Notes Bookmark this page
[ { "code": null, "e": 2332, "s": 2060, "text": "Maven is a project management and comprehension tool that provides developers a complete build lifecycle framework. Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle." }, { "code": null, "e": 2614, "s": 2332, "text": "In case of multiple development teams environment, Maven can set-up the way to work as per standards in a very short time. As most of the project setups are simple and reusable, Maven makes life of developer easy while creating reports, checks, build and testing automation setups." }, { "code": null, "e": 2671, "s": 2614, "text": "Maven provides developers ways to manage the following −" }, { "code": null, "e": 2678, "s": 2671, "text": "Builds" }, { "code": null, "e": 2692, "s": 2678, "text": "Documentation" }, { "code": null, "e": 2702, "s": 2692, "text": "Reporting" }, { "code": null, "e": 2715, "s": 2702, "text": "Dependencies" }, { "code": null, "e": 2720, "s": 2715, "text": "SCMs" }, { "code": null, "e": 2729, "s": 2720, "text": "Releases" }, { "code": null, "e": 2742, "s": 2729, "text": "Distribution" }, { "code": null, "e": 2755, "s": 2742, "text": "Mailing list" }, { "code": null, "e": 3009, "s": 2755, "text": "To summarize, Maven simplifies and standardizes the project build process. It handles compilation, distribution, documentation, team collaboration and other tasks seamlessly. Maven increases reusability and takes care of most of the build related tasks." }, { "code": null, "e": 3217, "s": 3009, "text": "Maven was originally designed to simplify building processes in Jakarta Turbine project. There were several projects and each project contained slightly different ANT build files. JARs were checked into CVS." }, { "code": null, "e": 3413, "s": 3217, "text": "Apache group then developed Maven which can build multiple projects together, publish projects information, deploy projects, share JARs across several projects and help in collaboration of teams." }, { "code": null, "e": 3484, "s": 3413, "text": "The primary goal of Maven is to provide developer with the following −" }, { "code": null, "e": 3579, "s": 3484, "text": "A comprehensive model for projects, which is reusable, maintainable, and easier to comprehend." }, { "code": null, "e": 3674, "s": 3579, "text": "A comprehensive model for projects, which is reusable, maintainable, and easier to comprehend." }, { "code": null, "e": 3734, "s": 3674, "text": "Plugins or tools that interact with this declarative model." }, { "code": null, "e": 3794, "s": 3734, "text": "Plugins or tools that interact with this declarative model." }, { "code": null, "e": 4017, "s": 3794, "text": "Maven project structure and contents are declared in an xml file, pom.xml, referred as Project Object Model (POM), which is the fundamental unit of the entire Maven system. In later chapters, we will explain POM in detail." }, { "code": null, "e": 4135, "s": 4017, "text": "Maven uses Convention over Configuration, which means developers are not required to create build process themselves." }, { "code": null, "e": 4449, "s": 4135, "text": "Developers do not have to mention each and every configuration detail. Maven provides sensible default behavior for projects. When a Maven project is created, Maven creates default project structure. Developer is only required to place files accordingly and he/she need not to define any configuration in pom.xml." }, { "code": null, "e": 4629, "s": 4449, "text": "As an example, following table shows the default values for project source code files, resource files and other configurations. Assuming, ${basedir} denotes the project location −" }, { "code": null, "e": 4913, "s": 4629, "text": "In order to build the project, Maven provides developers with options to mention life-cycle goals and project dependencies (that rely on Maven plugin capabilities and on its default conventions). Much of the project management and build related tasks are maintained by Maven plugins." }, { "code": null, "e": 5085, "s": 4913, "text": "Developers can build any given Maven project without the need to understand how the individual plugins work. We will discuss Maven Plugins in detail in the later chapters." }, { "code": null, "e": 5135, "s": 5085, "text": "Simple project setup that follows best practices." }, { "code": null, "e": 5185, "s": 5135, "text": "Simple project setup that follows best practices." }, { "code": null, "e": 5223, "s": 5185, "text": "Consistent usage across all projects." }, { "code": null, "e": 5261, "s": 5223, "text": "Consistent usage across all projects." }, { "code": null, "e": 5313, "s": 5261, "text": "Dependency management including automatic updating." }, { "code": null, "e": 5365, "s": 5313, "text": "Dependency management including automatic updating." }, { "code": null, "e": 5410, "s": 5365, "text": "A large and growing repository of libraries." }, { "code": null, "e": 5455, "s": 5410, "text": "A large and growing repository of libraries." }, { "code": null, "e": 5540, "s": 5455, "text": "Extensible, with the ability to easily write plugins in Java or scripting languages." }, { "code": null, "e": 5625, "s": 5540, "text": "Extensible, with the ability to easily write plugins in Java or scripting languages." }, { "code": null, "e": 5695, "s": 5625, "text": "Instant access to new features with little or no extra configuration." }, { "code": null, "e": 5765, "s": 5695, "text": "Instant access to new features with little or no extra configuration." }, { "code": null, "e": 5889, "s": 5765, "text": "Model-based builds − Maven is able to build any number of projects into predefined output types such as jar, war, metadata." }, { "code": null, "e": 6013, "s": 5889, "text": "Model-based builds − Maven is able to build any number of projects into predefined output types such as jar, war, metadata." }, { "code": null, "e": 6182, "s": 6013, "text": "Coherent site of project information − Using the same metadata as per the build process, maven is able to generate a website and a PDF including complete documentation." }, { "code": null, "e": 6351, "s": 6182, "text": "Coherent site of project information − Using the same metadata as per the build process, maven is able to generate a website and a PDF including complete documentation." }, { "code": null, "e": 6538, "s": 6351, "text": "Release management and distribution publication − Without additional configuration, maven will integrate with your source control system such as CVS and manages the release of a project." }, { "code": null, "e": 6725, "s": 6538, "text": "Release management and distribution publication − Without additional configuration, maven will integrate with your source control system such as CVS and manages the release of a project." }, { "code": null, "e": 6887, "s": 6725, "text": "Backward Compatibility − You can easily port the multiple modules of a project into Maven 3 from older versions of Maven. It can support the older versions also." }, { "code": null, "e": 7049, "s": 6887, "text": "Backward Compatibility − You can easily port the multiple modules of a project into Maven 3 from older versions of Maven. It can support the older versions also." }, { "code": null, "e": 7144, "s": 7049, "text": "Automatic parent versioning − No need to specify the parent in the sub module for maintenance." }, { "code": null, "e": 7239, "s": 7144, "text": "Automatic parent versioning − No need to specify the parent in the sub module for maintenance." }, { "code": null, "e": 7421, "s": 7239, "text": "Parallel builds − It analyzes the project dependency graph and enables you to build schedule modules in parallel. Using this, you can achieve the performance improvements of 20-50%." }, { "code": null, "e": 7603, "s": 7421, "text": "Parallel builds − It analyzes the project dependency graph and enables you to build schedule modules in parallel. Using this, you can achieve the performance improvements of 20-50%." }, { "code": null, "e": 7779, "s": 7603, "text": "Better Error and Integrity Reporting − Maven improved error reporting, and it provides you with a link to the Maven wiki page where you will get full description of the error." }, { "code": null, "e": 7955, "s": 7779, "text": "Better Error and Integrity Reporting − Maven improved error reporting, and it provides you with a link to the Maven wiki page where you will get full description of the error." }, { "code": null, "e": 8063, "s": 7955, "text": "First of all, open the console and execute a java command based on the operating system you are working on." }, { "code": null, "e": 8119, "s": 8063, "text": "Let's verify the output for all the operating systems −" }, { "code": null, "e": 8147, "s": 8119, "text": "java 11.0.11 2021-04-20 LTS" }, { "code": null, "e": 8210, "s": 8147, "text": "Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)" }, { "code": null, "e": 8287, "s": 8210, "text": "Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)" }, { "code": null, "e": 8315, "s": 8287, "text": "java 11.0.11 2021-04-20 LTS" }, { "code": null, "e": 8378, "s": 8315, "text": "Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)" }, { "code": null, "e": 8455, "s": 8378, "text": "Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)" }, { "code": null, "e": 8483, "s": 8455, "text": "java 11.0.11 2021-04-20 LTS" }, { "code": null, "e": 8546, "s": 8483, "text": "Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)" }, { "code": null, "e": 8623, "s": 8546, "text": "Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)" }, { "code": null, "e": 8847, "s": 8623, "text": "If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link http://www.oracle.com. We are assuming Java 11.0.11 as the installed version for this tutorial." }, { "code": null, "e": 8980, "s": 8847, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example." }, { "code": null, "e": 9030, "s": 8980, "text": "Append Java compiler location to the System Path." }, { "code": null, "e": 9107, "s": 9030, "text": "Verify Java installation using the command java -version as explained above." }, { "code": null, "e": 9172, "s": 9107, "text": "Download Maven 3.8.4 from https://maven.apache.org/download.cgi." }, { "code": null, "e": 9313, "s": 9172, "text": "Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-3.8.4 will be created from the archive." }, { "code": null, "e": 9367, "s": 9313, "text": "Add M2_HOME, M2, MAVEN_OPTS to environment variables." }, { "code": null, "e": 9422, "s": 9367, "text": "Set the environment variables using system properties." }, { "code": null, "e": 9539, "s": 9422, "text": "M2_HOME=C:\\Program Files\\Apache Software Foundation\\apache-maven-3.8.4 M2=%M2_HOME%\\bin MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 9593, "s": 9539, "text": "Open command terminal and set environment variables. " }, { "code": null, "e": 9674, "s": 9593, "text": "export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4 export M2=$M2_HOME/bin" }, { "code": null, "e": 9710, "s": 9674, "text": "export MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 9763, "s": 9710, "text": "Open command terminal and set environment variables." }, { "code": null, "e": 9821, "s": 9763, "text": "export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4" }, { "code": null, "e": 9844, "s": 9821, "text": "export M2=$M2_HOME/bin" }, { "code": null, "e": 9880, "s": 9844, "text": "export MAVEN_OPTS=-Xms256m -Xmx512m" }, { "code": null, "e": 9919, "s": 9880, "text": "Now append M2 variable to System Path." }, { "code": null, "e": 9975, "s": 9919, "text": "Now open console and execute the following mvn command." }, { "code": null, "e": 10054, "s": 9975, "text": "Finally, verify the output of the above commands, which should be as follows −" }, { "code": null, "e": 10116, "s": 10054, "text": "Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)" }, { "code": null, "e": 10191, "s": 10116, "text": "Maven home: C:\\Program Files\\Apache Software Foundation\\apache-maven-3.8.4" }, { "code": null, "e": 10285, "s": 10191, "text": "Java version: 11.0.11, vendor: Oracle Corporation, runtime: C:\\Program Files\\Java\\jdk11.0.11\\" }, { "code": null, "e": 10334, "s": 10285, "text": "Default locale: en_IN, platform encoding: Cp1252" }, { "code": null, "e": 10407, "s": 10334, "text": "OS name: \"windows 10\", version: \"10.0\", arch: \"amd64\", family: \"windows\"" }, { "code": null, "e": 10469, "s": 10407, "text": "Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)" }, { "code": null, "e": 10491, "s": 10469, "text": "Java version: 11.0.11" }, { "code": null, "e": 10530, "s": 10491, "text": "Java home: /usr/local/java-current/jre" }, { "code": null, "e": 10592, "s": 10530, "text": "Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)" }, { "code": null, "e": 10614, "s": 10592, "text": "Java version: 11.0.11" }, { "code": null, "e": 10648, "s": 10614, "text": "Java home: /Library/Java/Home/jre" }, { "code": null, "e": 10806, "s": 10648, "text": "POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml." }, { "code": null, "e": 10925, "s": 10806, "text": "The POM contains information about the project and various configuration detail used by Maven to build the project(s)." }, { "code": null, "e": 11212, "s": 10925, "text": "POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are following −" }, { "code": null, "e": 11233, "s": 11212, "text": "project dependencies" }, { "code": null, "e": 11241, "s": 11233, "text": "plugins" }, { "code": null, "e": 11247, "s": 11241, "text": "goals" }, { "code": null, "e": 11262, "s": 11247, "text": "build profiles" }, { "code": null, "e": 11278, "s": 11262, "text": "project version" }, { "code": null, "e": 11289, "s": 11278, "text": "developers" }, { "code": null, "e": 11302, "s": 11289, "text": "mailing list" }, { "code": null, "e": 11491, "s": 11302, "text": "Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its version as these attributes help in uniquely identifying the project in repository." }, { "code": null, "e": 11875, "s": 11491, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.companyname.project-group</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n</project>" }, { "code": null, "e": 11951, "s": 11875, "text": "It should be noted that there should be a single POM file for each project." }, { "code": null, "e": 12051, "s": 11951, "text": "All POM files require the project element and three mandatory fields: groupId, artifactId, version." }, { "code": null, "e": 12151, "s": 12051, "text": "All POM files require the project element and three mandatory fields: groupId, artifactId, version." }, { "code": null, "e": 12214, "s": 12151, "text": "Projects notation in repository is groupId:artifactId:version." }, { "code": null, "e": 12277, "s": 12214, "text": "Projects notation in repository is groupId:artifactId:version." }, { "code": null, "e": 12310, "s": 12277, "text": "Minimal requirements for a POM −" }, { "code": null, "e": 12343, "s": 12310, "text": "Minimal requirements for a POM −" }, { "code": null, "e": 12356, "s": 12343, "text": "Project root" }, { "code": null, "e": 12476, "s": 12356, "text": "This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification." }, { "code": null, "e": 12490, "s": 12476, "text": "Model version" }, { "code": null, "e": 12521, "s": 12490, "text": "Model version should be 4.0.0." }, { "code": null, "e": 12529, "s": 12521, "text": "groupId" }, { "code": null, "e": 12703, "s": 12529, "text": "This is an Id of project's group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects." }, { "code": null, "e": 12714, "s": 12703, "text": "artifactId" }, { "code": null, "e": 12908, "s": 12714, "text": "This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact's location within the repository." }, { "code": null, "e": 12916, "s": 12908, "text": "version" }, { "code": null, "e": 13071, "s": 12916, "text": "This is the version of the project. Along with the groupId, It is used within an artifact's repository to separate versions from each other. For example −" }, { "code": null, "e": 13109, "s": 13071, "text": "com.company.bank:consumer-banking:1.0" }, { "code": null, "e": 13148, "s": 13109, "text": "com.company.bank:consumer-banking:1.1." }, { "code": null, "e": 13348, "s": 13148, "text": "The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default." }, { "code": null, "e": 13590, "s": 13348, "text": "Maven use the effective POM (configuration from super pom plus project configuration) to execute relevant goal. It helps developers to specify minimum configuration detail in his/her pom.xml. Although configurations can be overridden easily." }, { "code": null, "e": 13717, "s": 13590, "text": "An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom" }, { "code": null, "e": 13816, "s": 13717, "text": "Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom." }, { "code": null, "e": 13885, "s": 13816, "text": "In example below, We've created a pom.xml in C:\\MVN\\project folder. " }, { "code": null, "e": 13983, "s": 13885, "text": "Now open command console, go the folder containing pom.xml and execute the following mvn command." }, { "code": null, "e": 14022, "s": 13983, "text": "C:\\MVN\\project>mvn help:effective-pom\n" }, { "code": null, "e": 14081, "s": 14022, "text": "Maven will start processing and display the effective-pom." }, { "code": null, "e": 14851, "s": 14081, "text": "C:\\MVN>mvn help:effective-pom\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ---------------< com.companyname.project-group:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ project ---\n[INFO]\nEffective POMs, after inheritance, interpolation, and profiles are applied:\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.261 s\n[INFO] Finished at: 2021-12-10T19:54:53+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 14957, "s": 14851, "text": "Effective POM displayed as result in console, after inheritance, interpolation, and profiles are applied." }, { "code": null, "e": 23877, "s": 14957, "text": "<?xml version=\"1.0\" encoding=\"Cp1252\"?>\n<!-- ====================================================================== -->\n<!-- -->\n<!-- Generated by Maven Help Plugin on 2021-12-10T19:54:52+05:30 -->\n<!-- See: http://maven.apache.org/plugins/maven-help-plugin/ -->\n<!-- -->\n<!-- ====================================================================== -->\n<!-- ====================================================================== -->\n<!-- -->\n<!-- Effective POM for project -->\n<!-- 'com.companyname.project-group:project:jar:1.0' -->\n<!-- -->\n<!-- ====================================================================== -->\n<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\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.project-group</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <repositories>\n <repository>\n <snapshots>\n <enabled>false</enabled>\n </snapshots>\n <id>central</id>\n <name>Central Repository</name>\n <url>https://repo.maven.apache.org/maven2</url>\n </repository>\n </repositories>\n <pluginRepositories>\n <pluginRepository>\n <releases>\n <updatePolicy>never</updatePolicy>\n </releases>\n <snapshots>\n <enabled>false</enabled>\n </snapshots>\n <id>central</id>\n <name>Central Repository</name>\n <url>https://repo.maven.apache.org/maven2</url>\n </pluginRepository>\n </pluginRepositories>\n <build>\n <sourceDirectory>C:\\MVN\\src\\main\\java</sourceDirectory>\n <scriptSourceDirectory>C:\\MVN\\src\\main\\scripts</scriptSourceDirectory>\n <testSourceDirectory>C:\\MVN\\src\\test\\java</testSourceDirectory>\n <outputDirectory>C:\\MVN\\target\\classes</outputDirectory>\n <testOutputDirectory>C:\\MVN\\target\\test-classes</testOutputDirectory>\n <resources>\n <resource>\n <directory>C:\\MVN\\src\\main\\resources</directory>\n </resource>\n </resources>\n <testResources>\n <testResource>\n <directory>C:\\MVN\\src\\test\\resources</directory>\n </testResource>\n </testResources>\n <directory>C:\\MVN\\target</directory>\n <finalName>project-1.0</finalName>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.3</version>\n </plugin>\n <plugin>\n <artifactId>maven-assembly-plugin</artifactId>\n <version>2.2-beta-5</version>\n </plugin>\n <plugin>\n <artifactId>maven-dependency-plugin</artifactId>\n <version>2.8</version>\n </plugin>\n <plugin>\n <artifactId>maven-release-plugin</artifactId>\n <version>2.5.3</version>\n </plugin>\n </plugins>\n </pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-clean-plugin</artifactId>\n <version>2.5</version>\n <executions>\n <execution>\n <id>default-clean</id>\n <phase>clean</phase>\n <goals>\n <goal>clean</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>default-testResources</id>\n <phase>process-test-resources</phase>\n <goals>\n <goal>testResources</goal>\n </goals>\n </execution>\n <execution>\n <id>default-resources</id>\n <phase>process-resources</phase>\n <goals>\n <goal>resources</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-jar-plugin</artifactId>\n <version>2.4</version>\n <executions>\n <execution>\n <id>default-jar</id>\n <phase>package</phase>\n <goals>\n <goal>jar</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.1</version>\n <executions>\n <execution>\n <id>default-compile</id>\n <phase>compile</phase>\n <goals>\n <goal>compile</goal>\n </goals>\n </execution>\n <execution>\n <id>default-testCompile</id>\n <phase>test-compile</phase>\n <goals>\n <goal>testCompile</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>2.12.4</version>\n <executions>\n <execution>\n <id>default-test</id>\n <phase>test</phase>\n <goals>\n <goal>test</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-install-plugin</artifactId>\n <version>2.4</version>\n <executions>\n <execution>\n <id>default-install</id>\n <phase>install</phase>\n <goals>\n <goal>install</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-deploy-plugin</artifactId>\n <version>2.7</version>\n <executions>\n <execution>\n <id>default-deploy</id>\n <phase>deploy</phase>\n <goals>\n <goal>deploy</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-site-plugin</artifactId>\n <version>3.3</version>\n <executions>\n <execution>\n <id>default-site</id>\n <phase>site</phase>\n <goals>\n <goal>site</goal>\n </goals>\n <configuration>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n <reportPlugins>\n <reportPlugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n </reportPlugin>\n </reportPlugins>\n </configuration>\n </execution>\n <execution>\n <id>default-deploy</id>\n <phase>site-deploy</phase>\n <goals>\n <goal>deploy</goal>\n </goals>\n <configuration>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n <reportPlugins>\n <reportPlugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n </reportPlugin>\n </reportPlugins>\n </configuration>\n </execution>\n </executions>\n <configuration>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n <reportPlugins>\n <reportPlugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n </reportPlugin>\n </reportPlugins>\n </configuration>\n </plugin>\n </plugins>\n </build>\n <reporting>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n </reporting>\n</project>" }, { "code": null, "e": 24086, "s": 23877, "text": "In above pom.xml, you can see the default project source folders structure, output directory, plug-ins required, repositories, reporting directory, which Maven will be using while executing the desired goals." }, { "code": null, "e": 24264, "s": 24086, "text": "Maven pom.xml is also not required to be written manually. Maven provides numerous archetype plugins to create projects, which in order, create the project structure and pom.xml" }, { "code": null, "e": 24520, "s": 24264, "text": "A Build Lifecycle is a well-defined sequence of phases, which define the order in which the goals are to be executed. Here phase represents a stage in life cycle. As an example, a typical Maven Build Lifecycle consists of the following sequence of phases." }, { "code": null, "e": 24630, "s": 24520, "text": "There are always pre and post phases to register goals, which must run prior to, or after a particular phase." }, { "code": null, "e": 24772, "s": 24630, "text": "When Maven starts building a project, it steps through a defined sequence of phases and executes goals, which are registered with each phase." }, { "code": null, "e": 24824, "s": 24772, "text": "Maven has the following three standard lifecycles −" }, { "code": null, "e": 24830, "s": 24824, "text": "clean" }, { "code": null, "e": 24848, "s": 24830, "text": "default(or build)" }, { "code": null, "e": 24853, "s": 24848, "text": "site" }, { "code": null, "e": 25101, "s": 24853, "text": "A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation." }, { "code": null, "e": 25342, "s": 25101, "text": "The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases while the dependency:copy-dependencies is a goal." }, { "code": null, "e": 25390, "s": 25342, "text": "mvn clean dependency:copy-dependencies package\n" }, { "code": null, "e": 25530, "s": 25390, "text": "Here the clean phase will be executed first, followed by the dependency:copy-dependencies goal, and finally package phase will be executed." }, { "code": null, "e": 25640, "s": 25530, "text": "When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases." }, { "code": null, "e": 25650, "s": 25640, "text": "pre-clean" }, { "code": null, "e": 25656, "s": 25650, "text": "clean" }, { "code": null, "e": 25667, "s": 25656, "text": "post-clean" }, { "code": null, "e": 25907, "s": 25667, "text": "Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory. Thus, when mvn clean command executes, Maven deletes the build directory." }, { "code": null, "e": 26006, "s": 25907, "text": "We can customize this behavior by mentioning goals in any of the above phases of clean life cycle." }, { "code": null, "e": 26209, "s": 26006, "text": "In the following example, We'll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases. This will allow us to echo text messages displaying the phases of the clean lifecycle." }, { "code": null, "e": 26259, "s": 26209, "text": "We've created a pom.xml in C:\\MVN\\project folder." }, { "code": null, "e": 28180, "s": 26259, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.1</version>\n <executions>\n <execution>\n <id>id.pre-clean</id>\n <phase>pre-clean</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>pre-clean phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.clean</id>\n <phase>clean</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>clean phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.post-clean</id>\n <phase>post-clean</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>post-clean phase</echo>\n </tasks>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>" }, { "code": null, "e": 28281, "s": 28180, "text": "Now open command console, go to the folder containing pom.xml and execute the following mvn command." }, { "code": null, "e": 28312, "s": 28281, "text": "C:\\MVN\\project>mvn post-clean\n" }, { "code": null, "e": 28391, "s": 28312, "text": "Maven will start processing and displaying all the phases of clean life cycle." }, { "code": null, "e": 29501, "s": 28391, "text": "\nC:\\MVN>mvn post-clean\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.projectgroup:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (id.pre-clean) @ project ---\n[INFO] Executing tasks\n [echo] pre-clean phase\n[INFO] Executed tasks\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project ---\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project ---\n[INFO] Executing tasks\n [echo] clean phase\n[INFO] Executed tasks\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (id.post-clean) @ project ---\n[INFO] Executing tasks\n [echo] post-clean phase\n[INFO] Executed tasks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 0.740 s\n[INFO] Finished at: 2021-12-10T20:03:53+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 29626, "s": 29501, "text": "You can try tuning mvn clean command, which will display pre-clean and clean. Nothing will be executed for post-clean phase." }, { "code": null, "e": 29736, "s": 29626, "text": "This is the primary life cycle of Maven and is used to build the application. It has the following 21 phases." }, { "code": null, "e": 29745, "s": 29736, "text": "validate" }, { "code": null, "e": 29856, "s": 29745, "text": "Validates whether project is correct and all necessary information is available to complete the build process." }, { "code": null, "e": 29867, "s": 29856, "text": "initialize" }, { "code": null, "e": 29920, "s": 29867, "text": "Initializes build state, for example set properties." }, { "code": null, "e": 29937, "s": 29920, "text": "generate-sources" }, { "code": null, "e": 29999, "s": 29937, "text": "Generate any source code to be included in compilation phase." }, { "code": null, "e": 30015, "s": 29999, "text": "process-sources" }, { "code": null, "e": 30071, "s": 30015, "text": "Process the source code, for example, filter any value." }, { "code": null, "e": 30090, "s": 30071, "text": "generate-resources" }, { "code": null, "e": 30140, "s": 30090, "text": "Generate resources to be included in the package." }, { "code": null, "e": 30158, "s": 30140, "text": "process-resources" }, { "code": null, "e": 30248, "s": 30158, "text": "Copy and process the resources into the destination directory, ready for packaging phase." }, { "code": null, "e": 30256, "s": 30248, "text": "compile" }, { "code": null, "e": 30296, "s": 30256, "text": "Compile the source code of the project." }, { "code": null, "e": 30312, "s": 30296, "text": "process-classes" }, { "code": null, "e": 30432, "s": 30312, "text": "Post-process the generated files from compilation, for example to do bytecode enhancement/optimization on Java classes." }, { "code": null, "e": 30454, "s": 30432, "text": "generate-test-sources" }, { "code": null, "e": 30521, "s": 30454, "text": "Generate any test source code to be included in compilation phase." }, { "code": null, "e": 30542, "s": 30521, "text": "process-test-sources" }, { "code": null, "e": 30604, "s": 30542, "text": "Process the test source code, for example, filter any values." }, { "code": null, "e": 30617, "s": 30604, "text": "test-compile" }, { "code": null, "e": 30683, "s": 30617, "text": "Compile the test source code into the test destination directory." }, { "code": null, "e": 30704, "s": 30683, "text": "process-test-classes" }, { "code": null, "e": 30765, "s": 30704, "text": "Process the generated files from test code file compilation." }, { "code": null, "e": 30770, "s": 30765, "text": "test" }, { "code": null, "e": 30836, "s": 30770, "text": "Run tests using a suitable unit testing framework (Junit is one)." }, { "code": null, "e": 30852, "s": 30836, "text": "prepare-package" }, { "code": null, "e": 30935, "s": 30852, "text": "Perform any operations necessary to prepare a package before the actual packaging." }, { "code": null, "e": 30943, "s": 30935, "text": "package" }, { "code": null, "e": 31043, "s": 30943, "text": "Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR file." }, { "code": null, "e": 31064, "s": 31043, "text": "pre-integration-test" }, { "code": null, "e": 31178, "s": 31064, "text": "Perform actions required before integration tests are executed. For example, setting up the required environment." }, { "code": null, "e": 31195, "s": 31178, "text": "integration-test" }, { "code": null, "e": 31295, "s": 31195, "text": "Process and deploy the package if necessary into an environment where integration tests can be run." }, { "code": null, "e": 31317, "s": 31295, "text": "post-integration-test" }, { "code": null, "e": 31428, "s": 31317, "text": "Perform actions required after integration tests have been executed. For example, cleaning up the environment." }, { "code": null, "e": 31435, "s": 31428, "text": "verify" }, { "code": null, "e": 31512, "s": 31435, "text": "Run any check-ups to verify the package is valid and meets quality criteria." }, { "code": null, "e": 31520, "s": 31512, "text": "install" }, { "code": null, "e": 31628, "s": 31520, "text": "Install the package into the local repository, which can be used as a dependency in other projects locally." }, { "code": null, "e": 31635, "s": 31628, "text": "deploy" }, { "code": null, "e": 31733, "s": 31635, "text": "Copies the final package to the remote repository for sharing with other developers and projects." }, { "code": null, "e": 31824, "s": 31733, "text": "There are few important concepts related to Maven Lifecycles, which are worth to mention −" }, { "code": null, "e": 31948, "s": 31824, "text": "When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute." }, { "code": null, "e": 32072, "s": 31948, "text": "When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute." }, { "code": null, "e": 32203, "s": 32072, "text": "Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR)." }, { "code": null, "e": 32334, "s": 32203, "text": "Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR)." }, { "code": null, "e": 32526, "s": 32334, "text": "In the following example, we will attach maven-antrun-plugin:run goal to few of the phases of Build lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle." }, { "code": null, "e": 32574, "s": 32526, "text": "We've updated pom.xml in C:\\MVN\\project folder." }, { "code": null, "e": 35311, "s": 32574, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.1</version>\n <executions>\n <execution>\n <id>id.validate</id>\n <phase>validate</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>validate phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.compile</id>\n <phase>compile</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>compile phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.test</id>\n <phase>test</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>test phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.package</id>\n <phase>package</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>package phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.deploy</id>\n <phase>deploy</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>deploy phase</echo>\n </tasks>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>" }, { "code": null, "e": 35409, "s": 35311, "text": "Now open command console, go the folder containing pom.xml and execute the following mvn command." }, { "code": null, "e": 35437, "s": 35409, "text": "C:\\MVN\\project>mvn compile\n" }, { "code": null, "e": 35529, "s": 35437, "text": "Maven will start processing and display phases of build life cycle up to the compile phase." }, { "code": null, "e": 36796, "s": 35529, "text": "\nC:\\MVN>mvn compile\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.projectgroup:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (id.validate) @ project ---\n[INFO] Executing tasks\n [echo] validate phase\n[INFO] Executed tasks\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ project ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ project ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (id.compile) @ project ---\n[INFO] Executing tasks\n [echo] compile phase\n[INFO] Executed tasks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 3.033 s\n[INFO] Finished at: 2021-12-10T20:05:46+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 36929, "s": 36796, "text": "Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases −" }, { "code": null, "e": 36938, "s": 36929, "text": "pre-site" }, { "code": null, "e": 36943, "s": 36938, "text": "site" }, { "code": null, "e": 36953, "s": 36943, "text": "post-site" }, { "code": null, "e": 36965, "s": 36953, "text": "site-deploy" }, { "code": null, "e": 37153, "s": 36965, "text": "In the following example, we will attach maven-antrun-plugin:run goal to all the phases of Site lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle." }, { "code": null, "e": 37201, "s": 37153, "text": "We've updated pom.xml in C:\\MVN\\project folder." }, { "code": null, "e": 39949, "s": 37201, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-site-plugin</artifactId>\n <version>3.7</version>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n <version>2.9</version>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.1</version>\n <executions>\n <execution>\n <id>id.pre-site</id>\n <phase>pre-site</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>pre-site phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.site</id>\n <phase>site</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>site phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.post-site</id>\n <phase>post-site</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>post-site phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n <execution>\n <id>id.site-deploy</id>\n <phase>site-deploy</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>site-deploy phase</echo>\n </tasks>\n </configuration>\n </execution>\n \n </executions>\n </plugin>\n </plugins>\n </build>\n</project>" }, { "code": null, "e": 40051, "s": 39949, "text": "Now open the command console, go the folder containing pom.xml and execute the following mvn command." }, { "code": null, "e": 40076, "s": 40051, "text": "C:\\MVN\\project>mvn site\n" }, { "code": null, "e": 40167, "s": 40076, "text": "Maven will start processing and displaying the phases of site life cycle up to site phase." }, { "code": null, "e": 41411, "s": 40167, "text": "C:\\MVN>mvn site\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.projectgroup:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-antrun-plugin:3.0.0:run (id.pre-site) @ project ---\n[INFO] Executing tasks\n[WARNING] [echo] pre-site phase\n[INFO] Executed tasks\n[INFO]\n[INFO] --- maven-site-plugin:3.7:site (default-site) @ project ---\n[WARNING] Input file encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[WARNING] No project URL defined - decoration links will not be relativized!\n[INFO] Rendering site with org.apache.maven.skins:maven-default-skin:jar:1.2 skin.\n[INFO]\n[INFO] --- maven-antrun-plugin:3.0.0:run (id.site) @ project ---\n[INFO] Executing tasks\n[WARNING] [echo] site phase\n[INFO] Executed tasks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 4.323 s\n[INFO] Finished at: 2021-12-10T20:22:31+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 41652, "s": 41411, "text": "A Build profile is a set of configuration values, which can be used to set or override default values of Maven build. Using a build profile, you can customize build for different environments such as Production v/s Development environments." }, { "code": null, "e": 41978, "s": 41652, "text": "Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are triggered in variety of ways. Profiles modify the POM at build time, and are used to give parameters different target environments (for example, the path of the database server in the development, testing, and production environments)." }, { "code": null, "e": 42021, "s": 41978, "text": "Build profiles are majorly of three types." }, { "code": null, "e": 42077, "s": 42021, "text": "A Maven Build Profile can be activated in various ways." }, { "code": null, "e": 42117, "s": 42077, "text": "Explicitly using command console input." }, { "code": null, "e": 42141, "s": 42117, "text": "Through maven settings." }, { "code": null, "e": 42197, "s": 42141, "text": "Based on environment variables (User/System variables)." }, { "code": null, "e": 42240, "s": 42197, "text": "OS Settings (for example, Windows family)." }, { "code": null, "e": 42263, "s": 42240, "text": "Present/missing files." }, { "code": null, "e": 42329, "s": 42263, "text": "Let us assume the following directory structure of your project −" }, { "code": null, "e": 42405, "s": 42329, "text": "Now, under src/main/resources, there are three environment specific files −" }, { "code": null, "e": 42420, "s": 42405, "text": "env.properties" }, { "code": null, "e": 42475, "s": 42420, "text": "default configuration used if no profile is mentioned." }, { "code": null, "e": 42495, "s": 42475, "text": "env.test.properties" }, { "code": null, "e": 42541, "s": 42495, "text": "test configuration when test profile is used." }, { "code": null, "e": 42561, "s": 42541, "text": "env.prod.properties" }, { "code": null, "e": 42613, "s": 42561, "text": "production configuration when prod profile is used." }, { "code": null, "e": 42887, "s": 42613, "text": "In the following example, we will attach maven-antrun-plugin:run goal to test the phase. This will allow us to echo text messages for different profiles. We will be using pom.xml to define different profiles and will activate profile at command console using maven command." }, { "code": null, "e": 42957, "s": 42887, "text": "Assume, we've created the following pom.xml in C:\\MVN\\project folder." }, { "code": null, "e": 44397, "s": 42957, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <profiles>\n <profile>\n <id>test</id>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.1</version>\n <executions>\n <execution>\n <phase>test</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>Using env.test.properties</echo>\n <copy file=\"src/main/resources/env.test.properties\"\n tofile=\"${project.build.outputDirectory}/env.properties\"/>\n </tasks>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n </profile>\n </profiles>\n</project>" }, { "code": null, "e": 44553, "s": 44397, "text": "Now open the command console, go to the folder containing pom.xml and execute the following mvn command. Pass the profile name as argument using -P option." }, { "code": null, "e": 44585, "s": 44553, "text": "C:\\MVN\\project>mvn test -Ptest\n" }, { "code": null, "e": 44662, "s": 44585, "text": "Maven will start processing and displaying the result of test build profile." }, { "code": null, "e": 46260, "s": 44662, "text": "\nC:\\MVN>mvn test -Ptest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.projectgroup:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ project ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] Copying 3 resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ project ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ project ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ project ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ project ---\n[INFO] No tests to run.\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (default) @ project ---\n[INFO] Executing tasks\n [echo] Using env.test.properties\n[INFO] Executed tasks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.011 s\n[INFO] Finished at: 2021-12-10T20:29:39+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 46318, "s": 46260, "text": "Now as an exercise, you can perform the following steps −" }, { "code": null, "e": 46451, "s": 46318, "text": "Add another profile element to profiles element of pom.xml (copy existing profile element and paste it where profile elements ends)." }, { "code": null, "e": 46584, "s": 46451, "text": "Add another profile element to profiles element of pom.xml (copy existing profile element and paste it where profile elements ends)." }, { "code": null, "e": 46639, "s": 46584, "text": "Update id of this profile element from test to normal." }, { "code": null, "e": 46694, "s": 46639, "text": "Update id of this profile element from test to normal." }, { "code": null, "e": 46782, "s": 46694, "text": "Update task section to echo env.properties and copy env.properties to target directory." }, { "code": null, "e": 46870, "s": 46782, "text": "Update task section to echo env.properties and copy env.properties to target directory." }, { "code": null, "e": 46966, "s": 46870, "text": "Again repeat the above three steps, update id to prod and task section for env.prod.properties." }, { "code": null, "e": 47062, "s": 46966, "text": "Again repeat the above three steps, update id to prod and task section for env.prod.properties." }, { "code": null, "e": 47132, "s": 47062, "text": "That's all. Now you've three build profiles ready (normal/test/prod)." }, { "code": null, "e": 47202, "s": 47132, "text": "That's all. Now you've three build profiles ready (normal/test/prod)." }, { "code": null, "e": 47360, "s": 47202, "text": "Now open the command console, go to the folder containing pom.xml and execute the following mvn commands. Pass the profile names as argument using -P option." }, { "code": null, "e": 47426, "s": 47360, "text": "C:\\MVN\\project>mvn test -Pnormal\n\nC:\\MVN\\project>mvn test -Pprod\n" }, { "code": null, "e": 47479, "s": 47426, "text": "Check the output of the build to see the difference." }, { "code": null, "e": 47659, "s": 47479, "text": "Open Maven settings.xml file available in %USER_HOME%/.m2 directory where %USER_HOME% represents the user home directory. If settings.xml file is not there, then create a new one." }, { "code": null, "e": 47751, "s": 47659, "text": "Add test profile as an active profile using active Profiles node as shown below in example." }, { "code": null, "e": 48314, "s": 47751, "text": "<settings 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 http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n <mirrors>\n <mirror>\n <id>maven.dev.snaponglobal.com</id>\n <name>Internal Artifactory Maven repository</name>\n <url>http://repo1.maven.org/maven2/</url>\n <mirrorOf>*</mirrorOf>\n </mirror>\n </mirrors>\n <activeProfiles>\n <activeProfile>test</activeProfile>\n </activeProfiles>\n</settings>" }, { "code": null, "e": 48528, "s": 48314, "text": "Now open command console, go to the folder containing pom.xml and execute the following mvn command. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile." }, { "code": null, "e": 48553, "s": 48528, "text": "C:\\MVN\\project>mvn test\n" }, { "code": null, "e": 48711, "s": 48553, "text": "Now remove active profile from maven settings.xml and update the test profile mentioned in pom.xml. Add activation element to profile element as shown below." }, { "code": null, "e": 48874, "s": 48711, "text": "The test profile will trigger when the system property \"env\" is specified with the value \"test\". Create an environment variable \"env\" and set its value as \"test\"." }, { "code": null, "e": 49035, "s": 48874, "text": "<profile>\n <id>test</id>\n <activation>\n <property>\n <name>env</name>\n <value>test</value>\n </property>\n </activation>\n</profile>" }, { "code": null, "e": 49138, "s": 49035, "text": "Let's open command console, go to the folder containing pom.xml and execute the following mvn command." }, { "code": null, "e": 49163, "s": 49138, "text": "C:\\MVN\\project>mvn test\n" }, { "code": null, "e": 49281, "s": 49163, "text": "Activation element to include os detail as shown below. This test profile will trigger when the system is windows XP." }, { "code": null, "e": 49505, "s": 49281, "text": "<profile>\n <id>test</id>\n <activation>\n <os>\n <name>Windows XP</name>\n <family>Windows</family>\n <arch>x86</arch>\n <version>5.1.2600</version>\n </os>\n </activation>\n</profile>" }, { "code": null, "e": 49720, "s": 49505, "text": "Now open command console, go to the folder containing pom.xml and execute the following mvn commands. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile." }, { "code": null, "e": 49745, "s": 49720, "text": "C:\\MVN\\project>mvn test\n" }, { "code": null, "e": 49920, "s": 49745, "text": "Now activation element to include OS details as shown below. The test profile will trigger when target/generated-sources/axistools/wsdl2java/com/companyname/group is missing." }, { "code": null, "e": 50125, "s": 49920, "text": "<profile>\n <id>test</id>\n <activation>\n <file>\n <missing>target/generated-sources/axistools/wsdl2java/\n com/companyname/group</missing>\n </file>\n </activation>\n</profile>" }, { "code": null, "e": 50344, "s": 50125, "text": "Now open the command console, go to the folder containing pom.xml and execute the following mvn commands. Do not pass the profile name using -P option. Maven will display result of test profile being an active profile." }, { "code": null, "e": 50369, "s": 50344, "text": "C:\\MVN\\project>mvn test\n" }, { "code": null, "e": 50552, "s": 50369, "text": "In Maven terminology, a repository is a directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily." }, { "code": null, "e": 50663, "s": 50552, "text": "Maven repository are of three types. The following illustration will give an idea regarding these three types." }, { "code": null, "e": 50669, "s": 50663, "text": "local" }, { "code": null, "e": 50677, "s": 50669, "text": "central" }, { "code": null, "e": 50684, "s": 50677, "text": "remote" }, { "code": null, "e": 50812, "s": 50684, "text": "Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time." }, { "code": null, "e": 51122, "s": 50812, "text": "Maven local repository keeps your project's all dependencies (library jars, plugin jars etc.). When you run a Maven build, then Maven automatically downloads all the dependency jars into the local repository. It helps to avoid references to dependencies stored on remote machine every time a project is build." }, { "code": null, "e": 51324, "s": 51122, "text": "Maven local repository by default get created by Maven in %USER_HOME% directory. To override the default location, mention another path in Maven settings.xml file available at %M2_HOME%\\conf directory." }, { "code": null, "e": 51630, "s": 51324, "text": "<settings xmlns = \"http://maven.apache.org/SETTINGS/1.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/SETTINGS/1.0.0 \n http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n <localRepository>C:/MyLocalRepository</localRepository>\n</settings>" }, { "code": null, "e": 51712, "s": 51630, "text": "When you run Maven command, Maven will download dependencies to your custom path." }, { "code": null, "e": 51835, "s": 51712, "text": "Maven central repository is repository provided by Maven community. It contains a large number of commonly used libraries." }, { "code": null, "e": 51992, "s": 51835, "text": "When Maven does not find any dependency in local repository, it starts searching in central repository using following URL − https://repo1.maven.org/maven2/" }, { "code": null, "e": 52044, "s": 51992, "text": "Key concepts of Central repository are as follows −" }, { "code": null, "e": 52091, "s": 52044, "text": "This repository is managed by Maven community." }, { "code": null, "e": 52128, "s": 52091, "text": "It is not required to be configured." }, { "code": null, "e": 52172, "s": 52128, "text": "It requires internet access to be searched." }, { "code": null, "e": 52388, "s": 52172, "text": "To browse the content of central maven repository, maven community has provided a URL − https://search.maven.org/#browse. Using this library, a developer can search all the available libraries in central repository." }, { "code": null, "e": 52710, "s": 52388, "text": "Sometimes, Maven does not find a mentioned dependency in central repository as well. It then stops the build process and output error message to console. To prevent such situation, Maven provides concept of Remote Repository, which is developer's own custom repository containing required libraries or other project jars." }, { "code": null, "e": 52879, "s": 52710, "text": "For example, using below mentioned POM.xml, Maven will download dependency (not available in central repository) from Remote Repositories mentioned in the same pom.xml." }, { "code": null, "e": 53783, "s": 52879, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <dependencies>\n <dependency>\n <groupId>com.companyname.common-lib</groupId>\n <artifactId>common-lib</artifactId>\n <version>1.0.0</version>\n </dependency>\n <dependencies>\n <repositories>\n <repository>\n <id>companyname.lib1</id>\n <url>http://download.companyname.org/maven2/lib1</url>\n </repository>\n <repository>\n <id>companyname.lib2</id>\n <url>http://download.companyname.org/maven2/lib2</url>\n </repository>\n </repositories>\n</project>" }, { "code": null, "e": 53895, "s": 53783, "text": "When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence −" }, { "code": null, "e": 54009, "s": 53895, "text": "Step 1 − Search dependency in local repository, if not found, move to step 2 else perform the further processing." }, { "code": null, "e": 54123, "s": 54009, "text": "Step 1 − Search dependency in local repository, if not found, move to step 2 else perform the further processing." }, { "code": null, "e": 54323, "s": 54123, "text": "Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference." }, { "code": null, "e": 54523, "s": 54323, "text": "Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference." }, { "code": null, "e": 54659, "s": 54523, "text": "Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency)." }, { "code": null, "e": 54795, "s": 54659, "text": "Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency)." }, { "code": null, "e": 55013, "s": 54795, "text": "Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency)." }, { "code": null, "e": 55231, "s": 55013, "text": "Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency)." }, { "code": null, "e": 55362, "s": 55231, "text": "Maven is actually a plugin execution framework where every task is actually done by plugins. Maven Plugins are generally used to −" }, { "code": null, "e": 55378, "s": 55362, "text": "create jar file" }, { "code": null, "e": 55394, "s": 55378, "text": "create war file" }, { "code": null, "e": 55413, "s": 55394, "text": "compile code files" }, { "code": null, "e": 55434, "s": 55413, "text": "unit testing of code" }, { "code": null, "e": 55463, "s": 55434, "text": "create project documentation" }, { "code": null, "e": 55486, "s": 55463, "text": "create project reports" }, { "code": null, "e": 55581, "s": 55486, "text": "A plugin generally provides a set of goals, which can be executed using the following syntax −" }, { "code": null, "e": 55612, "s": 55581, "text": "mvn [plugin-name]:[goal-name]\n" }, { "code": null, "e": 55736, "s": 55612, "text": "For example, a Java project can be compiled with the maven-compiler-plugin's compile-goal by running the following command." }, { "code": null, "e": 55758, "s": 55736, "text": "mvn compiler:compile\n" }, { "code": null, "e": 55810, "s": 55758, "text": "Maven provided the following two types of Plugins −" }, { "code": null, "e": 55824, "s": 55810, "text": "Build plugins" }, { "code": null, "e": 55923, "s": 55824, "text": "They execute during the build process and should be configured in the <build/> element of pom.xml." }, { "code": null, "e": 55941, "s": 55923, "text": "Reporting plugins" }, { "code": null, "e": 56063, "s": 55941, "text": "They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml." }, { "code": null, "e": 56109, "s": 56063, "text": "Following is the list of few common plugins −" }, { "code": null, "e": 56115, "s": 56109, "text": "clean" }, { "code": null, "e": 56179, "s": 56115, "text": "Cleans up target after the build. Deletes the target directory." }, { "code": null, "e": 56188, "s": 56179, "text": "compiler" }, { "code": null, "e": 56216, "s": 56188, "text": "Compiles Java source files." }, { "code": null, "e": 56225, "s": 56216, "text": "surefire" }, { "code": null, "e": 56274, "s": 56225, "text": "Runs the JUnit unit tests. Creates test reports." }, { "code": null, "e": 56278, "s": 56274, "text": "jar" }, { "code": null, "e": 56322, "s": 56278, "text": "Builds a JAR file from the current project." }, { "code": null, "e": 56326, "s": 56322, "text": "war" }, { "code": null, "e": 56370, "s": 56326, "text": "Builds a WAR file from the current project." }, { "code": null, "e": 56378, "s": 56370, "text": "javadoc" }, { "code": null, "e": 56413, "s": 56378, "text": "Generates Javadoc for the project." }, { "code": null, "e": 56420, "s": 56413, "text": "antrun" }, { "code": null, "e": 56483, "s": 56420, "text": "Runs a set of ant tasks from any phase mentioned of the build." }, { "code": null, "e": 56491, "s": 56483, "text": "Example" }, { "code": null, "e": 56690, "s": 56491, "text": "We've used maven-antrun-plugin extensively in our examples to print data on console. Refer Build Profiles chapter. Let us understand it in a better way and create a pom.xml in C:\\MVN\\project folder." }, { "code": null, "e": 57767, "s": 56690, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.1</version>\n <executions>\n <execution>\n <id>id.clean</id>\n <phase>clean</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <tasks>\n <echo>clean phase</echo>\n </tasks>\n </configuration>\n </execution> \n </executions>\n </plugin>\n </plugins>\n </build>\n</project>" }, { "code": null, "e": 57877, "s": 57767, "text": "Next, open the command console and go to the folder containing pom.xml and execute the following mvn command." }, { "code": null, "e": 57903, "s": 57877, "text": "C:\\MVN\\project>mvn clean\n" }, { "code": null, "e": 57983, "s": 57903, "text": "Maven will start processing and displaying the clean phase of clean life cycle." }, { "code": null, "e": 58819, "s": 57983, "text": "C:\\MVN>mvn clean\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.projectgroup:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project ---\n[INFO] Deleting C:\\MVN\\target\n[INFO]\n[INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project ---\n[INFO] Executing tasks\n [echo] clean phase\n[INFO] Executed tasks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 1.266 s\n[INFO] Finished at: 2021-12-13T13:58:10+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 58878, "s": 58819, "text": "The above example illustrates the following key concepts −" }, { "code": null, "e": 58934, "s": 58878, "text": "Plugins are specified in pom.xml using plugins element." }, { "code": null, "e": 58990, "s": 58934, "text": "Plugins are specified in pom.xml using plugins element." }, { "code": null, "e": 59027, "s": 58990, "text": "Each plugin can have multiple goals." }, { "code": null, "e": 59064, "s": 59027, "text": "Each plugin can have multiple goals." }, { "code": null, "e": 59181, "s": 59064, "text": "You can define phase from where plugin should starts its processing using its phase element. We've used clean phase." }, { "code": null, "e": 59298, "s": 59181, "text": "You can define phase from where plugin should starts its processing using its phase element. We've used clean phase." }, { "code": null, "e": 59433, "s": 59298, "text": "You can configure tasks to be executed by binding them to goals of plugin. We've bound echo task with run goal of maven-antrun-plugin." }, { "code": null, "e": 59568, "s": 59433, "text": "You can configure tasks to be executed by binding them to goals of plugin. We've bound echo task with run goal of maven-antrun-plugin." }, { "code": null, "e": 59667, "s": 59568, "text": "Maven will then download the plugin if not available in local repository and start its processing." }, { "code": null, "e": 59766, "s": 59667, "text": "Maven will then download the plugin if not available in local repository and start its processing." }, { "code": null, "e": 59985, "s": 59766, "text": "Maven uses archetype plugins to create projects. To create a simple java application, we'll use maven-archetype-quickstart plugin. In example below, we'll create a maven based java application project in C:\\MVN folder." }, { "code": null, "e": 60152, "s": 59985, "text": "Let's open the command console, go to the C:\\MVN directory and execute the following mvn command. Make sure that C:\\MVN directory is empty before running the command." }, { "code": null, "e": 60327, "s": 60152, "text": "C:\\MVN>mvn archetype:generate\n-DgroupId = com.companyname.bank \n-DartifactId = consumerBanking \n-DarchetypeArtifactId = maven-archetype-quickstart \n-DinteractiveMode = false\n" }, { "code": null, "e": 60420, "s": 60327, "text": "Maven will start processing and will create the complete java application project structure." }, { "code": null, "e": 62200, "s": 60420, "text": "C:\\MVN>mvn archetype:generate -DgroupId=com.companyname.bank -DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------< org.apache.maven:standalone-pom >-------------------\n[INFO] Building Maven Stub Project (No POM) 1\n[INFO] --------------------------------[ pom ]---------------------------------\n[INFO]\n[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>>\n[INFO]\n[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<<\n[INFO]\n[INFO]\n[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---\n[INFO] Generating project in Batch mode\n[INFO] ----------------------------------------------------------------------------\n[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0\n[INFO] ----------------------------------------------------------------------------\n[INFO] Parameter: basedir, Value: C:\\MVN\n[INFO] Parameter: package, Value: com.companyname.bank\n[INFO] Parameter: groupId, Value: com.companyname.bank\n[INFO] Parameter: artifactId, Value: consumerBanking\n[INFO] Parameter: packageName, Value: com.companyname.bank\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] project created from Old (1.x) Archetype in dir: C:\\MVN\\consumerBanking\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 9.396 s\n[INFO] Finished at: 2021-12-13T15:13:00+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n" }, { "code": null, "e": 62384, "s": 62200, "text": "Now go to C:/MVN directory. You'll see a java application project created, named consumer Banking (as specified in artifactId). Maven uses a standard directory layout as shown below −" }, { "code": null, "e": 62456, "s": 62384, "text": "Using the above example, we can understand the following key concepts −" }, { "code": null, "e": 62472, "s": 62456, "text": "consumerBanking" }, { "code": null, "e": 62504, "s": 62472, "text": "contains src folder and pom.xml" }, { "code": null, "e": 62518, "s": 62504, "text": "src/main/java" }, { "code": null, "e": 62595, "s": 62518, "text": "contains java code files under the package structure (com/companyName/bank)." }, { "code": null, "e": 62609, "s": 62595, "text": "src/main/test" }, { "code": null, "e": 62691, "s": 62609, "text": "contains test java code files under the package structure (com/companyName/bank)." }, { "code": null, "e": 62710, "s": 62691, "text": "src/main/resources" }, { "code": null, "e": 62809, "s": 62710, "text": "it contains images/properties files (In above example, we need to create this structure manually)." }, { "code": null, "e": 63003, "s": 62809, "text": "If you observe, you will find that Maven also created a sample Java Source file and Java Test file. Open C:\\MVN\\consumerBanking\\src\\main\\java\\com\\companyname\\bank folder, you will see App.java." }, { "code": null, "e": 63176, "s": 63003, "text": "package com.companyname.bank;\n\n/**\n * Hello world!\n *\n */\npublic class App {\n public static void main( String[] args ){\n System.out.println( \"Hello World!\" );\n }\n}" }, { "code": null, "e": 63267, "s": 63176, "text": "Open C:\\MVN\\consumerBanking\\src\\test\\java\\com\\companyname\\bank folder to see AppTest.java." }, { "code": null, "e": 63867, "s": 63267, "text": "package com.companyname.bank;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Unit test for simple App.\n */\npublic class AppTest extends TestCase {\n /**\n * Create the test case\n *\n * @param testName name of the test case\n */\n public AppTest( String testName ) {\n super( testName );\n }\n\n /**\n * @return the suite of tests being tested\n */\n public static Test suite() {\n return new TestSuite( AppTest.class );\n }\n\n /**\n * Rigourous Test :-)\n */\n public void testApp() {\n assertTrue( true );\n }\n}" }, { "code": null, "e": 63994, "s": 63867, "text": "Developers are required to place their files as mentioned in table above and Maven handles all the build related complexities." }, { "code": null, "e": 64099, "s": 63994, "text": "In the next chapter, we'll discuss how to build and test the project using maven Build and Test Project." }, { "code": null, "e": 64244, "s": 64099, "text": "What we learnt in Project Creation chapter is how to create a Java application using Maven. Now we'll see how to build and test the application." }, { "code": null, "e": 64446, "s": 64244, "text": "Go to C:/MVN directory where you've created your java application. Open consumerBanking folder. You will see the POM.xml file with the following contents. Update it to reflect the current java version." }, { "code": null, "e": 65157, "s": 64446, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <properties>\n <maven.compiler.source>11</maven.compiler.source>\n <maven.compiler.target>11</maven.compiler.target>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n </dependency>\n </dependencies> \n</project>" }, { "code": null, "e": 65369, "s": 65157, "text": "Here you can see, Maven already added Junit as test framework. By default, Maven adds a source file App.java and a test file AppTest.java in its default directory structure, as discussed in the previous chapter." }, { "code": null, "e": 65480, "s": 65369, "text": "Let's open the command console, go the C:\\MVN\\consumerBanking directory and execute the following mvn command." }, { "code": null, "e": 65522, "s": 65480, "text": "C:\\MVN\\consumerBanking>mvn clean package\n" }, { "code": null, "e": 65561, "s": 65522, "text": "Maven will start building the project." }, { "code": null, "e": 68225, "s": 65561, "text": "C:\\MVN\\consumerBanking>mvn clean package\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.bank:consumerBanking >----------------\n[INFO] Building consumerBanking 1.0-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking ---\n[INFO] Deleting C:\\MVN\\consumerBanking\\target\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 1 source file to C:\\MVN\\consumerBanking\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 1 source file to C:\\MVN\\consumerBanking\\target\\test-classes\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking ---\n[INFO] Surefire report directory: C:\\MVN\\consumerBanking\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.companyname.bank.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO]\n[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking ---\n[INFO] Building jar: C:\\MVN\\consumerBanking\\target\\consumerBanking-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 4.663 s\n[INFO] Finished at: 2021-12-13T17:34:27+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN\\consumerBanking>\n" }, { "code": null, "e": 68321, "s": 68225, "text": "You've built your project and created final jar file, following are the key learning concepts −" }, { "code": null, "e": 68450, "s": 68321, "text": "We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package)." }, { "code": null, "e": 68579, "s": 68450, "text": "We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package)." }, { "code": null, "e": 68675, "s": 68579, "text": "Packaged jar is available in consumerBanking\\target folder as consumerBanking-1.0-SNAPSHOT.jar." }, { "code": null, "e": 68771, "s": 68675, "text": "Packaged jar is available in consumerBanking\\target folder as consumerBanking-1.0-SNAPSHOT.jar." }, { "code": null, "e": 68849, "s": 68771, "text": "Test reports are available in consumerBanking\\target\\surefire-reports folder." }, { "code": null, "e": 68927, "s": 68849, "text": "Test reports are available in consumerBanking\\target\\surefire-reports folder." }, { "code": null, "e": 69006, "s": 68927, "text": "Maven compiles the source code file(s) and then tests the source code file(s)." }, { "code": null, "e": 69085, "s": 69006, "text": "Maven compiles the source code file(s) and then tests the source code file(s)." }, { "code": null, "e": 69117, "s": 69085, "text": "Then Maven runs the test cases." }, { "code": null, "e": 69149, "s": 69117, "text": "Then Maven runs the test cases." }, { "code": null, "e": 69185, "s": 69149, "text": "Finally, Maven creates the package." }, { "code": null, "e": 69221, "s": 69185, "text": "Finally, Maven creates the package." }, { "code": null, "e": 69346, "s": 69221, "text": "Now open the command console, go the C:\\MVN\\consumerBanking\\target\\classes directory and execute the following java command." }, { "code": null, "e": 69378, "s": 69346, "text": ">java com.companyname.bank.App\n" }, { "code": null, "e": 69415, "s": 69378, "text": "You will see the result as follows −" }, { "code": null, "e": 69429, "s": 69415, "text": "Hello World!\n" }, { "code": null, "e": 69601, "s": 69429, "text": "Let's see how we can add additional Java files in our project. Open C:\\MVN\\consumerBanking\\src\\main\\java\\com\\companyname\\bank folder, create Util class in it as Util.java." }, { "code": null, "e": 69746, "s": 69601, "text": "package com.companyname.bank;\n\npublic class Util {\n public static void printMessage(String message){\n System.out.println(message);\n }\n}" }, { "code": null, "e": 69786, "s": 69746, "text": "Update the App class to use Util class." }, { "code": null, "e": 69954, "s": 69786, "text": "package com.companyname.bank;\n\n/**\n* Hello world!\n*\n*/\n\npublic class App {\n public static void main( String[] args ){\n Util.printMessage(\"Hello World!\");\n }\n}" }, { "code": null, "e": 70063, "s": 69954, "text": "Now open the command console, go the C:\\MVN\\consumerBanking directory and execute the following mvn command." }, { "code": null, "e": 70083, "s": 70063, "text": ">mvn clean compile\n" }, { "code": null, "e": 70214, "s": 70083, "text": "After Maven build is successful, go to the C:\\MVN\\consumerBanking\\target\\classes directory and execute the following java command." }, { "code": null, "e": 70249, "s": 70214, "text": ">java -cp com.companyname.bank.App" }, { "code": null, "e": 70286, "s": 70249, "text": "You will see the result as follows −" }, { "code": null, "e": 70300, "s": 70286, "text": "Hello World!\n" }, { "code": null, "e": 70565, "s": 70300, "text": "As you know, Maven does the dependency management using the concept of Repositories. But what happens if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency." }, { "code": null, "e": 70669, "s": 70565, "text": "For example, let us do the following changes to the project created in ‘Creating Java Project’ chapter." }, { "code": null, "e": 70703, "s": 70669, "text": "Add lib folder to the src folder." }, { "code": null, "e": 70737, "s": 70703, "text": "Add lib folder to the src folder." }, { "code": null, "e": 70842, "s": 70737, "text": "Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations." }, { "code": null, "e": 70947, "s": 70842, "text": "Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations." }, { "code": null, "e": 71006, "s": 70947, "text": "Now our project structure should look like the following −" }, { "code": null, "e": 71334, "s": 71006, "text": "Here you are having your own library, specific to the project, which is an usual case and it contains jars, which may not be available in any repository for maven to download from. If your code is using this library with Maven, then Maven build will fail as it cannot download or refer to this library during compilation phase." }, { "code": null, "e": 71436, "s": 71334, "text": "To handle the situation, let's add this external dependency to maven pom.xml using the following way." }, { "code": null, "e": 72385, "s": 71436, "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 http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.bank</groupId>\n <artifactId>consumerBanking</artifactId>\n <packaging>jar</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>consumerBanking</name>\n <url>http://maven.apache.org</url>\n\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n\n <dependency>\n <groupId>ldapjdk</groupId>\n <artifactId>ldapjdk</artifactId>\n <scope>system</scope>\n <version>1.0</version>\n <systemPath>${basedir}\\src\\lib\\ldapjdk.jar</systemPath>\n </dependency>\n </dependencies>\n\n</project>" }, { "code": null, "e": 72531, "s": 72385, "text": "Look at the second dependency element under dependencies in the above example, which clears the following key concepts about External Dependency." }, { "code": null, "e": 72640, "s": 72531, "text": "External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies." }, { "code": null, "e": 72749, "s": 72640, "text": "External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies." }, { "code": null, "e": 72798, "s": 72749, "text": "Specify groupId same as the name of the library." }, { "code": null, "e": 72847, "s": 72798, "text": "Specify groupId same as the name of the library." }, { "code": null, "e": 72899, "s": 72847, "text": "Specify artifactId same as the name of the library." }, { "code": null, "e": 72951, "s": 72899, "text": "Specify artifactId same as the name of the library." }, { "code": null, "e": 72976, "s": 72951, "text": "Specify scope as system." }, { "code": null, "e": 73001, "s": 72976, "text": "Specify scope as system." }, { "code": null, "e": 73055, "s": 73001, "text": "Specify system path relative to the project location." }, { "code": null, "e": 73109, "s": 73055, "text": "Specify system path relative to the project location." }, { "code": null, "e": 73237, "s": 73109, "text": "Hope now you are clear about external dependencies and you will be able to specify external dependencies in your Maven project." }, { "code": null, "e": 73541, "s": 73237, "text": "This tutorial will teach you how to create documentation of the application in one go. So let's start, go to C:/MVN directory where you had created your java consumerBanking application using the examples given in the previous chapters. Open consumerBanking folder and execute the following mvn command." }, { "code": null, "e": 73610, "s": 73541, "text": "Update, the pom.xml in C:\\MVN\\consumerBanking folder as shown below." }, { "code": null, "e": 74882, "s": 73610, "text": "<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 http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.bank</groupId>\n <artifactId>consumerBanking</artifactId>\n <packaging>jar</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>consumerBanking</name>\n <url>http://maven.apache.org</url>\n <properties>\n <maven.compiler.source>11</maven.compiler.source>\n <maven.compiler.target>11</maven.compiler.target>\n </properties>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-site-plugin</artifactId>\n <version>3.7</version>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n <version>2.9</version>\n </plugin>\n </plugins>\n </build>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 74915, "s": 74882, "text": "C:\\MVN\\consumerBanking>mvn site\n" }, { "code": null, "e": 74954, "s": 74915, "text": "Maven will start building the project." }, { "code": null, "e": 75913, "s": 74954, "text": "[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.bank:consumerBanking >----------------\n[INFO] Building consumerBanking 1.0-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-site-plugin:3.7:site (default-site) @ consumerBanking ---\n[WARNING] Input file encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Relativizing decoration links with respect to localized project URL: http://maven.apache.org\n[INFO] Rendering site with org.apache.maven.skins:maven-default-skin:jar:1.2 skin.\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 5.850 s\n[INFO] Finished at: 2021-12-13T17:49:56+05:30\n[INFO] ------------------------------------------------------------------------\n" }, { "code": null, "e": 76008, "s": 75913, "text": "Your project documentation is now ready. Maven has created a site within the target directory." }, { "code": null, "e": 76102, "s": 76008, "text": "Open C:\\MVN\\consumerBanking\\target\\site folder. Click on index.html to see the documentation." }, { "code": null, "e": 76389, "s": 76102, "text": "Maven creates the documentation using a documentation-processing engine called Doxia which reads multiple source formats into a common document model. To write documentation for your project, you can write your content in a following few commonly used formats which are parsed by Doxia." }, { "code": null, "e": 76421, "s": 76389, "text": "https://jakarta.apache.org/site" }, { "code": null, "e": 76446, "s": 76421, "text": "https://maven.apache.org" }, { "code": null, "e": 76658, "s": 76446, "text": "Maven provides users, a very large list of different types of project templates (614 in numbers) using the concept of Archetype. Maven helps users to quickly start a new java project using the following command." }, { "code": null, "e": 76682, "s": 76658, "text": "mvn archetype:generate\n" }, { "code": null, "e": 76865, "s": 76682, "text": "Archetype is a Maven plugin whose task is to create a project structure as per its template. We are going to use quickstart archetype plugin to create a simple java application here." }, { "code": null, "e": 76966, "s": 76865, "text": "Let's open the command console, go to the C:\\ > MVN directory and execute the following mvn command." }, { "code": null, "e": 76998, "s": 76966, "text": "C:\\MVN>mvn archetype:generate \n" }, { "code": null, "e": 77073, "s": 76998, "text": "Maven will start processing and will ask to choose the required archetype." }, { "code": null, "e": 78207, "s": 77073, "text": "\nC:\\MVN>mvn archetype:generate\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------< org.apache.maven:standalone-pom >-------------------\n[INFO] Building Maven Stub Project (No POM) 1\n[INFO] --------------------------------[ pom ]---------------------------------\n[INFO]\n[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>>\n[INFO]\n[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<<\n[INFO]\n[INFO]\n[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---\n[INFO] Generating project in Interactive mode\n[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)\nChoose archetype:\n1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype (Blank multi project for Spring Boot + Elm)\n2: remote -> am.ik.archetype:graalvm-blank-archetype (Blank project for GraalVM)\n...\n3021: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-)\nChoose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1843:\n" }, { "code": null, "e": 78282, "s": 78207, "text": "Press Enter to choose to default option (1843: maven-archetype-quickstart)" }, { "code": null, "e": 78334, "s": 78282, "text": "Maven will ask for particular version of archetype." }, { "code": null, "e": 78514, "s": 78334, "text": "Choose org.apache.maven.archetypes:maven-archetype-quickstart version:\n1: 1.0-alpha-1\n2: 1.0-alpha-2\n3: 1.0-alpha-3\n4: 1.0-alpha-4\n5: 1.0\n6: 1.1\n7: 1.3\n8: 1.4\nChoose a number: 8:\n" }, { "code": null, "e": 78590, "s": 78514, "text": "Press Enter to choose to default option (8: maven-archetype-quickstart:1.4)" }, { "code": null, "e": 78756, "s": 78590, "text": "Maven will ask for the project detail. Enter project detail as asked. Press Enter if the default value is provided. You can override them by entering your own value." }, { "code": null, "e": 78985, "s": 78756, "text": "Define value for property 'groupId': : com.companyname.insurance\nDefine value for property 'artifactId': : health\nDefine value for property 'version': 1.0-SNAPSHOT:\nDefine value for property 'package': com.companyname.insurance:" }, { "code": null, "e": 79061, "s": 78985, "text": "Maven will ask for the project detail confirmation. Press enter or press Y." }, { "code": null, "e": 79209, "s": 79061, "text": "Confirm properties configuration:\ngroupId: com.companyname.insurance\nartifactId: health\nversion: 1.0-SNAPSHOT\npackage: com.companyname.insurance\nY:" }, { "code": null, "e": 79294, "s": 79209, "text": "Now Maven will start creating the project structure and will display the following −" }, { "code": null, "e": 80456, "s": 79294, "text": "[INFO] ----------------------------------------------------------------------------\n[INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4\n[INFO] ----------------------------------------------------------------------------\n[INFO] Parameter: groupId, Value: com.companyname.insurance\n[INFO] Parameter: artifactId, Value: health\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] Parameter: package, Value: com.companyname.insurance\n[INFO] Parameter: packageInPathFormat, Value: com/companyname/insurance\n[INFO] Parameter: package, Value: com.companyname.insurance\n[INFO] Parameter: groupId, Value: com.companyname.insurance\n[INFO] Parameter: artifactId, Value: health\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] Project created from Archetype in dir: C:\\MVN\\health\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 04:44 min\n[INFO] Finished at: 2021-12-13T18:52:59+05:30\n[INFO] ------------------------------------------------------------------------\n" }, { "code": null, "e": 80690, "s": 80456, "text": "Now go to C:\\ > MVN directory. You'll see a java application project created, named health, which was given as artifactId at the time of project creation. Maven will create a standard directory layout for the project as shown below −" }, { "code": null, "e": 80755, "s": 80690, "text": "Maven generates a POM.xml file for the project as listed below −" }, { "code": null, "e": 81551, "s": 80755, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.insurance</groupId>\n <artifactId>health</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>health</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 81635, "s": 81551, "text": "Maven generates sample java source file, App.java for the project as listed below −" }, { "code": null, "e": 81728, "s": 81635, "text": "Location: C:\\ > MVN > health > src > main > java > com > companyname > insurance > App.java." }, { "code": null, "e": 81910, "s": 81728, "text": "package com.companyname.insurance;\n\n/**\n * Hello world!\n *\n*/\npublic class App {\n public static void main( String[] args ) {\n System.out.println( \"Hello World!\" );\n }\n}" }, { "code": null, "e": 82003, "s": 81910, "text": "Maven generates sample java source test file, AppTest.java for the project as listed below −" }, { "code": null, "e": 82100, "s": 82003, "text": "Location: C:\\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java." }, { "code": null, "e": 82718, "s": 82100, "text": "package com.companyname.insurance;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Unit test for simple App.\n*/\npublic class AppTest extends TestCase {\n /**\n * Create the test case\n *\n * @param testName name of the test case\n */\n public AppTest( String testName ) {\n super( testName );\n }\n /**\n * @return the suite of tests being tested\n */\n public static Test suite() {\n return new TestSuite( AppTest.class );\n }\n /**\n * Rigourous Test :-)\n */\n public void testApp() {\n assertTrue( true );\n }\n}" }, { "code": null, "e": 82856, "s": 82718, "text": "Now you can see the power of Maven. You can create any kind of project using single command in maven and can kick-start your development." }, { "code": null, "e": 82882, "s": 82856, "text": "maven-archetype-archetype" }, { "code": null, "e": 82931, "s": 82882, "text": "An archetype, which contains a sample archetype." }, { "code": null, "e": 82959, "s": 82931, "text": "maven-archetype-j2ee-simple" }, { "code": null, "e": 83026, "s": 82959, "text": "An archetype, which contains a simplified sample J2EE application." }, { "code": null, "e": 83047, "s": 83026, "text": "maven-archetype-mojo" }, { "code": null, "e": 83108, "s": 83047, "text": "An archetype, which contains a sample a sample Maven plugin." }, { "code": null, "e": 83131, "s": 83108, "text": "maven-archetype-plugin" }, { "code": null, "e": 83183, "s": 83131, "text": "An archetype, which contains a sample Maven plugin." }, { "code": null, "e": 83211, "s": 83183, "text": "maven-archetype-plugin-site" }, { "code": null, "e": 83268, "s": 83211, "text": "An archetype, which contains a sample Maven plugin site." }, { "code": null, "e": 83292, "s": 83268, "text": "maven-archetype-portlet" }, { "code": null, "e": 83347, "s": 83292, "text": "An archetype, which contains a sample JSR-268 Portlet." }, { "code": null, "e": 83374, "s": 83347, "text": "maven-archetype-quickstart" }, { "code": null, "e": 83427, "s": 83374, "text": "An archetype, which contains a sample Maven project." }, { "code": null, "e": 83450, "s": 83427, "text": "maven-archetype-simple" }, { "code": null, "e": 83503, "s": 83450, "text": "An archetype, which contains a simple Maven project." }, { "code": null, "e": 83524, "s": 83503, "text": "maven-archetype-site" }, { "code": null, "e": 83690, "s": 83524, "text": "An archetype, which contains a sample Maven site to demonstrates some of the supported document types like APT, XDoc, and FML and demonstrates how to i18n your site." }, { "code": null, "e": 83718, "s": 83690, "text": "maven-archetype-site-simple" }, { "code": null, "e": 83768, "s": 83718, "text": "An archetype, which contains a sample Maven site." }, { "code": null, "e": 83791, "s": 83768, "text": "maven-archetype-webapp" }, { "code": null, "e": 83851, "s": 83791, "text": "An archetype, which contains a sample Maven Webapp project." }, { "code": null, "e": 84195, "s": 83851, "text": "A large software application generally consists of multiple modules and it is common scenario where multiple teams are working on different modules of same application. For example, consider a team is working on the front end of the application as app-ui project (app-ui.jar:1.0) and they are using data-service project (data-service.jar:1.0)." }, { "code": null, "e": 84382, "s": 84195, "text": "Now it may happen that team working on data-service is undergoing bug fixing or enhancements at rapid pace and they are releasing the library to remote repository almost every other day." }, { "code": null, "e": 84483, "s": 84382, "text": "Now if data-service team uploads a new version every other day, then following problems will arise −" }, { "code": null, "e": 84577, "s": 84483, "text": "data-service team should tell app-ui team every time when they have released an updated code." }, { "code": null, "e": 84671, "s": 84577, "text": "data-service team should tell app-ui team every time when they have released an updated code." }, { "code": null, "e": 84754, "s": 84671, "text": "app-ui team required to update their pom.xml regularly to get the updated version." }, { "code": null, "e": 84837, "s": 84754, "text": "app-ui team required to update their pom.xml regularly to get the updated version." }, { "code": null, "e": 84905, "s": 84837, "text": "To handle such kind of situation, SNAPSHOT concept comes into play." }, { "code": null, "e": 85083, "s": 84905, "text": "SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build." }, { "code": null, "e": 85238, "s": 85083, "text": "Now data-service team will release SNAPSHOT of its updated code every time to repository, say data-service: 1.0-SNAPSHOT, replacing an older SNAPSHOT jar." }, { "code": null, "e": 85469, "s": 85238, "text": "In case of Version, if Maven once downloaded the mentioned version, say data-service:1.0, it will never try to download a newer 1.0 available in repository. To download the updated code, data-service version is be upgraded to 1.1." }, { "code": null, "e": 85613, "s": 85469, "text": "In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT (data-service:1.0-SNAPSHOT) every time app-ui team build their project." }, { "code": null, "e": 85667, "s": 85613, "text": "app-ui project is using 1.0-SNAPSHOT of data-service." }, { "code": null, "e": 86456, "s": 85667, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>app-ui</groupId>\n <artifactId>app-ui</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <name>health</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>data-service</groupId>\n <artifactId>data-service</artifactId>\n <version>1.0-SNAPSHOT</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 86527, "s": 86456, "text": "data-service project is releasing 1.0-SNAPSHOT for every minor change." }, { "code": null, "e": 87106, "s": 86527, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>data-service</groupId>\n <artifactId>data-service</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>health</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n</project>" }, { "code": null, "e": 87293, "s": 87106, "text": "Although, in case of SNAPSHOT, Maven automatically fetches the latest SNAPSHOT on daily basis, you can force maven to download latest snapshot build using -U switch to any maven command." }, { "code": null, "e": 87315, "s": 87293, "text": "mvn clean package -U\n" }, { "code": null, "e": 87425, "s": 87315, "text": "Let's open the command console, go to the C:\\ > MVN > app-ui directory and execute the following mvn command." }, { "code": null, "e": 87461, "s": 87425, "text": "C:\\MVN\\app-ui>mvn clean package -U\n" }, { "code": null, "e": 87554, "s": 87461, "text": "Maven will start building the project after downloading the latest SNAPSHOT of data-service." }, { "code": null, "e": 89538, "s": 87554, "text": "[INFO] Scanning for projects...\n[INFO]--------------------------------------------\n[INFO] Building consumerBanking\n[INFO] task-segment: [clean, package]\n[INFO]--------------------------------------------\n[INFO] Downloading data-service:1.0-SNAPSHOT\n[INFO] 290K downloaded.\n[INFO] [clean:clean {execution: default-clean}]\n[INFO] Deleting directory C:\\MVN\\app-ui\\target\n[INFO] [resources:resources {execution: default-resources}]\n\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,\ni.e. build is platform dependent!\n\n[INFO] skip non existing resourceDirectory C:\\MVN\\app-ui\\src\\main\\resources\n[INFO] [compiler:compile {execution:default-compile}]\n[INFO] Compiling 1 source file to C:\\MVN\\app-ui\\target\\classes\n[INFO] [resources:testResources {execution: default-testResources}]\n\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,\ni.e. build is platform dependent!\n\n[INFO] skip non existing resourceDirectory C:\\MVN\\app-ui\\src\\test\\resources\n[INFO] [compiler:testCompile {execution: default-testCompile}]\n[INFO] Compiling 1 source file to C:\\MVN\\app-ui\\target\\test-classes\n[INFO] [surefire:test {execution: default-test}]\n[INFO] Surefire report directory: C:\\MVN\\app-ui\\target\\\nsurefire-reports\n\n--------------------------------------------------\n T E S T S\n--------------------------------------------------\n\nRunning com.companyname.bank.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\app-ui\\target\\\napp-ui-1.0-SNAPSHOT.jar\n[INFO]--------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO]--------------------------------------------------------\n[INFO] Total time: 2 seconds\n[INFO] Finished at: 2015-09-27T12:30:02+05:30\n[INFO] Final Memory: 16M/89M\n[INFO]------------------------------------------------------------------------\n" }, { "code": null, "e": 89740, "s": 89538, "text": "Build Automation defines the scenario where dependent project(s) build process gets started once the project build is successfully completed, in order to ensure that dependent project(s) is/are stable." }, { "code": null, "e": 89748, "s": 89740, "text": "Example" }, { "code": null, "e": 89874, "s": 89748, "text": "Consider a team is developing a project bus-core-api on which two other projects app-web-ui and app-desktop-ui are dependent." }, { "code": null, "e": 89940, "s": 89874, "text": "app-web-ui project is using 1.0-SNAPSHOT of bus-core-api project." }, { "code": null, "e": 90548, "s": 89940, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>app-web-ui</groupId>\n <artifactId>app-web-ui</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <dependencies>\n <dependency>\n <groupId>bus-core-api</groupId>\n <artifactId>bus-core-api</artifactId>\n <version>1.0-SNAPSHOT</version>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 90618, "s": 90548, "text": "app-desktop-ui project is using 1.0-SNAPSHOT of bus-core-api project." }, { "code": null, "e": 91703, "s": 90618, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>app_desktop_ui</groupId>\n <artifactId>app_desktop_ui</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <name>app_desktop_ui</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>bus_core_api</groupId>\n <artifactId>bus_core_api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <scope>system</scope>\n <systemPath>C:\\MVN\\bus_core_api\\target\\bus_core_api-1.0-SNAPSHOT.jar</systemPath>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 91726, "s": 91703, "text": "bus-core-api project −" }, { "code": null, "e": 92141, "s": 91726, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>bus_core_api</groupId>\n <artifactId>bus_core_api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging> \n</project>" }, { "code": null, "e": 92282, "s": 92141, "text": "Now, teams of app-web-ui and app-desktop-ui projects require that their build process should kick off whenever bus-core-api project changes." }, { "code": null, "e": 92423, "s": 92282, "text": "Using snapshot, ensures that the latest bus-core-api project should be used but to meet the above requirement we need to do something extra." }, { "code": null, "e": 92468, "s": 92423, "text": "We can proceed with the following two ways −" }, { "code": null, "e": 92560, "s": 92468, "text": "Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds." }, { "code": null, "e": 92652, "s": 92560, "text": "Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds." }, { "code": null, "e": 92747, "s": 92652, "text": "Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically." }, { "code": null, "e": 92842, "s": 92747, "text": "Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically." }, { "code": null, "e": 92879, "s": 92842, "text": "Update bus-core-api project pom.xml." }, { "code": null, "e": 93932, "s": 92879, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>bus-core-api</groupId>\n <artifactId>bus-core-api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <build>\n <plugins>\n <plugin>\n <artifactId>maven-invoker-plugin</artifactId>\n <version>1.6</version>\n <configuration>\n <debug>true</debug>\n <pomIncludes>\n <pomInclude>app-web-ui/pom.xml</pomInclude>\n <pomInclude>app-desktop-ui/pom.xml</pomInclude>\n </pomIncludes>\n </configuration>\n <executions>\n <execution>\n <id>build</id>\n <goals>\n <goal>run</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n <build>\n</project>" }, { "code": null, "e": 94048, "s": 93932, "text": "Let's open the command console, go to the C:\\ > MVN > bus-core-api directory and execute the following mvn command." }, { "code": null, "e": 94071, "s": 94048, "text": ">mvn clean package -U\n" }, { "code": null, "e": 94123, "s": 94071, "text": "Maven will start building the project bus-core-api." }, { "code": null, "e": 94666, "s": 94123, "text": "[INFO] Scanning for projects...\n[INFO] ------------------------------------------------------------------\n[INFO] Building bus-core-api\n[INFO] task-segment: [clean, package]\n[INFO] ------------------------------------------------------------------\n...\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\bus-core-ui\\target\\\nbus-core-ui-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] ------------------------------------------------------------------\n" }, { "code": null, "e": 94755, "s": 94666, "text": "Once bus-core-api build is successful, Maven will start building the app-web-ui project." }, { "code": null, "e": 95255, "s": 94755, "text": "[INFO] ------------------------------------------------------------------\n[INFO] Building app-web-ui\n[INFO] task-segment: [package]\n[INFO] ------------------------------------------------------------------\n...\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\app-web-ui\\target\\\napp-web-ui-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] ------------------------------------------------------------------\n" }, { "code": null, "e": 95346, "s": 95255, "text": "Once app-web-ui build is successful, Maven will start building the app-desktop-ui project." }, { "code": null, "e": 95860, "s": 95346, "text": "[INFO] ------------------------------------------------------------------\n[INFO] Building app-desktop-ui\n[INFO] task-segment: [package]\n[INFO] ------------------------------------------------------------------\n...\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\app-desktop-ui\\target\\\napp-desktop-ui-1.0-SNAPSHOT.jar\n[INFO] -------------------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] -------------------------------------------------------------------\n" }, { "code": null, "e": 96363, "s": 95860, "text": "Using a CI Server is more preferable to developers. It is not required to update the bus-core-api project, every time a new project (for example, app-mobile-ui) is added, as dependent project on bus-core-api project. Hudsion is a continuous integration tool written in java, which in a servlet container, such as, Apache tomcat and glassfish application server. Hudson automatically manages build automation using Maven dependency management. The following snapshot will define the role of Hudson tool." }, { "code": null, "e": 96632, "s": 96363, "text": "Hudson considers each project build as job. Once a project code is checked-in to SVN (or any Source Management Tool mapped to Hudson), Hudson starts its build job and once this job gets completed, it start other dependent jobs (other dependent projects) automatically." }, { "code": null, "e": 96864, "s": 96632, "text": "In the above example, when bus-core-ui source code is updated in SVN, Hudson starts its build. Once build is successful, Hudson looks for dependent projects automatically, and starts building app-web-ui and app-desktop-ui projects." }, { "code": null, "e": 97128, "s": 96864, "text": "One of the core features of Maven is Dependency Management. Managing dependencies is a difficult task once we've to deal with multi-module projects (consisting of hundreds of modules/sub-projects). Maven provides a high degree of control to manage such scenarios." }, { "code": null, "e": 97304, "s": 97128, "text": "It is pretty often a case, when a library, say A, depends upon other library, say B. In case another project C wants to use A, then that project requires to use library B too." }, { "code": null, "e": 97490, "s": 97304, "text": "Maven helps to avoid such requirements to discover all the libraries required. Maven does so by reading project files (pom.xml) of dependencies, figure out their dependencies and so on." }, { "code": null, "e": 97590, "s": 97490, "text": "We only need to define direct dependency in each project pom. Maven handles the rest automatically." }, { "code": null, "e": 97814, "s": 97590, "text": "With transitive dependencies, the graph of included libraries can quickly grow to a large extent. Cases can arise when there are duplicate libraries. Maven provides few features to control extent of transitive dependencies." }, { "code": null, "e": 97835, "s": 97814, "text": "Dependency mediation" }, { "code": null, "e": 98061, "s": 97835, "text": "Determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used." }, { "code": null, "e": 98083, "s": 98061, "text": "Dependency management" }, { "code": null, "e": 98365, "s": 98083, "text": "Directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependency Management section and directly control which version of B is to be used when it is ever referenced." }, { "code": null, "e": 98382, "s": 98365, "text": "Dependency scope" }, { "code": null, "e": 98443, "s": 98382, "text": "Includes dependencies as per the current stage of the build." }, { "code": null, "e": 98465, "s": 98443, "text": "Excluded dependencies" }, { "code": null, "e": 98616, "s": 98465, "text": "Any transitive dependency can be excluded using \"exclusion\" element. As example, A depends upon B and B depends upon C, then A can mark C as excluded." }, { "code": null, "e": 98638, "s": 98616, "text": "Optional dependencies" }, { "code": null, "e": 98818, "s": 98638, "text": "Any transitive dependency can be marked as optional using \"optional\" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C." }, { "code": null, "e": 98921, "s": 98818, "text": "Transitive Dependencies Discovery can be restricted using various Dependency Scope as mentioned below." }, { "code": null, "e": 98929, "s": 98921, "text": "compile" }, { "code": null, "e": 99025, "s": 98929, "text": "This scope indicates that dependency is available in classpath of project. It is default scope." }, { "code": null, "e": 99034, "s": 99025, "text": "provided" }, { "code": null, "e": 99132, "s": 99034, "text": "This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime." }, { "code": null, "e": 99140, "s": 99132, "text": "runtime" }, { "code": null, "e": 99244, "s": 99140, "text": "This scope indicates that dependency is not required for compilation, but is required during execution." }, { "code": null, "e": 99249, "s": 99244, "text": "test" }, { "code": null, "e": 99355, "s": 99249, "text": "This scope indicates that the dependency is only available for the test compilation and execution phases." }, { "code": null, "e": 99362, "s": 99355, "text": "system" }, { "code": null, "e": 99425, "s": 99362, "text": "This scope indicates that you have to provide the system path." }, { "code": null, "e": 99432, "s": 99425, "text": "import" }, { "code": null, "e": 99619, "s": 99432, "text": "This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section." }, { "code": null, "e": 99868, "s": 99619, "text": "Usually, we have a set of project under a common project. In such case, we can create a common pom having all the common dependencies and then make this pom, the parent of sub-project's poms. Following example will help you understand this concept." }, { "code": null, "e": 99925, "s": 99868, "text": "Following are the detail of the above dependency graph −" }, { "code": null, "e": 99980, "s": 99925, "text": "App-UI-WAR depends upon App-Core-lib and App-Data-lib." }, { "code": null, "e": 100029, "s": 99980, "text": "Root is parent of App-Core-lib and App-Data-lib." }, { "code": null, "e": 100102, "s": 100029, "text": "Root defines Lib1, lib2, Lib3 as dependencies in its dependency section." }, { "code": null, "e": 100113, "s": 100102, "text": "App-UI-WAR" }, { "code": null, "e": 100947, "s": 100113, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-UI-WAR</artifactId>\n <version>1.0</version>\n <packaging>war</packaging>\n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Core-lib</artifactId>\n <version>1.0</version>\n </dependency>\n </dependencies> \n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Data-lib</artifactId>\n <version>1.0</version>\n </dependency>\n </dependencies> \n</project>" }, { "code": null, "e": 100960, "s": 100947, "text": "App-Core-lib" }, { "code": null, "e": 101516, "s": 100960, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <parent>\n <artifactId>Root</artifactId>\n <groupId>com.companyname.groupname</groupId>\n <version>1.0</version>\n </parent>\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Core-lib</artifactId>\n <version>1.0</version> \n <packaging>jar</packaging>\n</project>" }, { "code": null, "e": 101529, "s": 101516, "text": "App-Data-lib" }, { "code": null, "e": 102087, "s": 101529, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <parent>\n <artifactId>Root</artifactId>\n <groupId>com.companyname.groupname</groupId>\n <version>1.0</version>\n </parent>\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Data-lib</artifactId>\n <version>1.0</version> \n <packaging>jar</packaging>\n</project>" }, { "code": null, "e": 102092, "s": 102087, "text": "Root" }, { "code": null, "e": 103110, "s": 102092, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>Root</artifactId>\n <version>1.0</version>\n <packaging>pom</packaging>\n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname1</groupId>\n <artifactId>Lib1</artifactId>\n <version>1.0</version>\n </dependency>\n </dependencies> \n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname2</groupId>\n <artifactId>Lib2</artifactId>\n <version>2.1</version>\n </dependency>\n </dependencies> \n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname3</groupId>\n <artifactId>Lib3</artifactId>\n <version>1.1</version>\n </dependency>\n </dependencies> \n</project>" }, { "code": null, "e": 103251, "s": 103110, "text": "Now when we build App-UI-WAR project, Maven will discover all the dependencies by traversing the dependency graph and build the application." }, { "code": null, "e": 103313, "s": 103251, "text": "From above example, we can learn the following key concepts −" }, { "code": null, "e": 103518, "s": 103313, "text": "Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM)." }, { "code": null, "e": 103723, "s": 103518, "text": "Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM)." }, { "code": null, "e": 103866, "s": 103723, "text": "There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail." }, { "code": null, "e": 104009, "s": 103866, "text": "There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail." }, { "code": null, "e": 104097, "s": 104009, "text": "In project development, normally a deployment process consists of the following steps −" }, { "code": null, "e": 104220, "s": 104097, "text": "Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it." }, { "code": null, "e": 104343, "s": 104220, "text": "Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it." }, { "code": null, "e": 104387, "s": 104343, "text": "Download the complete source code from SVN." }, { "code": null, "e": 104431, "s": 104387, "text": "Download the complete source code from SVN." }, { "code": null, "e": 104454, "s": 104431, "text": "Build the application." }, { "code": null, "e": 104477, "s": 104454, "text": "Build the application." }, { "code": null, "e": 104553, "s": 104477, "text": "Store the build output either WAR or EAR file to a common network location." }, { "code": null, "e": 104629, "s": 104553, "text": "Store the build output either WAR or EAR file to a common network location." }, { "code": null, "e": 104699, "s": 104629, "text": "Get the file from network and deploy the file to the production site." }, { "code": null, "e": 104769, "s": 104699, "text": "Get the file from network and deploy the file to the production site." }, { "code": null, "e": 104852, "s": 104769, "text": "Updated the documentation with date and updated version number of the application." }, { "code": null, "e": 104935, "s": 104852, "text": "Updated the documentation with date and updated version number of the application." }, { "code": null, "e": 105328, "s": 104935, "text": "There are normally multiple people involved in the above mentioned deployment process. One team may handle check-in of code, other may handle build and so on. It is very likely that any step may be missed out due to manual efforts involved and owing to multi-team environment. For example, older build may not be replaced on network machine and deployment team deployed the older build again." }, { "code": null, "e": 105389, "s": 105328, "text": "Automate the deployment process by combining the following −" }, { "code": null, "e": 105427, "s": 105389, "text": "Maven, to build and release projects." }, { "code": null, "e": 105486, "s": 105427, "text": "SubVersion, source code repository, to manage source code." }, { "code": null, "e": 105554, "s": 105486, "text": "Remote Repository Manager (Jfrog/Nexus) to manage project binaries." }, { "code": null, "e": 105633, "s": 105554, "text": "We will be using Maven Release plug-in to create an automated release process." }, { "code": null, "e": 105676, "s": 105633, "text": "For Example: bus-core-api project POM.xml." }, { "code": null, "e": 107143, "s": 105676, "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 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>bus-core-api</groupId>\n <artifactId>bus-core-api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging> \n <scm>\n <url>http://www.svn.com</url>\n <connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/\n Framework</connection>\n <developerConnection>scm:svn:${username}/${password}@localhost:8080:\n common_core_api:1101:code</developerConnection>\n </scm>\n <distributionManagement>\n <repository>\n <id>Core-API-Java-Release</id>\n <name>Release repository</name>\n <url>http://localhost:8081/nexus/content/repositories/\n Core-Api-Release</url>\n </repository>\n </distributionManagement>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-release-plugin</artifactId>\n <version>2.0-beta-9</version>\n <configuration>\n <useReleaseProfile>false</useReleaseProfile>\n <goals>deploy</goals>\n <scmCommentPrefix>[bus-core-api-release-checkin]-<\n /scmCommentPrefix>\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>" }, { "code": null, "e": 107207, "s": 107143, "text": "In Pom.xml, following are the important elements we have used −" }, { "code": null, "e": 107211, "s": 107207, "text": "SCM" }, { "code": null, "e": 107288, "s": 107211, "text": "Configures the SVN location from where Maven will check out the source code." }, { "code": null, "e": 107301, "s": 107288, "text": "Repositories" }, { "code": null, "e": 107403, "s": 107301, "text": "Location where built WAR/EAR/JAR or any other artifact will be stored after code build is successful." }, { "code": null, "e": 107410, "s": 107403, "text": "Plugin" }, { "code": null, "e": 107481, "s": 107410, "text": "maven-release-plugin is configured to automate the deployment process." }, { "code": null, "e": 107551, "s": 107481, "text": "The Maven does the following useful tasks using maven-release-plugin." }, { "code": null, "e": 107570, "s": 107551, "text": "mvn release:clean\n" }, { "code": null, "e": 107647, "s": 107570, "text": "It cleans the workspace in case the last release process was not successful." }, { "code": null, "e": 107669, "s": 107647, "text": "mvn release:rollback\n" }, { "code": null, "e": 107784, "s": 107669, "text": "Rollback the changes done to workspace code and configuration in case the last release process was not successful." }, { "code": null, "e": 107805, "s": 107784, "text": "mvn release:prepare\n" }, { "code": null, "e": 107855, "s": 107805, "text": "Performs multiple number of operations, such as −" }, { "code": null, "e": 107918, "s": 107855, "text": "Checks whether there are any uncommitted local changes or not." }, { "code": null, "e": 107981, "s": 107918, "text": "Checks whether there are any uncommitted local changes or not." }, { "code": null, "e": 108030, "s": 107981, "text": "Ensures that there are no SNAPSHOT dependencies." }, { "code": null, "e": 108079, "s": 108030, "text": "Ensures that there are no SNAPSHOT dependencies." }, { "code": null, "e": 108173, "s": 108079, "text": "Changes the version of the application and removes SNAPSHOT from the version to make release." }, { "code": null, "e": 108267, "s": 108173, "text": "Changes the version of the application and removes SNAPSHOT from the version to make release." }, { "code": null, "e": 108292, "s": 108267, "text": "Update pom files to SVN." }, { "code": null, "e": 108317, "s": 108292, "text": "Update pom files to SVN." }, { "code": null, "e": 108333, "s": 108317, "text": "Run test cases." }, { "code": null, "e": 108349, "s": 108333, "text": "Run test cases." }, { "code": null, "e": 108380, "s": 108349, "text": "Commit the modified POM files." }, { "code": null, "e": 108411, "s": 108380, "text": "Commit the modified POM files." }, { "code": null, "e": 108438, "s": 108411, "text": "Tag the code in subversion" }, { "code": null, "e": 108465, "s": 108438, "text": "Tag the code in subversion" }, { "code": null, "e": 108534, "s": 108465, "text": "Increment the version number and append SNAPSHOT for future release." }, { "code": null, "e": 108603, "s": 108534, "text": "Increment the version number and append SNAPSHOT for future release." }, { "code": null, "e": 108641, "s": 108603, "text": "Commit the modified POM files to SVN." }, { "code": null, "e": 108679, "s": 108641, "text": "Commit the modified POM files to SVN." }, { "code": null, "e": 108700, "s": 108679, "text": "mvn release:perform\n" }, { "code": null, "e": 108835, "s": 108700, "text": "Checks out the code using the previously defined tag and run the Maven deploy goal, to deploy the war or built artifact to repository." }, { "code": null, "e": 108950, "s": 108835, "text": "Let's open the command console, go to the C:\\ > MVN >bus-core-api directory and execute the following mvn command." }, { "code": null, "e": 108972, "s": 108950, "text": ">mvn release:prepare\n" }, { "code": null, "e": 109067, "s": 108972, "text": "Maven will start building the project. Once build is successful run the following mvn command." }, { "code": null, "e": 109089, "s": 109067, "text": ">mvn release:perform\n" }, { "code": null, "e": 109171, "s": 109089, "text": "Once build is successful you can verify the uploaded JAR file in your repository." }, { "code": null, "e": 109317, "s": 109171, "text": "This chapter teaches you how to manage a web based project using Maven. Here you will learn how to create/build/deploy and run a web application." }, { "code": null, "e": 109503, "s": 109317, "text": "To create a simple java web application, we will use maven-archetype-webapp plugin. So, let's open the command console, go to the C:\\MVN directory and execute the following mvn command." }, { "code": null, "e": 109670, "s": 109503, "text": "C:\\MVN>mvn archetype:generate \n-DgroupId = com.companyname.automobile \n-DartifactId = trucks\n-DarchetypeArtifactId = maven-archetype-webapp \n-DinteractiveMode = false" }, { "code": null, "e": 109785, "s": 109670, "text": "Maven will start processing and will create the complete web based java application project structure as follows −" }, { "code": null, "e": 111200, "s": 109785, "text": "C:\\MVN>mvn archetype:generate -DgroupId=com.companyname.automobile -DartifactId=trucks -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------< org.apache.maven:standalone-pom >-------------------\n[INFO] Building Maven Stub Project (No POM) 1\n[INFO] --------------------------------[ pom ]---------------------------------\n...\n[INFO] ----------------------------------------------------------------------------\n[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0\n[INFO] ----------------------------------------------------------------------------\n[INFO] Parameter: basedir, Value: C:\\MVN\n[INFO] Parameter: package, Value: com.companyname.automobile\n[INFO] Parameter: groupId, Value: com.companyname.automobile\n[INFO] Parameter: artifactId, Value: trucks\n[INFO] Parameter: packageName, Value: com.companyname.automobile\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] project created from Old (1.x) Archetype in dir: C:\\MVN\\trucks\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 10.381 s\n[INFO] Finished at: 2021-12-13T19:00:13+05:30\n[INFO] ------------------------------------------------------------------------\nC:\\MVN>\n" }, { "code": null, "e": 111432, "s": 111200, "text": "Now go to C:/MVN directory. You'll see a java application project created, named trucks (as specified in artifactId) as specified in the following snapshot. The following directory structure is generally used for web applications −" }, { "code": null, "e": 111544, "s": 111432, "text": "Maven uses a standard directory layout. Using the above example, we can understand the following key concepts −" }, { "code": null, "e": 111551, "s": 111544, "text": "trucks" }, { "code": null, "e": 111584, "s": 111551, "text": "contains src folder and pom.xml." }, { "code": null, "e": 111600, "s": 111584, "text": "src/main/webapp" }, { "code": null, "e": 111639, "s": 111600, "text": "contains index.jsp and WEB-INF folder." }, { "code": null, "e": 111663, "s": 111639, "text": "src/main/webapp/WEB-INF" }, { "code": null, "e": 111680, "s": 111663, "text": "contains web.xml" }, { "code": null, "e": 111699, "s": 111680, "text": "src/main/resources" }, { "code": null, "e": 111736, "s": 111699, "text": "it contains images/properties files." }, { "code": null, "e": 112498, "s": 111736, "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 http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.automobile</groupId>\n <artifactId>trucks</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>trucks Maven Webapp</name>\n <url>http://maven.apache.org</url>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n <build>\n <finalName>trucks</finalName>\n </build>\n</project>" }, { "code": null, "e": 112578, "s": 112498, "text": "If you observe, you will find that Maven also created a sample JSP Source file." }, { "code": null, "e": 112676, "s": 112578, "text": "Open C:\\ > MVN > trucks > src > main > webapp > folder to see index.jsp with the following code −" }, { "code": null, "e": 112740, "s": 112676, "text": "<html>\n <body>\n <h2>Hello World!</h2>\n </body>\n</html>" }, { "code": null, "e": 112845, "s": 112740, "text": "Let's open the command console, go to the C:\\MVN\\trucks directory and execute the following mvn command." }, { "code": null, "e": 112877, "s": 112845, "text": "C:\\MVN\\trucks>mvn clean package" }, { "code": null, "e": 112916, "s": 112877, "text": "Maven will start building the project." }, { "code": null, "e": 115459, "s": 112916, "text": "\nC:\\MVN\\trucks>mvn clean package\n[INFO] Scanning for projects...\n[INFO]\n[INFO] -----------------< com.companyname.automobile:trucks >------------------\n[INFO] Building trucks Maven Webapp 1.0-SNAPSHOT\n[INFO] --------------------------------[ war ]---------------------------------\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ trucks ---\n[INFO] Deleting C:\\MVN\\trucks\\target\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ trucks ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] Copying 0 resource\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ trucks ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ trucks ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\trucks\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ trucks ---\n[INFO] No sources to compile\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ trucks ---\n[INFO] No tests to run.\n[INFO]\n[INFO] --- maven-war-plugin:2.2:war (default-war) @ trucks ---\nWARNING: An illegal reflective access operation has occurred\nWARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/intel/.m2/repository/com/thoughtworks/xstream/xstream/1.3.1/xstream-1.3.1.jar) to field java.util.Properties.defaults\nWARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields\nWARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations\nWARNING: All illegal access operations will be denied in a future release\n[INFO] Packaging webapp\n[INFO] Assembling webapp [trucks] in [C:\\MVN\\trucks\\target\\trucks]\n[INFO] Processing war project\n[INFO] Copying webapp resources [C:\\MVN\\trucks\\src\\main\\webapp]\n[INFO] Webapp assembled in [50 msecs]\n[INFO] Building war: C:\\MVN\\trucks\\target\\trucks.war\n[INFO] WEB-INF\\web.xml already added, skipping\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.494 s\n[INFO] Finished at: 2021-12-13T19:02:15+05:30\n[INFO] ------------------------------------------------------------------------\nC:\\MVN\\trucks>\n" }, { "code": null, "e": 115593, "s": 115459, "text": "Now copy the trucks.war created in C:\\ > MVN > trucks > target > folder to your webserver webapp directory and restart the webserver." }, { "code": null, "e": 115681, "s": 115593, "text": "Run the web-application using URL: http://<server-name>:<port-number>/trucks/index.jsp." }, { "code": null, "e": 115700, "s": 115681, "text": "Verify the output." }, { "code": null, "e": 115803, "s": 115700, "text": "Eclipse provides an excellent plugin m2eclipse which seamlessly integrates Maven and Eclipse together." }, { "code": null, "e": 115852, "s": 115803, "text": "Some of features of m2eclipse are listed below −" }, { "code": null, "e": 115890, "s": 115852, "text": "You can run Maven goals from Eclipse." }, { "code": null, "e": 115928, "s": 115890, "text": "You can run Maven goals from Eclipse." }, { "code": null, "e": 116013, "s": 115928, "text": "You can view the output of Maven commands inside the Eclipse, using its own console." }, { "code": null, "e": 116098, "s": 116013, "text": "You can view the output of Maven commands inside the Eclipse, using its own console." }, { "code": null, "e": 116142, "s": 116098, "text": "You can update maven dependencies with IDE." }, { "code": null, "e": 116186, "s": 116142, "text": "You can update maven dependencies with IDE." }, { "code": null, "e": 116235, "s": 116186, "text": "You can Launch Maven builds from within Eclipse." }, { "code": null, "e": 116284, "s": 116235, "text": "You can Launch Maven builds from within Eclipse." }, { "code": null, "e": 116367, "s": 116284, "text": "It does the dependency management for Eclipse build path based on Maven's pom.xml." }, { "code": null, "e": 116450, "s": 116367, "text": "It does the dependency management for Eclipse build path based on Maven's pom.xml." }, { "code": null, "e": 116605, "s": 116450, "text": "It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository (requires dependency project be in same workspace)." }, { "code": null, "e": 116760, "s": 116605, "text": "It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository (requires dependency project be in same workspace)." }, { "code": null, "e": 116857, "s": 116760, "text": "It automatic downloads the required dependencies and sources from the remote Maven repositories." }, { "code": null, "e": 116954, "s": 116857, "text": "It automatic downloads the required dependencies and sources from the remote Maven repositories." }, { "code": null, "e": 117064, "s": 116954, "text": "It provides wizards for creating new Maven projects, pom.xml and to enable Maven support on existing projects" }, { "code": null, "e": 117174, "s": 117064, "text": "It provides wizards for creating new Maven projects, pom.xml and to enable Maven support on existing projects" }, { "code": null, "e": 117246, "s": 117174, "text": "It provides quick search for dependencies in remote Maven repositories." }, { "code": null, "e": 117318, "s": 117246, "text": "It provides quick search for dependencies in remote Maven repositories." }, { "code": null, "e": 117372, "s": 117318, "text": "Use one of the following links to install m2eclipse −" }, { "code": null, "e": 117419, "s": 117372, "text": "Installing m2eclipse in Eclipse 3.5 (Gallileo)" }, { "code": null, "e": 117464, "s": 117419, "text": "Installing m2eclipse in Eclipse 3.6 (Helios)" }, { "code": null, "e": 117551, "s": 117464, "text": "Following example will help you to leverage benefits of integrating Eclipse and maven." }, { "code": null, "e": 117565, "s": 117551, "text": "Open Eclipse." }, { "code": null, "e": 117579, "s": 117565, "text": "Open Eclipse." }, { "code": null, "e": 117610, "s": 117579, "text": "Select File > Import > option." }, { "code": null, "e": 117641, "s": 117610, "text": "Select File > Import > option." }, { "code": null, "e": 117693, "s": 117641, "text": "Select Maven Projects Option. Click on Next Button." }, { "code": null, "e": 117745, "s": 117693, "text": "Select Maven Projects Option. Click on Next Button." }, { "code": null, "e": 117966, "s": 117745, "text": "Select Project location, where a project was created using Maven. We've created a Java Project consumer Banking in the previous chapters. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven." }, { "code": null, "e": 118187, "s": 117966, "text": "Select Project location, where a project was created using Maven. We've created a Java Project consumer Banking in the previous chapters. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven." }, { "code": null, "e": 118208, "s": 118187, "text": "Click Finish Button." }, { "code": null, "e": 118229, "s": 118208, "text": "Click Finish Button." }, { "code": null, "e": 118276, "s": 118229, "text": "Now, you can see the maven project in eclipse." }, { "code": null, "e": 118407, "s": 118276, "text": "Now, have a look at consumer Banking project properties. You can see that Eclipse has added Maven dependencies to java build path." }, { "code": null, "e": 118480, "s": 118407, "text": "Now, it is time to build this project using maven capability of eclipse." }, { "code": null, "e": 118541, "s": 118480, "text": "Right Click on consumerBanking project to open context menu." }, { "code": null, "e": 118563, "s": 118541, "text": "Select Run as option." }, { "code": null, "e": 118590, "s": 118563, "text": "Then maven package option." }, { "code": null, "e": 118684, "s": 118590, "text": "Maven will start building the project. You can see the output in Eclipse Console as follows −" }, { "code": null, "e": 121282, "s": 118684, "text": "[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.bank:consumerBanking >----------------\n[INFO] Building consumerBanking 1.0-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking ---\n[INFO] Deleting C:\\MVN\\consumerBanking\\target\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 1 source file to C:\\MVN\\consumerBanking\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 1 source file to C:\\MVN\\consumerBanking\\target\\test-classes\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking ---\n[INFO] Surefire report directory: C:\\MVN\\consumerBanking\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.companyname.bank.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO]\n[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking ---\n[INFO] Building jar: C:\\MVN\\consumerBanking\\target\\consumerBanking-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 4.663 s\n[INFO] Finished at: 2021-12-13T17:34:27+05:30\n[INFO] ------------------------------------------------------------------------\n" }, { "code": null, "e": 121364, "s": 121282, "text": "Now, right click on App.java. Select Run As option. Then select Java Application." }, { "code": null, "e": 121401, "s": 121364, "text": "You will see the result as follows −" }, { "code": null, "e": 121415, "s": 121401, "text": "Hello World!\n" }, { "code": null, "e": 121587, "s": 121415, "text": "NetBeans 6.7 and newer has in-built support for Maven. In case of previous version, Maven plugin is available in plugin Manager. We are using NetBeans 6.9 in this example." }, { "code": null, "e": 121635, "s": 121587, "text": "Some of features of NetBeans are listed below −" }, { "code": null, "e": 121674, "s": 121635, "text": "You can run Maven goals from NetBeans." }, { "code": null, "e": 121713, "s": 121674, "text": "You can run Maven goals from NetBeans." }, { "code": null, "e": 121798, "s": 121713, "text": "You can view the output of Maven commands inside the NetBeans using its own console." }, { "code": null, "e": 121883, "s": 121798, "text": "You can view the output of Maven commands inside the NetBeans using its own console." }, { "code": null, "e": 121927, "s": 121883, "text": "You can update maven dependencies with IDE." }, { "code": null, "e": 121971, "s": 121927, "text": "You can update maven dependencies with IDE." }, { "code": null, "e": 122021, "s": 121971, "text": "You can Launch Maven builds from within NetBeans." }, { "code": null, "e": 122071, "s": 122021, "text": "You can Launch Maven builds from within NetBeans." }, { "code": null, "e": 122151, "s": 122071, "text": "NetBeans does the dependency management automatically based on Maven's pom.xml." }, { "code": null, "e": 122231, "s": 122151, "text": "NetBeans does the dependency management automatically based on Maven's pom.xml." }, { "code": null, "e": 122384, "s": 122231, "text": "NetBeans resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace)." }, { "code": null, "e": 122537, "s": 122384, "text": "NetBeans resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace)." }, { "code": null, "e": 122636, "s": 122537, "text": "NetBeans automatic downloads required dependencies and sources from the remote Maven repositories." }, { "code": null, "e": 122735, "s": 122636, "text": "NetBeans automatic downloads required dependencies and sources from the remote Maven repositories." }, { "code": null, "e": 122803, "s": 122735, "text": "NetBeans provides wizards for creating new Maven projects, pom.xml." }, { "code": null, "e": 122871, "s": 122803, "text": "NetBeans provides wizards for creating new Maven projects, pom.xml." }, { "code": null, "e": 123007, "s": 122871, "text": "NetBeans provides a Maven Repository browser that enables you to view your local repository and registered external Maven repositories." }, { "code": null, "e": 123143, "s": 123007, "text": "NetBeans provides a Maven Repository browser that enables you to view your local repository and registered external Maven repositories." }, { "code": null, "e": 123231, "s": 123143, "text": "Following example will help you to leverage benefits of integrating NetBeans and Maven." }, { "code": null, "e": 123246, "s": 123231, "text": "Open NetBeans." }, { "code": null, "e": 123261, "s": 123246, "text": "Open NetBeans." }, { "code": null, "e": 123301, "s": 123261, "text": "Select File Menu > Open Project option." }, { "code": null, "e": 123341, "s": 123301, "text": "Select File Menu > Open Project option." }, { "code": null, "e": 123536, "s": 123341, "text": "Select Project location, where a project was created using Maven. We've created a Java Project consumerBanking. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven." }, { "code": null, "e": 123731, "s": 123536, "text": "Select Project location, where a project was created using Maven. We've created a Java Project consumerBanking. Go to ‘Creating Java Project’ chapter, to see how to create a project using Maven." }, { "code": null, "e": 123922, "s": 123731, "text": "Now, you can see the maven project in NetBeans. Have a look at consumerBanking project Libraries and Test Libraries. You can see that NetBeans has added Maven dependencies to its build path." }, { "code": null, "e": 123994, "s": 123922, "text": "Now, Its time to build this project using maven capability of NetBeans." }, { "code": null, "e": 124055, "s": 123994, "text": "Right Click on consumerBanking project to open context menu." }, { "code": null, "e": 124089, "s": 124055, "text": "Select Clean and Build as option." }, { "code": null, "e": 124184, "s": 124089, "text": "Maven will start building the project. You can see the output in NetBeans Console as follows −" }, { "code": null, "e": 126177, "s": 124184, "text": "NetBeans: Executing 'mvn.bat -Dnetbeans.execution = true clean install'\nNetBeans: JAVA_HOME = C:\\Program Files\\Java\\jdk1.6.0_21\nScanning for projects...\n------------------------------------------------------------------------\nBuilding consumerBanking\n task-segment: [clean, install]\n------------------------------------------------------------------------\n[clean:clean]\n[resources:resources]\n[WARNING] Using platform encoding (Cp1252 actually)\nto copy filtered resources, i.e. build is platform dependent!\nskip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\main\\resources\n[compiler:compile]\nCompiling 2 source files to C:\\MVN\\consumerBanking\\target\\classes\n[resources:testResources]\n[WARNING] Using platform encoding (Cp1252 actually)\nto copy filtered resources, i.e. build is platform dependent!\nskip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\test\\resources\n[compiler:testCompile]\nCompiling 1 source file to C:\\MVN\\consumerBanking\\target\\test-classes\n[surefire:test]\nSurefire report directory: C:\\MVN\\consumerBanking\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.companyname.bank.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[jar:jar]\nBuilding jar: C:\\MVN\\consumerBanking\\target\\consumerBanking-1.0-SNAPSHOT.jar\n[install:install]\nInstalling C:\\MVN\\consumerBanking\\target\\consumerBanking-1.0-SNAPSHOT.jar\nto C:\\Users\\GB3824\\.m2\\repository\\com\\companyname\\bank\\consumerBanking\\\n1.0-SNAPSHOT\\consumerBanking-1.0-SNAPSHOT.jar\n------------------------------------------------------------------------\nBUILD SUCCESSFUL\n------------------------------------------------------------------------\nTotal time: 9 seconds\nFinished at: Thu Jul 19 12:57:28 IST 2012\nFinal Memory: 16M/85M\n------------------------------------------------------------------------" }, { "code": null, "e": 126283, "s": 126177, "text": "Now, right click on App.java. Select Run File as option. You will see the result in the NetBeans Console." }, { "code": null, "e": 127540, "s": 126283, "text": "NetBeans: Executing 'mvn.bat -Dexec.classpathScope = runtime \n-Dexec.args = -classpath %classpath com.companyname.bank.App \n-Dexec.executable = C:\\Program Files\\Java\\jdk1.6.0_21\\bin\\java.exe \n-Dnetbeans.execution = true process-classes \norg.codehaus.mojo:exec-maven-plugin:1.1.1:exec'\nNetBeans: JAVA_HOME = C:\\Program Files\\Java\\jdk1.6.0_21\nScanning for projects...\n------------------------------------------------------------------------\nBuilding consumerBanking\n task-segment: [process-classes, \n org.codehaus.mojo:exec-maven-plugin:1.1.1:exec]\n------------------------------------------------------------------------\n[resources:resources]\n[WARNING] Using platform encoding (Cp1252 actually) \nto copy filtered resources, i.e. build is platform dependent!\nskip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\main\\resources\n[compiler:compile]\nNothing to compile - all classes are up to date\n[exec:exec]\nHello World!\n------------------------------------------------------------------------\nBUILD SUCCESSFUL\n------------------------------------------------------------------------\nTotal time: 1 second\nFinished at: Thu Jul 19 14:18:13 IST 2012\nFinal Memory: 7M/64M\n------------------------------------------------------------------------\n" }, { "code": null, "e": 127653, "s": 127540, "text": "IntelliJ IDEA has in-built support for Maven. We are using IntelliJ IDEA Community Edition 11.1 in this example." }, { "code": null, "e": 127710, "s": 127653, "text": "Some of the features of IntelliJ IDEA are listed below −" }, { "code": null, "e": 127754, "s": 127710, "text": "You can run Maven goals from IntelliJ IDEA." }, { "code": null, "e": 127798, "s": 127754, "text": "You can run Maven goals from IntelliJ IDEA." }, { "code": null, "e": 127888, "s": 127798, "text": "You can view the output of Maven commands inside the IntelliJ IDEA using its own console." }, { "code": null, "e": 127978, "s": 127888, "text": "You can view the output of Maven commands inside the IntelliJ IDEA using its own console." }, { "code": null, "e": 128024, "s": 127978, "text": "You can update maven dependencies within IDE." }, { "code": null, "e": 128070, "s": 128024, "text": "You can update maven dependencies within IDE." }, { "code": null, "e": 128125, "s": 128070, "text": "You can Launch Maven builds from within IntelliJ IDEA." }, { "code": null, "e": 128180, "s": 128125, "text": "You can Launch Maven builds from within IntelliJ IDEA." }, { "code": null, "e": 128265, "s": 128180, "text": "IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml." }, { "code": null, "e": 128350, "s": 128265, "text": "IntelliJ IDEA does the dependency management automatically based on Maven's pom.xml." }, { "code": null, "e": 128508, "s": 128350, "text": "IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace)." }, { "code": null, "e": 128666, "s": 128508, "text": "IntelliJ IDEA resolves Maven dependencies from its workspace without installing to local Maven repository (requires dependency project be in same workspace)." }, { "code": null, "e": 128778, "s": 128666, "text": "IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories." }, { "code": null, "e": 128890, "s": 128778, "text": "IntelliJ IDEA automatically downloads the required dependencies and sources from the remote Maven repositories." }, { "code": null, "e": 128963, "s": 128890, "text": "IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml." }, { "code": null, "e": 129036, "s": 128963, "text": "IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml." }, { "code": null, "e": 129129, "s": 129036, "text": "Following example will help you to leverage benefits of integrating IntelliJ IDEA and Maven." }, { "code": null, "e": 129184, "s": 129129, "text": "We will import Maven project using New Project Wizard." }, { "code": null, "e": 129204, "s": 129184, "text": "Open IntelliJ IDEA." }, { "code": null, "e": 129224, "s": 129204, "text": "Open IntelliJ IDEA." }, { "code": null, "e": 129263, "s": 129224, "text": "Select File Menu > New Project Option." }, { "code": null, "e": 129302, "s": 129263, "text": "Select File Menu > New Project Option." }, { "code": null, "e": 129345, "s": 129302, "text": "Select import project from existing model." }, { "code": null, "e": 129388, "s": 129345, "text": "Select import project from existing model." }, { "code": null, "e": 129408, "s": 129388, "text": "Select Maven option" }, { "code": null, "e": 129605, "s": 129408, "text": "Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven." }, { "code": null, "e": 129802, "s": 129605, "text": "Select Project location, where a project was created using Maven. We have created a Java Project consumerBanking. Go to ‘Creating Java Project' chapter, to see how to create a project using Maven." }, { "code": null, "e": 129834, "s": 129802, "text": "Select Maven project to import." }, { "code": null, "e": 129878, "s": 129834, "text": "Enter name of the project and click finish." }, { "code": null, "e": 130089, "s": 129878, "text": "Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section." }, { "code": null, "e": 130300, "s": 130089, "text": "Now, you can see the maven project in IntelliJ IDEA. Have a look at consumerBanking project external libraries. You can see that IntelliJ IDEA has added Maven dependencies to its build path under Maven section." }, { "code": null, "e": 130373, "s": 130300, "text": "Now, it is time to build this project using capability of IntelliJ IDEA." }, { "code": null, "e": 130405, "s": 130373, "text": "Select consumerBanking project." }, { "code": null, "e": 130437, "s": 130405, "text": "Select consumerBanking project." }, { "code": null, "e": 130479, "s": 130437, "text": "Select Buid menu > Rebuild Project Option" }, { "code": null, "e": 130521, "s": 130479, "text": "Select Buid menu > Rebuild Project Option" }, { "code": null, "e": 130569, "s": 130521, "text": "You can see the output in IntelliJ IDEA Console" }, { "code": null, "e": 130616, "s": 130569, "text": "4:01:56 PM Compilation completed successfully\n" }, { "code": null, "e": 130648, "s": 130616, "text": "Select consumerBanking project." }, { "code": null, "e": 130680, "s": 130648, "text": "Select consumerBanking project." }, { "code": null, "e": 130726, "s": 130680, "text": "Right click on App.java to open context menu." }, { "code": null, "e": 130772, "s": 130726, "text": "Right click on App.java to open context menu." }, { "code": null, "e": 130794, "s": 130772, "text": "select Run App.main()" }, { "code": null, "e": 130816, "s": 130794, "text": "select Run App.main()" }, { "code": null, "e": 130866, "s": 130816, "text": "You will see the result in IntelliJ IDEA Console." }, { "code": null, "e": 132116, "s": 130866, "text": "\"C:\\Program Files\\Java\\jdk1.6.0_21\\bin\\java\"\n-Didea.launcher.port=7533 \n\"-Didea.launcher.bin.path=\nC:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition 11.1.2\\bin\"\n-Dfile.encoding=UTF-8 \n-classpath \"C:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\charsets.jar;\n\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\deploy.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\javaws.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\jce.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\jsse.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\management-agent.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\plugin.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\resources.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\rt.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\dnsns.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\localedata.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\sunjce_provider.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\sunmscapi.jar;\nC:\\Program Files\\Java\\jdk1.6.0_21\\jre\\lib\\ext\\sunpkcs11.jar\n\nC:\\MVN\\consumerBanking\\target\\classes;\nC:\\Program Files\\JetBrains\\\nIntelliJ IDEA Community Edition 11.1.2\\lib\\idea_rt.jar\" \ncom.intellij.rt.execution.application.AppMain com.companyname.bank.App\nHello World!\n\nProcess finished with exit code 0\n" }, { "code": null, "e": 132149, "s": 132116, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 132163, "s": 132149, "text": " Karthikeya T" }, { "code": null, "e": 132198, "s": 132163, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 132216, "s": 132198, "text": " Quaatso Learning" }, { "code": null, "e": 132223, "s": 132216, "text": " Print" }, { "code": null, "e": 132234, "s": 132223, "text": " Add Notes" } ]
Goldman Sachs Interview Experience 2021 | 4+ Years Experienced - GeeksforGeeks
21 Jul, 2021 I gave the Goldman Sachs interview this year in June. The whole process took 2 weeks. I had 3 rounds on a single day and after that there was a manager round. Online HackerRank Test: https://leetcode.com/discuss/interview-question/625140/Goldman-Sachs-or-OA-2020-or-Array-Burst-Problem-and-Birthday-Partyhttps://www.geeksforgeeks.org/coin-change-dp-7/ https://leetcode.com/discuss/interview-question/625140/Goldman-Sachs-or-OA-2020-or-Array-Burst-Problem-and-Birthday-Party https://www.geeksforgeeks.org/coin-change-dp-7/ Screening Round: Find a given string is Pangram or notGiven 2-d array with student name and marks find the best avg marks of any student Find a given string is Pangram or not Given 2-d array with student name and marks find the best avg marks of any student Round 1: Given alphabetical array
a b c d e f g h I j 
k l m n o p q r s t
 u v w x y
 z. Start from [0,0] and create a string path to make a given string. To take a letter use T
 to go down, use D. To go left use L. To go up use UIf the given string is = “abmd” The output is =. “TRTRDDTRUUT”You can print any output just take of z as you can’t way go down all the way to z’s row to reach z you have to go via `u` onlyGiven a sorted array print the any 2 numbers whose sum is closest to given number Given alphabetical array
a b c d e f g h I j 
k l m n o p q r s t
 u v w x y
 z. Start from [0,0] and create a string path to make a given string. To take a letter use T
 to go down, use D. To go left use L. To go up use UIf the given string is = “abmd” The output is =. “TRTRDDTRUUT”You can print any output just take of z as you can’t way go down all the way to z’s row to reach z you have to go via `u` only If the given string is = “abmd” The output is =. “TRTRDDTRUUT” You can print any output just take of z as you can’t way go down all the way to z’s row to reach z you have to go via `u` only Given a sorted array print the any 2 numbers whose sum is closest to given number Round 2: https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/Design a Library management SystemSome Java questions were asked related to concurrent hashmap, Java callable methods https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/ Design a Library management System Some Java questions were asked related to concurrent hashmap, Java callable methods Round 3: System design question – need to design to detect anomaly in stock purchasing:- need to store previous stock purchase in a different table and use that System design question – need to design to detect anomaly in stock purchasing:- need to store previous stock purchase in a different table and use that It was medium level interview, and I got selected. Goldman Sachs Marketing Experienced Interview Experiences Goldman Sachs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced) Paypal Interview Experience for SSE Amazon Interview Experience for System Development Engineer (Exp - 6 months) Walmart Interview Experience for SDE-III Amazon Interview Questions Microsoft Interview Experience for Internship (Via Engage) Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
[ { "code": null, "e": 25215, "s": 25187, "text": "\n21 Jul, 2021" }, { "code": null, "e": 25374, "s": 25215, "text": "I gave the Goldman Sachs interview this year in June. The whole process took 2 weeks. I had 3 rounds on a single day and after that there was a manager round." }, { "code": null, "e": 25398, "s": 25374, "text": "Online HackerRank Test:" }, { "code": null, "e": 25567, "s": 25398, "text": "https://leetcode.com/discuss/interview-question/625140/Goldman-Sachs-or-OA-2020-or-Array-Burst-Problem-and-Birthday-Partyhttps://www.geeksforgeeks.org/coin-change-dp-7/" }, { "code": null, "e": 25689, "s": 25567, "text": "https://leetcode.com/discuss/interview-question/625140/Goldman-Sachs-or-OA-2020-or-Array-Burst-Problem-and-Birthday-Party" }, { "code": null, "e": 25737, "s": 25689, "text": "https://www.geeksforgeeks.org/coin-change-dp-7/" }, { "code": null, "e": 25754, "s": 25737, "text": "Screening Round:" }, { "code": null, "e": 25874, "s": 25754, "text": "Find a given string is Pangram or notGiven 2-d array with student name and marks find the best avg marks of any student" }, { "code": null, "e": 25912, "s": 25874, "text": "Find a given string is Pangram or not" }, { "code": null, "e": 25995, "s": 25912, "text": "Given 2-d array with student name and marks find the best avg marks of any student" }, { "code": null, "e": 26004, "s": 25995, "text": "Round 1:" }, { "code": null, "e": 26499, "s": 26004, "text": "Given alphabetical array
a b c d e f g h I j 
k l m n o p q r s t
 u v w x y
 z. Start from [0,0] and create a string path to make a given string. To take a letter use T
 to go down, use D. To go left use L. To go up use UIf the given string is = “abmd”\nThe output is =. “TRTRDDTRUUT”You can print any output just take of z as you can’t way go down all the way to z’s row to reach z you have to go via `u` onlyGiven a sorted array print the any 2 numbers whose sum is closest to given number" }, { "code": null, "e": 26913, "s": 26499, "text": "Given alphabetical array
a b c d e f g h I j 
k l m n o p q r s t
 u v w x y
 z. Start from [0,0] and create a string path to make a given string. To take a letter use T
 to go down, use D. To go left use L. To go up use UIf the given string is = “abmd”\nThe output is =. “TRTRDDTRUUT”You can print any output just take of z as you can’t way go down all the way to z’s row to reach z you have to go via `u` only" }, { "code": null, "e": 26976, "s": 26913, "text": "If the given string is = “abmd”\nThe output is =. “TRTRDDTRUUT”" }, { "code": null, "e": 27103, "s": 26976, "text": "You can print any output just take of z as you can’t way go down all the way to z’s row to reach z you have to go via `u` only" }, { "code": null, "e": 27185, "s": 27103, "text": "Given a sorted array print the any 2 numbers whose sum is closest to given number" }, { "code": null, "e": 27194, "s": 27185, "text": "Round 2:" }, { "code": null, "e": 27396, "s": 27194, "text": "https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/Design a Library management SystemSome Java questions were asked related to concurrent hashmap, Java callable methods" }, { "code": null, "e": 27481, "s": 27396, "text": "https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/" }, { "code": null, "e": 27516, "s": 27481, "text": "Design a Library management System" }, { "code": null, "e": 27600, "s": 27516, "text": "Some Java questions were asked related to concurrent hashmap, Java callable methods" }, { "code": null, "e": 27609, "s": 27600, "text": "Round 3:" }, { "code": null, "e": 27761, "s": 27609, "text": "System design question – need to design to detect anomaly in stock purchasing:- need to store previous stock purchase in a different table and use that" }, { "code": null, "e": 27913, "s": 27761, "text": "System design question – need to design to detect anomaly in stock purchasing:- need to store previous stock purchase in a different table and use that" }, { "code": null, "e": 27964, "s": 27913, "text": "It was medium level interview, and I got selected." }, { "code": null, "e": 27978, "s": 27964, "text": "Goldman Sachs" }, { "code": null, "e": 27988, "s": 27978, "text": "Marketing" }, { "code": null, "e": 28000, "s": 27988, "text": "Experienced" }, { "code": null, "e": 28022, "s": 28000, "text": "Interview Experiences" }, { "code": null, "e": 28036, "s": 28022, "text": "Goldman Sachs" }, { "code": null, "e": 28134, "s": 28036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28143, "s": 28134, "text": "Comments" }, { "code": null, "e": 28156, "s": 28143, "text": "Old Comments" }, { "code": null, "e": 28221, "s": 28156, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 28301, "s": 28221, "text": "Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)" }, { "code": null, "e": 28337, "s": 28301, "text": "Paypal Interview Experience for SSE" }, { "code": null, "e": 28414, "s": 28337, "text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)" }, { "code": null, "e": 28455, "s": 28414, "text": "Walmart Interview Experience for SDE-III" }, { "code": null, "e": 28482, "s": 28455, "text": "Amazon Interview Questions" }, { "code": null, "e": 28541, "s": 28482, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 28601, "s": 28541, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 28651, "s": 28601, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
3 NumPy Functions to Facilitate Data Analysis with Pandas | by Soner Yıldırım | Towards Data Science
Pandas and Numpy are the two most popular Python libraries used for data analysis and manipulation. Pandas is equipped with a lot of practical and handy functions. Pandas also allows for using some Numpy functions which results in more functional and efficient operations with Pandas. In this article, we will go over 3 Numpy functions that are of great help when doing data analysis with Pandas. Let’s start with importing the libraries and creating a sample data frame to work on. import numpy as npimport pandas as pddf = pd.DataFrame({ "A": np.random.randint(10, size=6), "B": np.random.randint(20, size=6), "C": np.random.randint(10,20, size=6), "D": np.random.random(6).round(2)})df The first one we are interested in is the where function which provides a convenient way for creating conditional columns. We pass a condition to the where function and determine a separate value for the rows that satisfy and do not satisfy the condition. For instance, we can create a column “E” that takes the value 1 if both the values in columns “B” and “C” are higher than 10. Otherwise, the value in column “E” is 0. df["E"] = np.where((df["B"] > 10) & (df["C"] > 10), 1, 0)df We can combine as many conditions as needed using logical operators. The select function is like an upgraded version of the where. We are able apply multiple conditions to determine a separate value for each. With where function, we can only test a condition (or a set of conditions) and determine two values. What the select function does is take it one step further. We can test multiple conditions (or multiple sets of conditions) and assign a separate value for rows that meet each condition set. It also allows for specifying a default value to be used for rows that do not meet any of the conditions. It will be more clear with an example. conditions = [ (df["B"] >= 10) & (df["A"] == 0), (df["B"] >= 10) & (df["A"] == 8)]values = [1, 2]df["F"] = np.select(conditions, values, default=0)df The log function, as its name suggests, is used for taking the logarithm of a value. np.log10(100)2.0np.log2(16)4.0np.log(1000)6.907755278982137 Thankfully, we can apply the log function to an entire column of a data frame. Taking the log of a column is a useful practice in many cases. For instance, if the target variable in a machine learning model includes outliers, it is better to use the log of the target variable in the model. Log linear models are commonly used in machine learning. We have the following data frame: The values 600 and 850 are quite large compared to the other values in the target column. Let’s take the log of this column to see the difference. df["log_target"] = np.log(df["target"])df The differences have become smaller due to the log function. Numpy and Pandas go hand in hand. In fact, Pandas and some other Python libraries were built on top of Numpy. In most cases, we are able to complete a task with Pandas functions. However, using Numpy functions in some cases provide additional benefits and functionality. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 336, "s": 172, "text": "Pandas and Numpy are the two most popular Python libraries used for data analysis and manipulation. Pandas is equipped with a lot of practical and handy functions." }, { "code": null, "e": 569, "s": 336, "text": "Pandas also allows for using some Numpy functions which results in more functional and efficient operations with Pandas. In this article, we will go over 3 Numpy functions that are of great help when doing data analysis with Pandas." }, { "code": null, "e": 655, "s": 569, "text": "Let’s start with importing the libraries and creating a sample data frame to work on." }, { "code": null, "e": 873, "s": 655, "text": "import numpy as npimport pandas as pddf = pd.DataFrame({ \"A\": np.random.randint(10, size=6), \"B\": np.random.randint(20, size=6), \"C\": np.random.randint(10,20, size=6), \"D\": np.random.random(6).round(2)})df" }, { "code": null, "e": 996, "s": 873, "text": "The first one we are interested in is the where function which provides a convenient way for creating conditional columns." }, { "code": null, "e": 1129, "s": 996, "text": "We pass a condition to the where function and determine a separate value for the rows that satisfy and do not satisfy the condition." }, { "code": null, "e": 1296, "s": 1129, "text": "For instance, we can create a column “E” that takes the value 1 if both the values in columns “B” and “C” are higher than 10. Otherwise, the value in column “E” is 0." }, { "code": null, "e": 1356, "s": 1296, "text": "df[\"E\"] = np.where((df[\"B\"] > 10) & (df[\"C\"] > 10), 1, 0)df" }, { "code": null, "e": 1425, "s": 1356, "text": "We can combine as many conditions as needed using logical operators." }, { "code": null, "e": 1565, "s": 1425, "text": "The select function is like an upgraded version of the where. We are able apply multiple conditions to determine a separate value for each." }, { "code": null, "e": 1963, "s": 1565, "text": "With where function, we can only test a condition (or a set of conditions) and determine two values. What the select function does is take it one step further. We can test multiple conditions (or multiple sets of conditions) and assign a separate value for rows that meet each condition set. It also allows for specifying a default value to be used for rows that do not meet any of the conditions." }, { "code": null, "e": 2002, "s": 1963, "text": "It will be more clear with an example." }, { "code": null, "e": 2154, "s": 2002, "text": "conditions = [ (df[\"B\"] >= 10) & (df[\"A\"] == 0), (df[\"B\"] >= 10) & (df[\"A\"] == 8)]values = [1, 2]df[\"F\"] = np.select(conditions, values, default=0)df" }, { "code": null, "e": 2239, "s": 2154, "text": "The log function, as its name suggests, is used for taking the logarithm of a value." }, { "code": null, "e": 2299, "s": 2239, "text": "np.log10(100)2.0np.log2(16)4.0np.log(1000)6.907755278982137" }, { "code": null, "e": 2647, "s": 2299, "text": "Thankfully, we can apply the log function to an entire column of a data frame. Taking the log of a column is a useful practice in many cases. For instance, if the target variable in a machine learning model includes outliers, it is better to use the log of the target variable in the model. Log linear models are commonly used in machine learning." }, { "code": null, "e": 2681, "s": 2647, "text": "We have the following data frame:" }, { "code": null, "e": 2828, "s": 2681, "text": "The values 600 and 850 are quite large compared to the other values in the target column. Let’s take the log of this column to see the difference." }, { "code": null, "e": 2870, "s": 2828, "text": "df[\"log_target\"] = np.log(df[\"target\"])df" }, { "code": null, "e": 2931, "s": 2870, "text": "The differences have become smaller due to the log function." }, { "code": null, "e": 3041, "s": 2931, "text": "Numpy and Pandas go hand in hand. In fact, Pandas and some other Python libraries were built on top of Numpy." }, { "code": null, "e": 3202, "s": 3041, "text": "In most cases, we are able to complete a task with Pandas functions. However, using Numpy functions in some cases provide additional benefits and functionality." } ]
Count all pairs with given XOR - GeeksforGeeks
05 Nov, 2021 Given an array of distinct positive integers and a number x, find the number of pairs of integers in the array whose XOR is equal to x. Examples: Input : arr[] = {5, 4, 10, 15, 7, 6}, x = 5 Output : 1 Explanation : (10 ^ 15) = 5 Input : arr[] = {3, 6, 8, 10, 15, 50}, x = 5 Output : 2 Explanation : (3 ^ 6) = 5 and (10 ^ 15) = 5 A Simple solution is to traverse each element and check if there’s another number whose XOR with it is equal to x. This solution takes O(n2) time. An efficient solution to this problem takes O(n) time. The idea is based on the fact that arr[i] ^ arr[j] is equal to x if and only if arr[i] ^ x is equal to arr[j]. 1) Initialize result as 0. 2) Create an empty hash set "s". 3) Do following for each element arr[i] in arr[] (a) If x ^ arr[i] is in "s", then increment result by 1. (b) Insert arr[i] into the hash set "s". 3) return result. C++ Java Python3 C# Javascript // C++ program to Count all pair with given XOR// value x#include<bits/stdc++.h> using namespace std; // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.int xorPairCount(int arr[], int n, int x){ int result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ unordered_set<int> s; for (int i=0; i<n ; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.find(x^arr[i]) != s.end()) result++; // Make element visited s.insert(arr[i]); } // return total count of pairs with XOR equal to x return result;} // driver programint main(){ int arr[] = {5 , 4 ,10, 15, 7, 6}; int n = sizeof(arr)/sizeof(arr[0]); int x = 5; cout << "Count of pairs with given XOR = " << xorPairCount(arr, n, x); return 0;} // Java program to Count all pair with// given XOR value ximport java.util.*; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR // value equals to x. static int xorPairCount(int arr[], int n, int x) { int result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.contains(x ^ arr[i]) && (x ^ arr[i]) == (int) s.toArray()[s.size() - 1]) { result++; } // Make element visited s.add(arr[i]); } // return total count of // pairs with XOR equal to x return result; } // Driver code public static void main(String[] args) { int arr[] = {5, 4, 10, 15, 7, 6}; int n = arr.length; int x = 5; System.out.print("Count of pairs with given XOR = " + xorPairCount(arr, n, x)); }} // This code contributed by Rajput-Ji # Python3 program to count all the pair# with given xor # Returns count of pairs in arr[0..n-1]# with XOR value equals to x.def xorPairCount(arr, n, x): result = 0 # Initialize result # create empty set that stores the # visiting element of array. s = set() for i in range(0, n): # If there exist an element in set s # with XOR equals to x^arr[i], that # means there exist an element such # that the XOR of element with arr[i] # is equal to x, then increment count. if(x ^ arr[i] in s): result = result + 1 # Make element visited s.add(arr[i]) return result # Driver Codeif __name__ == "__main__": arr = [5, 4, 10, 15, 7, 6] n = len(arr) x = 5 print("Count of pair with given XOR = " + str(xorPairCount(arr, n, x))) # This code is contributed by Anubhav Natani // C# program to Count all pair with// given XOR value xusing System;using System.Collections.Generic; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR // value equals to x. static int xorPairCount(int []arr, int n, int x) { int result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.Contains(x ^ arr[i])) { result++; } // Make element visited s.Add(arr[i]); } // return total count of // pairs with XOR equal to x return result; } // Driver code public static void Main() { int []arr = {5, 4, 10, 15, 7, 6}; int n = arr.Length; int x = 5; Console.WriteLine("Count of pairs with given XOR = " + xorPairCount(arr, n, x)); }} /* This code contributed by PrinciRaj1992 */ <script>// Javascript program to Count all pair with// given XOR value x // Returns count of pairs in arr[0..n-1] with XOR // value equals to x. function xorPairCount(arr,n,x) { let result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ let s = new Set(); for (let i = 0; i < n; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.has(x ^ arr[i]) ) { result++; } // Make element visited s.add(arr[i]); } // return total count of // pairs with XOR equal to x return result; } // Driver code let arr=[5, 4, 10, 15, 7, 6]; let n = arr.length; let x = 5; document.write("Count of pairs with given XOR = " + xorPairCount(arr, n, x)); // This code is contributed by unknown2108</script> Output: Count of pairs with given XOR = 1 Time complexity : O(n) Auxiliary Space: O(n) How to handle duplicates? The above efficient solution doesn’t work if there are duplicates in the input array. For example, the above solution produces different results for {2, 2, 5} and {5, 2, 2}. To handle duplicates, we store counts of occurrences of all elements. We use unordered_map instead of unordered_set. C++ Java Python3 C# Javascript // C++ program to Count all pair with given XOR// value x#include<bits/stdc++.h> using namespace std; // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.int xorPairCount(int arr[], int n, int x){ int result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. unordered_map<int, int> m; for (int i=0; i<n ; i++) { int curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.find(curr_xor) != m.end()) result += m[curr_xor]; // Increment count of current element m[arr[i]]++; } // return total count of pairs with XOR equal to x return result;} // driver programint main(){ int arr[] = {2, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); int x = 0; cout << "Count of pairs with given XOR = " << xorPairCount(arr, n, x); return 0;} // Java program to Count all pair with given XOR// value ximport java.util.*; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.static int xorPairCount(int arr[], int n, int x){ int result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. Map<Integer,Integer> m = new HashMap<>(); for (int i = 0; i < n ; i++) { int curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.containsKey(curr_xor)) result += m.get(curr_xor); // Increment count of current element if(m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else{ m.put(arr[i], 1); } } // return total count of pairs with XOR equal to x return result;} // Driver codepublic static void main(String[] args){ int arr[] = {2, 5, 2}; int n = arr.length; int x = 0; System.out.println("Count of pairs with given XOR = " + xorPairCount(arr, n, x));}} // This code has been contributed by 29AjayKumar # Python3 program to Count all pair with# given XOR value x # Returns count of pairs in arr[0..n-1]# with XOR value equals to x.def xorPairCount(arr, n, x): result = 0 # Initialize result # create empty map that stores counts # of individual elements of array. m = dict() for i in range(n): curr_xor = x ^ arr[i] # If there exist an element in map m # with XOR equals to x^arr[i], that # means there exist an element such that # the XOR of element with arr[i] is equal # to x, then increment count. if (curr_xor in m.keys()): result += m[curr_xor] # Increment count of current element if arr[i] in m.keys(): m[arr[i]] += 1 else: m[arr[i]] = 1 # return total count of pairs # with XOR equal to x return result # Driver Codearr = [2, 5, 2]n = len(arr)x = 0print("Count of pairs with given XOR = ", xorPairCount(arr, n, x)) # This code is contributed by Mohit Kumar // C# program to Count all pair with given XOR// value xusing System;using System.Collections.Generic; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.static int xorPairCount(int []arr, int n, int x){ int result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. Dictionary<int,int> m = new Dictionary<int,int>(); for (int i = 0; i < n ; i++) { int curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.ContainsKey(curr_xor)) result += m[curr_xor]; // Increment count of current element if(m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // return total count of pairs with XOR equal to x return result;} // Driver codepublic static void Main(String[] args){ int []arr = {2, 5, 2}; int n = arr.Length; int x = 0; Console.WriteLine("Count of pairs with given XOR = " + xorPairCount(arr, n, x));}} // This code has been contributed by 29AjayKumar <script> // Javascript program to Count all pair with given XOR// value x // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.function xorPairCount(arr, n, x){ let result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. let m = new Map(); for (let i = 0; i < n ; i++) { let curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.has(curr_xor)) result += m.get(curr_xor); // Increment count of current element if(m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1); } else{ m.set(arr[i], 1); } } // return total count of pairs with XOR equal to x return result;} // Driver program let arr = [2, 5, 2]; let n = arr.length; let x = 0; document.write("Count of pairs with given XOR = " + xorPairCount(arr, n, x)); </script> Output: Count of pairs with given XOR = 1 Time complexity : O(n) Auxiliary Space: O(n) This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. NerdCaps AnubhavNatani mohit kumar 29 Rajput-Ji princiraj1992 29AjayKumar unknown2108 avijitmondal1998 subhammahato348 Bitwise-XOR Arrays Bit Magic Hash Arrays Hash Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 24863, "s": 24835, "text": "\n05 Nov, 2021" }, { "code": null, "e": 25000, "s": 24863, "text": "Given an array of distinct positive integers and a number x, find the number of pairs of integers in the array whose XOR is equal to x. " }, { "code": null, "e": 25011, "s": 25000, "text": "Examples: " }, { "code": null, "e": 25197, "s": 25011, "text": "Input : arr[] = {5, 4, 10, 15, 7, 6}, x = 5\nOutput : 1\nExplanation : (10 ^ 15) = 5\n\nInput : arr[] = {3, 6, 8, 10, 15, 50}, x = 5\nOutput : 2\nExplanation : (3 ^ 6) = 5 and (10 ^ 15) = 5 " }, { "code": null, "e": 25513, "s": 25197, "text": "A Simple solution is to traverse each element and check if there’s another number whose XOR with it is equal to x. This solution takes O(n2) time. An efficient solution to this problem takes O(n) time. The idea is based on the fact that arr[i] ^ arr[j] is equal to x if and only if arr[i] ^ x is equal to arr[j]. " }, { "code": null, "e": 25750, "s": 25513, "text": "1) Initialize result as 0.\n2) Create an empty hash set \"s\".\n3) Do following for each element arr[i] in arr[]\n (a) If x ^ arr[i] is in \"s\", then increment result by 1.\n (b) Insert arr[i] into the hash set \"s\".\n3) return result." }, { "code": null, "e": 25754, "s": 25750, "text": "C++" }, { "code": null, "e": 25759, "s": 25754, "text": "Java" }, { "code": null, "e": 25767, "s": 25759, "text": "Python3" }, { "code": null, "e": 25770, "s": 25767, "text": "C#" }, { "code": null, "e": 25781, "s": 25770, "text": "Javascript" }, { "code": "// C++ program to Count all pair with given XOR// value x#include<bits/stdc++.h> using namespace std; // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.int xorPairCount(int arr[], int n, int x){ int result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ unordered_set<int> s; for (int i=0; i<n ; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.find(x^arr[i]) != s.end()) result++; // Make element visited s.insert(arr[i]); } // return total count of pairs with XOR equal to x return result;} // driver programint main(){ int arr[] = {5 , 4 ,10, 15, 7, 6}; int n = sizeof(arr)/sizeof(arr[0]); int x = 5; cout << \"Count of pairs with given XOR = \" << xorPairCount(arr, n, x); return 0;}", "e": 26918, "s": 25781, "text": null }, { "code": "// Java program to Count all pair with// given XOR value ximport java.util.*; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR // value equals to x. static int xorPairCount(int arr[], int n, int x) { int result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.contains(x ^ arr[i]) && (x ^ arr[i]) == (int) s.toArray()[s.size() - 1]) { result++; } // Make element visited s.add(arr[i]); } // return total count of // pairs with XOR equal to x return result; } // Driver code public static void main(String[] args) { int arr[] = {5, 4, 10, 15, 7, 6}; int n = arr.length; int x = 5; System.out.print(\"Count of pairs with given XOR = \" + xorPairCount(arr, n, x)); }} // This code contributed by Rajput-Ji", "e": 28355, "s": 26918, "text": null }, { "code": "# Python3 program to count all the pair# with given xor # Returns count of pairs in arr[0..n-1]# with XOR value equals to x.def xorPairCount(arr, n, x): result = 0 # Initialize result # create empty set that stores the # visiting element of array. s = set() for i in range(0, n): # If there exist an element in set s # with XOR equals to x^arr[i], that # means there exist an element such # that the XOR of element with arr[i] # is equal to x, then increment count. if(x ^ arr[i] in s): result = result + 1 # Make element visited s.add(arr[i]) return result # Driver Codeif __name__ == \"__main__\": arr = [5, 4, 10, 15, 7, 6] n = len(arr) x = 5 print(\"Count of pair with given XOR = \" + str(xorPairCount(arr, n, x))) # This code is contributed by Anubhav Natani", "e": 29260, "s": 28355, "text": null }, { "code": "// C# program to Count all pair with// given XOR value xusing System;using System.Collections.Generic; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR // value equals to x. static int xorPairCount(int []arr, int n, int x) { int result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.Contains(x ^ arr[i])) { result++; } // Make element visited s.Add(arr[i]); } // return total count of // pairs with XOR equal to x return result; } // Driver code public static void Main() { int []arr = {5, 4, 10, 15, 7, 6}; int n = arr.Length; int x = 5; Console.WriteLine(\"Count of pairs with given XOR = \" + xorPairCount(arr, n, x)); }} /* This code contributed by PrinciRaj1992 */", "e": 30639, "s": 29260, "text": null }, { "code": "<script>// Javascript program to Count all pair with// given XOR value x // Returns count of pairs in arr[0..n-1] with XOR // value equals to x. function xorPairCount(arr,n,x) { let result = 0; // Initialize result // create empty set that stores the visiting // element of array. // Refer below post for details of unordered_set // https://www.geeksforgeeks.org/unorderd_set-stl-uses/ let s = new Set(); for (let i = 0; i < n; i++) { // If there exist an element in set s // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (s.has(x ^ arr[i]) ) { result++; } // Make element visited s.add(arr[i]); } // return total count of // pairs with XOR equal to x return result; } // Driver code let arr=[5, 4, 10, 15, 7, 6]; let n = arr.length; let x = 5; document.write(\"Count of pairs with given XOR = \" + xorPairCount(arr, n, x)); // This code is contributed by unknown2108</script>", "e": 31912, "s": 30639, "text": null }, { "code": null, "e": 31922, "s": 31912, "text": "Output: " }, { "code": null, "e": 31956, "s": 31922, "text": "Count of pairs with given XOR = 1" }, { "code": null, "e": 31979, "s": 31956, "text": "Time complexity : O(n)" }, { "code": null, "e": 32004, "s": 31979, "text": "Auxiliary Space: O(n) " }, { "code": null, "e": 32323, "s": 32004, "text": "How to handle duplicates? The above efficient solution doesn’t work if there are duplicates in the input array. For example, the above solution produces different results for {2, 2, 5} and {5, 2, 2}. To handle duplicates, we store counts of occurrences of all elements. We use unordered_map instead of unordered_set. " }, { "code": null, "e": 32327, "s": 32323, "text": "C++" }, { "code": null, "e": 32332, "s": 32327, "text": "Java" }, { "code": null, "e": 32340, "s": 32332, "text": "Python3" }, { "code": null, "e": 32343, "s": 32340, "text": "C#" }, { "code": null, "e": 32354, "s": 32343, "text": "Javascript" }, { "code": "// C++ program to Count all pair with given XOR// value x#include<bits/stdc++.h> using namespace std; // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.int xorPairCount(int arr[], int n, int x){ int result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. unordered_map<int, int> m; for (int i=0; i<n ; i++) { int curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.find(curr_xor) != m.end()) result += m[curr_xor]; // Increment count of current element m[arr[i]]++; } // return total count of pairs with XOR equal to x return result;} // driver programint main(){ int arr[] = {2, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); int x = 0; cout << \"Count of pairs with given XOR = \" << xorPairCount(arr, n, x); return 0;}", "e": 33439, "s": 32354, "text": null }, { "code": "// Java program to Count all pair with given XOR// value ximport java.util.*; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.static int xorPairCount(int arr[], int n, int x){ int result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. Map<Integer,Integer> m = new HashMap<>(); for (int i = 0; i < n ; i++) { int curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.containsKey(curr_xor)) result += m.get(curr_xor); // Increment count of current element if(m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else{ m.put(arr[i], 1); } } // return total count of pairs with XOR equal to x return result;} // Driver codepublic static void main(String[] args){ int arr[] = {2, 5, 2}; int n = arr.length; int x = 0; System.out.println(\"Count of pairs with given XOR = \" + xorPairCount(arr, n, x));}} // This code has been contributed by 29AjayKumar", "e": 34718, "s": 33439, "text": null }, { "code": "# Python3 program to Count all pair with# given XOR value x # Returns count of pairs in arr[0..n-1]# with XOR value equals to x.def xorPairCount(arr, n, x): result = 0 # Initialize result # create empty map that stores counts # of individual elements of array. m = dict() for i in range(n): curr_xor = x ^ arr[i] # If there exist an element in map m # with XOR equals to x^arr[i], that # means there exist an element such that # the XOR of element with arr[i] is equal # to x, then increment count. if (curr_xor in m.keys()): result += m[curr_xor] # Increment count of current element if arr[i] in m.keys(): m[arr[i]] += 1 else: m[arr[i]] = 1 # return total count of pairs # with XOR equal to x return result # Driver Codearr = [2, 5, 2]n = len(arr)x = 0print(\"Count of pairs with given XOR = \", xorPairCount(arr, n, x)) # This code is contributed by Mohit Kumar", "e": 35739, "s": 34718, "text": null }, { "code": "// C# program to Count all pair with given XOR// value xusing System;using System.Collections.Generic; class GFG{ // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.static int xorPairCount(int []arr, int n, int x){ int result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. Dictionary<int,int> m = new Dictionary<int,int>(); for (int i = 0; i < n ; i++) { int curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.ContainsKey(curr_xor)) result += m[curr_xor]; // Increment count of current element if(m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // return total count of pairs with XOR equal to x return result;} // Driver codepublic static void Main(String[] args){ int []arr = {2, 5, 2}; int n = arr.Length; int x = 0; Console.WriteLine(\"Count of pairs with given XOR = \" + xorPairCount(arr, n, x));}} // This code has been contributed by 29AjayKumar", "e": 37110, "s": 35739, "text": null }, { "code": "<script> // Javascript program to Count all pair with given XOR// value x // Returns count of pairs in arr[0..n-1] with XOR// value equals to x.function xorPairCount(arr, n, x){ let result = 0; // Initialize result // create empty map that stores counts of // individual elements of array. let m = new Map(); for (let i = 0; i < n ; i++) { let curr_xor = x^arr[i]; // If there exist an element in map m // with XOR equals to x^arr[i], that means // there exist an element such that the // XOR of element with arr[i] is equal to // x, then increment count. if (m.has(curr_xor)) result += m.get(curr_xor); // Increment count of current element if(m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1); } else{ m.set(arr[i], 1); } } // return total count of pairs with XOR equal to x return result;} // Driver program let arr = [2, 5, 2]; let n = arr.length; let x = 0; document.write(\"Count of pairs with given XOR = \" + xorPairCount(arr, n, x)); </script>", "e": 38243, "s": 37110, "text": null }, { "code": null, "e": 38253, "s": 38243, "text": "Output: " }, { "code": null, "e": 38287, "s": 38253, "text": "Count of pairs with given XOR = 1" }, { "code": null, "e": 38310, "s": 38287, "text": "Time complexity : O(n)" }, { "code": null, "e": 38332, "s": 38310, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 38761, "s": 38332, "text": "This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 38770, "s": 38761, "text": "NerdCaps" }, { "code": null, "e": 38784, "s": 38770, "text": "AnubhavNatani" }, { "code": null, "e": 38799, "s": 38784, "text": "mohit kumar 29" }, { "code": null, "e": 38809, "s": 38799, "text": "Rajput-Ji" }, { "code": null, "e": 38823, "s": 38809, "text": "princiraj1992" }, { "code": null, "e": 38835, "s": 38823, "text": "29AjayKumar" }, { "code": null, "e": 38847, "s": 38835, "text": "unknown2108" }, { "code": null, "e": 38864, "s": 38847, "text": "avijitmondal1998" }, { "code": null, "e": 38880, "s": 38864, "text": "subhammahato348" }, { "code": null, "e": 38892, "s": 38880, "text": "Bitwise-XOR" }, { "code": null, "e": 38899, "s": 38892, "text": "Arrays" }, { "code": null, "e": 38909, "s": 38899, "text": "Bit Magic" }, { "code": null, "e": 38914, "s": 38909, "text": "Hash" }, { "code": null, "e": 38921, "s": 38914, "text": "Arrays" }, { "code": null, "e": 38926, "s": 38921, "text": "Hash" }, { "code": null, "e": 38936, "s": 38926, "text": "Bit Magic" }, { "code": null, "e": 39034, "s": 38936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39043, "s": 39034, "text": "Comments" }, { "code": null, "e": 39056, "s": 39043, "text": "Old Comments" }, { "code": null, "e": 39104, "s": 39056, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39148, "s": 39104, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39171, "s": 39148, "text": "Introduction to Arrays" }, { "code": null, "e": 39203, "s": 39171, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39217, "s": 39203, "text": "Linear Search" }, { "code": null, "e": 39244, "s": 39217, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 39290, "s": 39244, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 39358, "s": 39290, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 39387, "s": 39358, "text": "Count set bits in an integer" } ]
LCM And GCD | Practice | GeeksforGeeks
Given two numbers A and B. The task is to find out their LCM and GCD. Example 1: Input: A = 5 , B = 10 Output: 10 5 Explanation: LCM of 5 and 10 is 10, while thier GCD is 5. Example 1: Input: A = 14 , B = 8 Output: 56 2 Explanation: LCM of 14 and 8 is 56, while thier GCD is 2. Your Task: You don't need to read input or print anything. Your task is to complete the function lcmAndGcd() which takes an Integer N as input and returns a List of two Integers, the required LCM and GCD. Expected Time Complexity: O(log(min(A, B)) Expected Auxiliary Space: O(1) Constraints: 1 <= A,B <= 1018 0 mayank180919991 month ago vector<long long> lcmAndGcd(long long A , long long B) { // code here vector<long long>v; int a=__gcd(A,B); v.push_back((A*B)/a); v.push_back(a); return v; } 0 himanshulanjewar241 month ago class Solution: def gcd(self, a, b): mini min(a,b) rem = max(a, b)%mini if rem == 0: return mini else: return self.gcd(rem,mini) def 1cmAndGcd(self, A, B): #code here l = [ ] l.append((A*B)//self.gcd(A,B)) l.append(self.gcd(A,B)) return l 0 soham0071 month ago long long gcd(int a,int b){ return b==0?a:gcd(b,a%b); } vector<long long> lcmAndGcd(long long A , long long B) { // code here vector<long long>arr; long long st = gcd(A,B); long long st1 = (A*B)/st; arr.push_back(st1); arr.push_back(st); return arr; } 0 sharmarahul996111 month ago long long C=A; long long D=B; while(A!=B){ if(A>B){ A=A-B; }if(B>A){ B=B-A; } } long long gcd = A; long long lcm = (C*D)/gcd; return {lcm , gcd}; +1 itsmeshahid2 months ago vector<long long> lcmAndGcd(long long A , long long B) { long long gcd=1; long long maxi=max(A,B); long long mini=min(A,B); while(maxi%mini!=0){ long long rem=maxi%mini; maxi=mini; mini=rem; } gcd=mini; long long lcm=A*B/gcd; return {lcm, gcd}; } +1 anuraggulati2412 months ago c++ optamized solution do not make recursive calls in this gcd function because space complexity is increase and in iterative sapace is constant and time is linear .. so no need for recursive call .... long long gcd(long long int a , long long int b) { if(a==b) { return b; } if(a%b == 0) { return b; } if(b%a == 0) { return a; } while(a != b) { if(a>b) { a = a-b; } else { b = b - a; } } return b; } vector<long long> lcmAndGcd(long long A , long long B) { // code here vector<long long> vec1 = {(A*B)/gcd(A,B) , gcd(A,B)}; return vec1; } 0 aakasshuit2 months ago static long GCD(Long A, Long B){ if(A==0){ return B; } return GCD(B%A,A); } static long LCM(Long A,Long B){ return (A*B)/GCD(A,B); } static Long[] lcmAndGcd(Long A , Long B) { // code here Long[] ans = new Long[2]; ans[0]= LCM(A,B); ans[1]= GCD(A,B); return ans; +1 asifsaba5812 months ago long long GCD(long long A,long long B){ if(B==0){ return A; } return GCD(B,A%B); } long long LCM(long long A,long long B){ long long res=A*B; return (res/GCD(A,B)); } vector<long long> lcmAndGcd(long long A , long long B) { vector<long long>ans; ans.push_back(LCM(A,B)); ans.push_back(GCD(A,B)); return ans; } +2 imohdalam2 months ago Java class Solution { static Long[] lcmAndGcd(Long A , Long B) { Long[] ans = new Long[2]; ans[1] = gcd(A, B); ans[0] = lcm(A, B, ans[1]); return ans; } static long lcm(long A, long B, long gcd){ return A*B/gcd; } static long gcd(long A, long B){ if(A == 0) return B; if(B == 0) return A; if( A == B) return A; if(A > B) return gcd(A-B, B); return gcd(A, B-A); } }; 0 u6twqtxu7rv0cxwmqxqnrtghetxkoua4ogrydvxe2 months ago For c++ class Solution { public: long long gcd(long long a,long long b){ if(a==0){ return b; } else if(b==0){ return a; } if (a>b){ return gcd(a%b,b); }else{ return gcd(a,b%a); } } vector<long long> lcmAndGcd(long long A , long long B) { vector<long long> vector2 = {(A*B)/gcd(A,B),gcd(A,B)}; return vector2; // code here } }; 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": 308, "s": 238, "text": "Given two numbers A and B. The task is to find out their LCM and GCD." }, { "code": null, "e": 321, "s": 310, "text": "Example 1:" }, { "code": null, "e": 414, "s": 321, "text": "Input:\nA = 5 , B = 10\nOutput:\n10 5\nExplanation:\nLCM of 5 and 10 is 10, while\nthier GCD is 5." }, { "code": null, "e": 425, "s": 414, "text": "Example 1:" }, { "code": null, "e": 518, "s": 425, "text": "Input:\nA = 14 , B = 8\nOutput:\n56 2\nExplanation:\nLCM of 14 and 8 is 56, while\nthier GCD is 2." }, { "code": null, "e": 725, "s": 520, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function lcmAndGcd() which takes an Integer N as input and returns a List of two Integers, the required LCM and GCD." }, { "code": null, "e": 801, "s": 727, "text": "Expected Time Complexity: O(log(min(A, B))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 833, "s": 803, "text": "Constraints:\n1 <= A,B <= 1018" }, { "code": null, "e": 835, "s": 833, "text": "0" }, { "code": null, "e": 861, "s": 835, "text": "mayank180919991 month ago" }, { "code": null, "e": 1074, "s": 861, "text": " vector<long long> lcmAndGcd(long long A , long long B) {\n // code here\n vector<long long>v;\n int a=__gcd(A,B);\n v.push_back((A*B)/a);\n v.push_back(a);\n return v; \n }" }, { "code": null, "e": 1076, "s": 1074, "text": "0" }, { "code": null, "e": 1106, "s": 1076, "text": "himanshulanjewar241 month ago" }, { "code": null, "e": 1122, "s": 1106, "text": "class Solution:" }, { "code": null, "e": 1148, "s": 1122, "text": " def gcd(self, a, b):" }, { "code": null, "e": 1173, "s": 1148, "text": " mini min(a,b) " }, { "code": null, "e": 1204, "s": 1173, "text": " rem = max(a, b)%mini" }, { "code": null, "e": 1227, "s": 1204, "text": " if rem == 0:" }, { "code": null, "e": 1254, "s": 1227, "text": " return mini" }, { "code": null, "e": 1270, "s": 1254, "text": " else:" }, { "code": null, "e": 1311, "s": 1270, "text": " return self.gcd(rem,mini)" }, { "code": null, "e": 1345, "s": 1313, "text": " def 1cmAndGcd(self, A, B):" }, { "code": null, "e": 1366, "s": 1345, "text": " #code here" }, { "code": null, "e": 1384, "s": 1366, "text": " l = [ ]" }, { "code": null, "e": 1425, "s": 1384, "text": " l.append((A*B)//self.gcd(A,B))" }, { "code": null, "e": 1459, "s": 1425, "text": " l.append(self.gcd(A,B))" }, { "code": null, "e": 1478, "s": 1459, "text": " return l" }, { "code": null, "e": 1480, "s": 1478, "text": "0" }, { "code": null, "e": 1500, "s": 1480, "text": "soham0071 month ago" }, { "code": null, "e": 1852, "s": 1500, "text": " long long gcd(int a,int b){\n return b==0?a:gcd(b,a%b);\n }\n vector<long long> lcmAndGcd(long long A , long long B) {\n // code here\n vector<long long>arr;\n long long st = gcd(A,B);\n \n \n long long st1 = (A*B)/st;\n \n arr.push_back(st1);\n arr.push_back(st);\n return arr;\n }" }, { "code": null, "e": 1854, "s": 1852, "text": "0" }, { "code": null, "e": 1882, "s": 1854, "text": "sharmarahul996111 month ago" }, { "code": null, "e": 2129, "s": 1882, "text": " long long C=A; long long D=B; while(A!=B){ if(A>B){ A=A-B; }if(B>A){ B=B-A; } } long long gcd = A; long long lcm = (C*D)/gcd; return {lcm , gcd};" }, { "code": null, "e": 2132, "s": 2129, "text": "+1" }, { "code": null, "e": 2156, "s": 2132, "text": "itsmeshahid2 months ago" }, { "code": null, "e": 2521, "s": 2156, "text": "vector<long long> lcmAndGcd(long long A , long long B) { long long gcd=1; long long maxi=max(A,B); long long mini=min(A,B); while(maxi%mini!=0){ long long rem=maxi%mini; maxi=mini; mini=rem; } gcd=mini; long long lcm=A*B/gcd; return {lcm, gcd}; }" }, { "code": null, "e": 2524, "s": 2521, "text": "+1" }, { "code": null, "e": 2552, "s": 2524, "text": "anuraggulati2412 months ago" }, { "code": null, "e": 2754, "s": 2552, "text": "c++ optamized solution do not make recursive calls in this gcd function because space complexity is increase and in iterative sapace is constant and time is linear .. so no need for recursive call ...." }, { "code": null, "e": 3289, "s": 2758, "text": "long long gcd(long long int a , long long int b) {\n \n if(a==b) {\n return b;\n }\n \n if(a%b == 0) {\n return b;\n }\n if(b%a == 0) {\n return a;\n }\n while(a != b) {\n if(a>b) {\n a = a-b;\n }\n else {\n b = b - a;\n }\n }\n return b; \n }\n vector<long long> lcmAndGcd(long long A , long long B) {\n // code here\n vector<long long> vec1 = {(A*B)/gcd(A,B) , gcd(A,B)};\n return vec1;\n }" }, { "code": null, "e": 3293, "s": 3291, "text": "0" }, { "code": null, "e": 3316, "s": 3293, "text": "aakasshuit2 months ago" }, { "code": null, "e": 3680, "s": 3316, "text": " static long GCD(Long A, Long B){\n if(A==0){\n return B;\n }\n return GCD(B%A,A);\n }\n static long LCM(Long A,Long B){\n return (A*B)/GCD(A,B);\n }\n static Long[] lcmAndGcd(Long A , Long B) {\n // code here\n Long[] ans = new Long[2];\n ans[0]= LCM(A,B);\n ans[1]= GCD(A,B);\n return ans;" }, { "code": null, "e": 3683, "s": 3680, "text": "+1" }, { "code": null, "e": 3707, "s": 3683, "text": "asifsaba5812 months ago" }, { "code": null, "e": 4193, "s": 3707, "text": " long long GCD(long long A,long long B){\n \n \n if(B==0){\n \n return A;\n }\n return GCD(B,A%B);\n }\n \n long long LCM(long long A,long long B){\n \n long long res=A*B;\n \n return (res/GCD(A,B));\n }\n \n vector<long long> lcmAndGcd(long long A , long long B) {\n \n vector<long long>ans;\n \n ans.push_back(LCM(A,B));\n \n ans.push_back(GCD(A,B));\n \n return ans;\n \n }" }, { "code": null, "e": 4196, "s": 4193, "text": "+2" }, { "code": null, "e": 4218, "s": 4196, "text": "imohdalam2 months ago" }, { "code": null, "e": 4223, "s": 4218, "text": "Java" }, { "code": null, "e": 4800, "s": 4223, "text": "class Solution {\n static Long[] lcmAndGcd(Long A , Long B) {\n Long[] ans = new Long[2];\n \n ans[1] = gcd(A, B);\n ans[0] = lcm(A, B, ans[1]);\n \n return ans;\n }\n \n static long lcm(long A, long B, long gcd){\n return A*B/gcd;\n }\n \n static long gcd(long A, long B){\n\n if(A == 0)\n return B;\n \n if(B == 0)\n return A;\n \n if( A == B)\n return A;\n \n if(A > B)\n return gcd(A-B, B);\n \n return gcd(A, B-A);\n }\n};" }, { "code": null, "e": 4802, "s": 4800, "text": "0" }, { "code": null, "e": 4855, "s": 4802, "text": "u6twqtxu7rv0cxwmqxqnrtghetxkoua4ogrydvxe2 months ago" }, { "code": null, "e": 4863, "s": 4855, "text": "For c++" }, { "code": null, "e": 5339, "s": 4863, "text": "class Solution {\n public: long long gcd(long long a,long long b){\n if(a==0){\n return b;\n } else if(b==0){\n return a;\n \n }\n if (a>b){\n return gcd(a%b,b);\n }else{\n return gcd(a,b%a);\n }\n }\n vector<long long> lcmAndGcd(long long A , long long B) {\n \n vector<long long> vector2 = {(A*B)/gcd(A,B),gcd(A,B)};\n return vector2;\n // code here\n }\n};" }, { "code": null, "e": 5485, "s": 5339, "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": 5521, "s": 5485, "text": " Login to access your submissions. " }, { "code": null, "e": 5531, "s": 5521, "text": "\nProblem\n" }, { "code": null, "e": 5541, "s": 5531, "text": "\nContest\n" }, { "code": null, "e": 5604, "s": 5541, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5752, "s": 5604, "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": 5960, "s": 5752, "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": 6066, "s": 5960, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Create Sliding Text Reveal Animation using HTML & CSS ? - GeeksforGeeks
18 Aug, 2021 In this article, we will implement sliding text reveal animation which can be used in personal portfolios, websites, and even in YouTube introduction videos to add an extra edge to our videos so that it looks more interesting and eye-catchy at first instance and the best part is that we will do that using just HTML and CSS. Approach: The animation will begin with the appearance of the first text, for example, we are taking the word as “GEEKSFORGEEKS”, and then it will slide towards the left, and our second text that is: “A Computer Science Portal For Geeks” will reveal towards the right (If you’re still confused, what the animation is all about, you can quickly scroll to the end of the page and see the output, for better understanding). We will be using different keyframes to divide our animation into different stages so that it works smoothly. Keyframes hold what styles the element will have at certain times. The following keyframes are used: @keyframes appear: In this keyframe, we will deal with the way the first text appears. @keyframes slide: In this keyframe, we will try to move the text in a sliding manner. @keyframes reveal: In this keyframe, we will reveal our second text. Below is the implementation of the above approach. Example: In this example, we will be going to use the above-defined properties to create the animation. index.html <!DOCTYPE html><html> <head> <title>Text Reveal Animation</title> </head> <style> @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap'); body{ font-family: Montserrat; text-align: center; color: #006600; font-size: 34px; padding-top: 40vh; overflow: hidden; } div{ display: inline-block; overflow: hidden; white-space: nowrap; } div:first-of-type{ animation: appear 6s infinite; } div:last-of-type{ animation: reveal 6s infinite; } div:last-of-type span{ font-size: 33px; color: #808000; animation: slide 6s infinite; } @keyframes appear{ 0%{opacity: 0;} 20%{opacity: 1;} 80%{opacity: 1;} 100%{opacity: 0;} } @keyframes slide{ 0%{margin-left:-800px;} 20%{margin-left:-800px;} 35%{margin-left:0px;} 100%{margin-left:0px;} } @keyframes reveal{ 0%{opacity: 0; width: 0px;} 20%{opacity: 1; width: 0px;} 30%{width: 655px;} 80%{opacity: 1;} 100%{opacity: 0; width: 655px;} } </style> <body> <div>GEEKSFORGEEKS</div> <div> <span>A Computer Science Portal For Geeks</span> </div> </body></html> Output: Note: For other texts of different lengths the width and the font size of both the text should be changed accordingly. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26647, "s": 26619, "text": "\n18 Aug, 2021" }, { "code": null, "e": 26973, "s": 26647, "text": "In this article, we will implement sliding text reveal animation which can be used in personal portfolios, websites, and even in YouTube introduction videos to add an extra edge to our videos so that it looks more interesting and eye-catchy at first instance and the best part is that we will do that using just HTML and CSS." }, { "code": null, "e": 27395, "s": 26973, "text": "Approach: The animation will begin with the appearance of the first text, for example, we are taking the word as “GEEKSFORGEEKS”, and then it will slide towards the left, and our second text that is: “A Computer Science Portal For Geeks” will reveal towards the right (If you’re still confused, what the animation is all about, you can quickly scroll to the end of the page and see the output, for better understanding). " }, { "code": null, "e": 27606, "s": 27395, "text": "We will be using different keyframes to divide our animation into different stages so that it works smoothly. Keyframes hold what styles the element will have at certain times. The following keyframes are used:" }, { "code": null, "e": 27693, "s": 27606, "text": "@keyframes appear: In this keyframe, we will deal with the way the first text appears." }, { "code": null, "e": 27779, "s": 27693, "text": "@keyframes slide: In this keyframe, we will try to move the text in a sliding manner." }, { "code": null, "e": 27848, "s": 27779, "text": "@keyframes reveal: In this keyframe, we will reveal our second text." }, { "code": null, "e": 27899, "s": 27848, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 28003, "s": 27899, "text": "Example: In this example, we will be going to use the above-defined properties to create the animation." }, { "code": null, "e": 28014, "s": 28003, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <head> <title>Text Reveal Animation</title> </head> <style> @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap'); body{ font-family: Montserrat; text-align: center; color: #006600; font-size: 34px; padding-top: 40vh; overflow: hidden; } div{ display: inline-block; overflow: hidden; white-space: nowrap; } div:first-of-type{ animation: appear 6s infinite; } div:last-of-type{ animation: reveal 6s infinite; } div:last-of-type span{ font-size: 33px; color: #808000; animation: slide 6s infinite; } @keyframes appear{ 0%{opacity: 0;} 20%{opacity: 1;} 80%{opacity: 1;} 100%{opacity: 0;} } @keyframes slide{ 0%{margin-left:-800px;} 20%{margin-left:-800px;} 35%{margin-left:0px;} 100%{margin-left:0px;} } @keyframes reveal{ 0%{opacity: 0; width: 0px;} 20%{opacity: 1; width: 0px;} 30%{width: 655px;} 80%{opacity: 1;} 100%{opacity: 0; width: 655px;} } </style> <body> <div>GEEKSFORGEEKS</div> <div> <span>A Computer Science Portal For Geeks</span> </div> </body></html>", "e": 29350, "s": 28014, "text": null }, { "code": null, "e": 29358, "s": 29350, "text": "Output:" }, { "code": null, "e": 29477, "s": 29358, "text": "Note: For other texts of different lengths the width and the font size of both the text should be changed accordingly." }, { "code": null, "e": 29614, "s": 29477, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29629, "s": 29614, "text": "CSS-Properties" }, { "code": null, "e": 29643, "s": 29629, "text": "CSS-Questions" }, { "code": null, "e": 29647, "s": 29643, "text": "CSS" }, { "code": null, "e": 29652, "s": 29647, "text": "HTML" }, { "code": null, "e": 29669, "s": 29652, "text": "Web Technologies" }, { "code": null, "e": 29674, "s": 29669, "text": "HTML" }, { "code": null, "e": 29772, "s": 29674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29809, "s": 29772, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29848, "s": 29809, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29877, "s": 29848, "text": "Form validation using jQuery" }, { "code": null, "e": 29919, "s": 29877, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29954, "s": 29919, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 30014, "s": 29954, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30067, "s": 30014, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30128, "s": 30067, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30152, "s": 30128, "text": "REST API (Introduction)" } ]
Python List Comprehension and Slicing - GeeksforGeeks
21 Jan, 2022 List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence andAn optional predicate part. Output expression, Input sequence, A variable representing a member of the input sequence and An optional predicate part. For example : lst = [x ** 2 for x in range (1, 11) if x % 2 == 1] here, x ** 2 is output expression, range (1, 11) is input sequence, x is variable and if x % 2 == 1 is predicate part. Example 1: Python3 # Python program to demonstrate list comprehension in Python # below list contains square of all odd numbers from # range 1 to 10 odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1] print (odd_square) # for understanding, above generation is same as, odd_square = [] for x in range(1, 11): if x % 2 == 1: odd_square.append(x**2) print (odd_square) # below list contains power of 2 from 1 to 8 power_of_2 = [2 ** x for x in range(1, 9)] print (power_of_2) # below list contains prime and non-prime in range 1 to 50 noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes] print (primes) # list for lowering the characters print ([x.lower() for x in ["A","B","C"]] ) # list which extracts number string = "my phone number is : 11122 !!" print("\nExtracted digits") numbers = [x for x in string if x.isdigit()] print (numbers) # A list of list for multiplication table a = 5table = [[a, b, a * b] for b in range(1, 11)] print("\nMultiplication Table") for i in table: print (i) Output: [1, 9, 25, 49, 81] [1, 9, 25, 49, 81] [2, 4, 8, 16, 32, 64, 128, 256] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] ['a', 'b', 'c'] Extracted digits ['1', '1', '1', '2', '2'] Multiplication Table [5, 1, 5] [5, 2, 10] [5, 3, 15] [5, 4, 20] [5, 5, 25] [5, 6, 30] [5, 7, 35] [5, 8, 40] [5, 9, 45] [5, 10, 50] After getting the list, we can get a part of it using python’s slicing operator which has the following syntax: [start : stop : steps] which means that slicing will start from index start will go up to stop in step of steps. Default value of start is 0, stop is last index of list and for step it is 1 So [: stop] will slice list from starting till stop index and [start : ] will slice list from start index till end Negative value of steps shows right to left traversal instead of left to right traversal that is why [: : -1] prints list in reverse order. Example 2: Python3 # Let us first create a list to demonstrate slicing# lst contains all number from 1 to 10lst =list(range(1, 11))print (lst) # below list has numbers from 2 to 5lst1_5 = lst[1 : 5]print (lst1_5) # below list has numbers from 6 to 8lst5_8 = lst[5 : 8]print (lst5_8) # below list has numbers from 2 to 10lst1_ = lst[1 : ]print (lst1_) # below list has numbers from 1 to 5lst_5 = lst[: 5]print (lst_5) # below list has numbers from 2 to 8 in step 2lst1_8_2 = lst[1 : 8 : 2]print (lst1_8_2) # below list has numbers from 10 to 1lst_rev = lst[ : : -1]print (lst_rev) # below list has numbers from 10 to 6 in step 2lst_rev_9_5_2 = lst[9 : 4 : -2]print (lst_rev_9_5_2) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 3, 4, 5] [6, 7, 8] [2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 2, 3, 4, 5] [2, 4, 6, 8] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [10, 8, 6] We can use the filter function to filter a list based on some condition provided as a lambda expression as the first argument and list as the second argument, an example of which is shown below : Example 3: Python3 import functools # filtering odd numberslst = filter(lambda x : x % 2 == 1, range(1, 20))print (list(lst)) # filtering odd square which are divisible by 5lst = filter(lambda x : x % 5 == 0, [x ** 2 for x in range(1, 11) if x % 2 == 1])print (list(lst)) # filtering negative numberslst = filter((lambda x: x < 0), range(-5,5))print (list(lst)) # implementing max() function, usingprint (functools.reduce(lambda a,b: a if (a > b) else b, [7, 12, 45, 100, 15])) Output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] [25] [-5, -4, -3, -2, -1] 100 YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial - Slicing and Splitting | 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:12•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=i5WNg3UOkQk" 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 Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ManasChhabra2 ramalaiguhan punamsingh628700 amartyaghoshgfg python-list python-list-functions Python School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 25471, "s": 25443, "text": "\n21 Jan, 2022" }, { "code": null, "e": 25677, "s": 25471, "text": "List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. " }, { "code": null, "e": 25735, "s": 25677, "text": "A list comprehension generally consists of these parts : " }, { "code": null, "e": 25854, "s": 25735, "text": "Output expression,Input sequence,A variable representing a member of the input sequence andAn optional predicate part." }, { "code": null, "e": 25873, "s": 25854, "text": "Output expression," }, { "code": null, "e": 25889, "s": 25873, "text": "Input sequence," }, { "code": null, "e": 25948, "s": 25889, "text": "A variable representing a member of the input sequence and" }, { "code": null, "e": 25976, "s": 25948, "text": "An optional predicate part." }, { "code": null, "e": 26194, "s": 25976, "text": "For example :\n\nlst = [x ** 2 for x in range (1, 11) if x % 2 == 1] \n\nhere, x ** 2 is output expression, \n range (1, 11) is input sequence, \n x is variable and \n if x % 2 == 1 is predicate part." }, { "code": null, "e": 26206, "s": 26194, "text": "Example 1: " }, { "code": null, "e": 26214, "s": 26206, "text": "Python3" }, { "code": "# Python program to demonstrate list comprehension in Python # below list contains square of all odd numbers from # range 1 to 10 odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1] print (odd_square) # for understanding, above generation is same as, odd_square = [] for x in range(1, 11): if x % 2 == 1: odd_square.append(x**2) print (odd_square) # below list contains power of 2 from 1 to 8 power_of_2 = [2 ** x for x in range(1, 9)] print (power_of_2) # below list contains prime and non-prime in range 1 to 50 noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes] print (primes) # list for lowering the characters print ([x.lower() for x in [\"A\",\"B\",\"C\"]] ) # list which extracts number string = \"my phone number is : 11122 !!\" print(\"\\nExtracted digits\") numbers = [x for x in string if x.isdigit()] print (numbers) # A list of list for multiplication table a = 5table = [[a, b, a * b] for b in range(1, 11)] print(\"\\nMultiplication Table\") for i in table: print (i)", "e": 27298, "s": 26214, "text": null }, { "code": null, "e": 27307, "s": 27298, "text": "Output: " }, { "code": null, "e": 27626, "s": 27307, "text": "[1, 9, 25, 49, 81]\n[1, 9, 25, 49, 81]\n[2, 4, 8, 16, 32, 64, 128, 256]\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]\n['a', 'b', 'c']\n\nExtracted digits\n['1', '1', '1', '2', '2']\n\nMultiplication Table\n[5, 1, 5]\n[5, 2, 10]\n[5, 3, 15]\n[5, 4, 20]\n[5, 5, 25]\n[5, 6, 30]\n[5, 7, 35]\n[5, 8, 40]\n[5, 9, 45]\n[5, 10, 50]" }, { "code": null, "e": 27739, "s": 27626, "text": "After getting the list, we can get a part of it using python’s slicing operator which has the following syntax: " }, { "code": null, "e": 27937, "s": 27739, "text": "[start : stop : steps] \n\nwhich means that slicing will start from index start\n will go up to stop in step of steps. \n Default value of start is 0, stop is last index of list\n and for step it is 1 " }, { "code": null, "e": 28192, "s": 27937, "text": "So [: stop] will slice list from starting till stop index and [start : ] will slice list from start index till end Negative value of steps shows right to left traversal instead of left to right traversal that is why [: : -1] prints list in reverse order." }, { "code": null, "e": 28204, "s": 28192, "text": "Example 2: " }, { "code": null, "e": 28212, "s": 28204, "text": "Python3" }, { "code": "# Let us first create a list to demonstrate slicing# lst contains all number from 1 to 10lst =list(range(1, 11))print (lst) # below list has numbers from 2 to 5lst1_5 = lst[1 : 5]print (lst1_5) # below list has numbers from 6 to 8lst5_8 = lst[5 : 8]print (lst5_8) # below list has numbers from 2 to 10lst1_ = lst[1 : ]print (lst1_) # below list has numbers from 1 to 5lst_5 = lst[: 5]print (lst_5) # below list has numbers from 2 to 8 in step 2lst1_8_2 = lst[1 : 8 : 2]print (lst1_8_2) # below list has numbers from 10 to 1lst_rev = lst[ : : -1]print (lst_rev) # below list has numbers from 10 to 6 in step 2lst_rev_9_5_2 = lst[9 : 4 : -2]print (lst_rev_9_5_2)", "e": 28901, "s": 28212, "text": null }, { "code": null, "e": 28910, "s": 28901, "text": "Output: " }, { "code": null, "e": 29066, "s": 28910, "text": "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n[2, 3, 4, 5]\n[6, 7, 8]\n[2, 3, 4, 5, 6, 7, 8, 9, 10]\n[1, 2, 3, 4, 5]\n[2, 4, 6, 8]\n[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n[10, 8, 6]" }, { "code": null, "e": 29262, "s": 29066, "text": "We can use the filter function to filter a list based on some condition provided as a lambda expression as the first argument and list as the second argument, an example of which is shown below :" }, { "code": null, "e": 29275, "s": 29262, "text": "Example 3: " }, { "code": null, "e": 29283, "s": 29275, "text": "Python3" }, { "code": "import functools # filtering odd numberslst = filter(lambda x : x % 2 == 1, range(1, 20))print (list(lst)) # filtering odd square which are divisible by 5lst = filter(lambda x : x % 5 == 0, [x ** 2 for x in range(1, 11) if x % 2 == 1])print (list(lst)) # filtering negative numberslst = filter((lambda x: x < 0), range(-5,5))print (list(lst)) # implementing max() function, usingprint (functools.reduce(lambda a,b: a if (a > b) else b, [7, 12, 45, 100, 15]))", "e": 29764, "s": 29283, "text": null }, { "code": null, "e": 29773, "s": 29764, "text": "Output: " }, { "code": null, "e": 29839, "s": 29773, "text": "[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\n[25]\n[-5, -4, -3, -2, -1]\n100" }, { "code": null, "e": 30689, "s": 29839, "text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial - Slicing and Splitting | 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:12•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=i5WNg3UOkQk\" 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": 30862, "s": 30689, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 30876, "s": 30862, "text": "ManasChhabra2" }, { "code": null, "e": 30889, "s": 30876, "text": "ramalaiguhan" }, { "code": null, "e": 30906, "s": 30889, "text": "punamsingh628700" }, { "code": null, "e": 30922, "s": 30906, "text": "amartyaghoshgfg" }, { "code": null, "e": 30934, "s": 30922, "text": "python-list" }, { "code": null, "e": 30956, "s": 30934, "text": "python-list-functions" }, { "code": null, "e": 30963, "s": 30956, "text": "Python" }, { "code": null, "e": 30982, "s": 30963, "text": "School Programming" }, { "code": null, "e": 30994, "s": 30982, "text": "python-list" }, { "code": null, "e": 31092, "s": 30994, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31124, "s": 31092, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31146, "s": 31124, "text": "Enumerate() in Python" }, { "code": null, "e": 31188, "s": 31146, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31214, "s": 31188, "text": "Python String | replace()" }, { "code": null, "e": 31243, "s": 31214, "text": "*args and **kwargs in Python" }, { "code": null, "e": 31259, "s": 31243, "text": "Arrays in C/C++" }, { "code": null, "e": 31278, "s": 31259, "text": "Inheritance in C++" }, { "code": null, "e": 31303, "s": 31278, "text": "Reverse a string in Java" }, { "code": null, "e": 31327, "s": 31303, "text": "C++ Classes and Objects" } ]
How to delete rows of R dataframe based on string match? - GeeksforGeeks
26 Apr, 2022 In this article, we will discuss how to delete rows of a dataframe based on string match in R Programming Language. For this grep() function can be used. This function searches for matches of certain character patterns in a vector of character strings and returns a boolean value as TRUE if that string is present else it returns FALSE. Syntax: grepl(pattern, string, ignore.case=FALSE) Parameter: pattern: regular expressions pattern string: character vector to be searched First with the help of grepl() we have obtained the rows which consist of specified substrings in it. Then with Not operator(!) we have removed those rows in our data frame and stored them in another data frame. Data frame in use: Data frame Example 1: R Strings<-c("Geeks","For","Geeks","GFG","Ram", "Ramesh","Gene","Siri")Id<-1:8 # df is our data frame namedf<-data.frame(Id,Strings) print(df) # Removes the rows in Data frame# which consist "Ra" in itnew_df=df[!grepl("Ra",df$Strings),]print(new_df) Output: Example 2: R Strings<-c("Geeks","For","Geeks","GFG","Ram", "Ramesh","Gene","Siri")Id<-1:8 # df is our data frame namedf<-data.frame(Id,Strings) print(df) # Removes the rows in Data frame# which consist "Ge" in itnew_df=df[!grepl("Ge",df$Strings),]print(new_df) Output: vitapanekrsj Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n26 Apr, 2022" }, { "code": null, "e": 26603, "s": 26487, "text": "In this article, we will discuss how to delete rows of a dataframe based on string match in R Programming Language." }, { "code": null, "e": 26824, "s": 26603, "text": "For this grep() function can be used. This function searches for matches of certain character patterns in a vector of character strings and returns a boolean value as TRUE if that string is present else it returns FALSE." }, { "code": null, "e": 26874, "s": 26824, "text": "Syntax: grepl(pattern, string, ignore.case=FALSE)" }, { "code": null, "e": 26885, "s": 26874, "text": "Parameter:" }, { "code": null, "e": 26922, "s": 26885, "text": "pattern: regular expressions pattern" }, { "code": null, "e": 26962, "s": 26922, "text": "string: character vector to be searched" }, { "code": null, "e": 27174, "s": 26962, "text": "First with the help of grepl() we have obtained the rows which consist of specified substrings in it. Then with Not operator(!) we have removed those rows in our data frame and stored them in another data frame." }, { "code": null, "e": 27193, "s": 27174, "text": "Data frame in use:" }, { "code": null, "e": 27204, "s": 27193, "text": "Data frame" }, { "code": null, "e": 27215, "s": 27204, "text": "Example 1:" }, { "code": null, "e": 27217, "s": 27215, "text": "R" }, { "code": "Strings<-c(\"Geeks\",\"For\",\"Geeks\",\"GFG\",\"Ram\", \"Ramesh\",\"Gene\",\"Siri\")Id<-1:8 # df is our data frame namedf<-data.frame(Id,Strings) print(df) # Removes the rows in Data frame# which consist \"Ra\" in itnew_df=df[!grepl(\"Ra\",df$Strings),]print(new_df)", "e": 27477, "s": 27217, "text": null }, { "code": null, "e": 27485, "s": 27477, "text": "Output:" }, { "code": null, "e": 27496, "s": 27485, "text": "Example 2:" }, { "code": null, "e": 27498, "s": 27496, "text": "R" }, { "code": "Strings<-c(\"Geeks\",\"For\",\"Geeks\",\"GFG\",\"Ram\", \"Ramesh\",\"Gene\",\"Siri\")Id<-1:8 # df is our data frame namedf<-data.frame(Id,Strings) print(df) # Removes the rows in Data frame# which consist \"Ge\" in itnew_df=df[!grepl(\"Ge\",df$Strings),]print(new_df)", "e": 27758, "s": 27498, "text": null }, { "code": null, "e": 27766, "s": 27758, "text": "Output:" }, { "code": null, "e": 27779, "s": 27766, "text": "vitapanekrsj" }, { "code": null, "e": 27786, "s": 27779, "text": "Picked" }, { "code": null, "e": 27807, "s": 27786, "text": "R DataFrame-Programs" }, { "code": null, "e": 27819, "s": 27807, "text": "R-DataFrame" }, { "code": null, "e": 27830, "s": 27819, "text": "R Language" }, { "code": null, "e": 27841, "s": 27830, "text": "R Programs" }, { "code": null, "e": 27939, "s": 27841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27991, "s": 27939, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28026, "s": 27991, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28064, "s": 28026, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28122, "s": 28064, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28165, "s": 28122, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28223, "s": 28165, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28266, "s": 28223, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28315, "s": 28266, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28365, "s": 28315, "text": "How to filter R dataframe by multiple conditions?" } ]
Vertical Sum in a given Binary Tree | Set 1 - GeeksforGeeks
14 Feb, 2022 Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line. Print all sums through different vertical lines.Examples: 1 / \ 2 3 / \ / \ 4 5 6 7 The tree has 5 vertical linesVertical-Line-1 has only one node 4 => vertical sum is 4 Vertical-Line-2: has only one node 2=> vertical sum is 2 Vertical-Line-3: has three nodes: 1,5,6 => vertical sum is 1+5+6 = 12 Vertical-Line-4: has only one node 3 => vertical sum is 3 Vertical-Line-5: has only one node 7 => vertical sum is 7So expected output is 4, 2, 12, 3 and 7 We need to check the Horizontal Distances from the root for all nodes. If two nodes have the same Horizontal Distance (HD), then they are on the same vertical line. The idea of HD is simple. HD for root is 0, a right edge (edge connecting to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1 horizontal distance. For example, in the above tree, HD for Node 4 is at -2, HD for Node 2 is -1, HD for 5 and 6 is 0 and HD for node 7 is +2. We can do an in-order traversal of the given Binary Tree. While traversing the tree, we can recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1.Following is Java implementation for the same. HashMap is used to store the vertical sums for different horizontal distances. Thanks to Nages for suggesting this method. C++ Java Python3 C# Javascript // C++ program to find Vertical Sum in// a given Binary Tree#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to create a new// Binary Tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Traverses the tree in in-order form and// populates a hashMap that contains the// vertical sumvoid verticalSumUtil(Node *node, int hd, map<int, int> &Map){ // Base case if (node == NULL) return; // Recur for left subtree verticalSumUtil(node->left, hd-1, Map); // Add val of current node to // map entry of corresponding hd Map[hd] += node->data; // Recur for right subtree verticalSumUtil(node->right, hd+1, Map);} // Function to find vertical sumvoid verticalSum(Node *root){ // a map to store sum of nodes for each // horizontal distance map < int, int> Map; map < int, int> :: iterator it; // populate the map verticalSumUtil(root, 0, Map); // Prints the values stored by VerticalSumUtil() for (it = Map.begin(); it != Map.end(); ++it) { cout << it->first << ": " << it->second << endl; }} // Driver program to test above functionsint main(){ // Create binary tree as shown in above figure Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); root->right->right->right = newNode(9); cout << "Following are the values of vertical" " sums with the positions of the " "columns with respect to root\n"; verticalSum(root); return 0;}// This code is contributed by Aditi Sharma import java.util.TreeMap; // Class for a tree nodeclass TreeNode { // data members private int key; private TreeNode left; private TreeNode right; // Accessor methods public int key() { return key; } public TreeNode left() { return left; } public TreeNode right() { return right; } // Constructor public TreeNode(int key) { this.key = key; left = null; right = null; } // Methods to set left and right subtrees public void setLeft(TreeNode left) { this.left = left; } public void setRight(TreeNode right) { this.right = right; }} // Class for a Binary Treeclass Tree { private TreeNode root; // Constructors public Tree() { root = null; } public Tree(TreeNode n) { root = n; } // Method to be called by the consumer classes // like Main class public void VerticalSumMain() { VerticalSum(root); } // A wrapper over VerticalSumUtil() private void VerticalSum(TreeNode root) { // base case if (root == null) { return; } // Creates an empty TreeMap hM TreeMap<Integer, Integer> hM = new TreeMap<Integer, Integer>(); // Calls the VerticalSumUtil() to store the // vertical sum values in hM VerticalSumUtil(root, 0, hM); // Prints the values stored by VerticalSumUtil() if (hM != null) { System.out.println(hM.entrySet()); } } // Traverses the tree in in-order form and builds // a hashMap hM that contains the vertical sum private void VerticalSumUtil(TreeNode root, int hD, TreeMap<Integer, Integer> hM) { // base case if (root == null) { return; } // Store the values in hM for left subtree VerticalSumUtil(root.left(), hD - 1, hM); // Update vertical sum for hD of this node int prevSum = (hM.get(hD) == null) ? 0 : hM.get(hD); hM.put(hD, prevSum + root.key()); // Store the values in hM for right subtree VerticalSumUtil(root.right(), hD + 1, hM); }} // Driver class to test the verticalSum methodspublic class Main { public static void main(String[] args) { /* Create the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 */ TreeNode root = new TreeNode(1); root.setLeft(new TreeNode(2)); root.setRight(new TreeNode(3)); root.left().setLeft(new TreeNode(4)); root.left().setRight(new TreeNode(5)); root.right().setLeft(new TreeNode(6)); root.right().setRight(new TreeNode(7)); Tree t = new Tree(root); System.out.println("Following are the values of" + " vertical sums with the positions" + " of the columns with respect to root "); t.VerticalSumMain(); }} # Python3 program to find Vertical Sum in# a given Binary Tree # Node definitionclass newNode: def __init__(self, data): self.left = None self.right = None self.data = data # Traverses the tree in in-order form and# populates a hashMap that contains the# vertical sumdef verticalSumUtil(root, hd, Map): # Base case if(root == None): return # Recur for left subtree verticalSumUtil(root.left, hd - 1, Map) # Add val of current node to # map entry of corresponding hd if(hd in Map.keys()): Map[hd] = Map[hd] + root.data else: Map[hd] = root.data # Recur for right subtree verticalSumUtil(root.right, hd + 1, Map) # Function to find vertical_sumdef verticalSum(root): # a dictionary to store sum of # nodes for each horizontal distance Map = {} # Populate the dictionary verticalSumUtil(root, 0, Map); # Prints the values stored # by VerticalSumUtil() for i,j in Map.items(): print(i, "=", j, end = ", ") # Driver Codeif __name__ == "__main__": ''' Create the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) print("Following are the values of vertical " "sums with the positions of the " "columns with respect to root") verticalSum(root) # This code is contributed by vipinyadav15799 // C# program to find Vertical Sum in// a given Binary Treeusing System;using System.Collections.Generic; // Class for a tree nodeclass TreeNode{ // data members public int key; public TreeNode left; public TreeNode right; // Accessor methods public int Key() { return key; } public TreeNode Left() { return left; } public TreeNode Right() { return right; } // Constructor public TreeNode(int key) { this.key = key; left = null; right = null; } // Methods to set left and right subtrees public void setLeft(TreeNode left) { this.left = left; } public void setRight(TreeNode right) { this.right = right; }} // Class for a Binary Treeclass Tree{ private TreeNode root; // Constructors public Tree() { root = null; } public Tree(TreeNode n) { root = n; } // Method to be called by the consumer classes // like Main class public void VerticalSumMain() { VerticalSum(root); } // A wrapper over VerticalSumUtil() private void VerticalSum(TreeNode root) { // base case if (root == null) { return; } // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); // Calls the VerticalSumUtil() to store the // vertical sum values in hM VerticalSumUtil(root, 0, hM); // Prints the values stored by VerticalSumUtil() if (hM != null) { Console.Write("["); foreach(KeyValuePair<int, int> entry in hM) { Console.Write(entry.Key + " = " + entry.Value + ", "); } Console.Write("]"); } } // Traverses the tree in in-order form and builds // a hashMap hM that contains the vertical sum private void VerticalSumUtil(TreeNode root, int hD, Dictionary<int, int> hM) { // base case if (root == null) { return; } // Store the values in hM for left subtree VerticalSumUtil(root.Left(), hD - 1, hM); // Update vertical sum for hD of this node int prevSum = 0; if(hM.ContainsKey(hD)) { prevSum = hM[hD]; hM[hD] = prevSum + root.Key(); } else hM.Add(hD, prevSum + root.Key()); // Store the values in hM for right subtree VerticalSumUtil(root.Right(), hD + 1, hM); }} // Driver Codepublic class GFG{ public static void Main(String[] args) { /* Create the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 */ TreeNode root = new TreeNode(1); root.setLeft(new TreeNode(2)); root.setRight(new TreeNode(3)); root.Left().setLeft(new TreeNode(4)); root.Left().setRight(new TreeNode(5)); root.Right().setLeft(new TreeNode(6)); root.Right().setRight(new TreeNode(7)); Tree t = new Tree(root); Console.WriteLine("Following are the values of" + " vertical sums with the positions" + " of the columns with respect to root "); t.VerticalSumMain(); }} // This code is contributed by Rajput-Ji <script>// JavaScript program to find Vertical Sum in// a given Binary Tree // Node definitionclass newNode{ constructor(data){ this.left = null this.right = null this.data = data } } // Traverses the tree in in-order form and// populates a hashMap that contains the// vertical sumfunction verticalSumUtil(root, hd, map){ // Base case if(root == null) return; // Recur for left subtree verticalSumUtil(root.left, hd - 1, map) // Add val of current node to// map entry of corresponding hd if(map.has(hd) == true) map.set(hd , map.get(hd) + root.data) else map.set(hd , root.data) // Recur for right subtree verticalSumUtil(root.right, hd + 1, map) } // Function to find vertical_sumfunction verticalSum(root){ // a dictionary to store sum of// nodes for each horizontal distance let map = new Map() // Populate the dictionary verticalSumUtil(root, 0, map); // Prints the values stored// by VerticalSumUtil() for(const [i,j] of map.entries()) document.write(i + ": " + j) } // Driver Code // Create the following Binary Tree // 1 // / \ // 2 3 /// \ / \ // 4 5 6 7 root = new newNode(1) root.left = new newNode(2) root.right = new newNode(3) root.left.left = new newNode(4) root.left.right = new newNode(5) root.right.left = new newNode(6) root.right.right = new newNode(7) root.right.left.right = new newNode(8); root.right.right.right = new newNode(9); document.write("Following are the values of vertical sums with the positions of the columns with respect to root") verticalSum(root) // This code is contributed by shinjanpatra</script> Following are the values of vertical sums with the positions of the columns with respect to root -2: 4 -1: 2 0: 12 1: 11 2: 7 3: 9 Vertical Sum in Binary Tree | Set 2 (Space Optimized)Time Complexity: O(nlogn)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Shivam.Pradhan Rajput-Ji vipinyadav15799 maulikgandhi9 kalrap615 shinjanpatra Amazon Hash Tree Amazon Hash Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 37093, "s": 37065, "text": "\n14 Feb, 2022" }, { "code": null, "e": 37245, "s": 37093, "text": "Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line. Print all sums through different vertical lines.Examples: " }, { "code": null, "e": 37299, "s": 37245, "text": " 1\n / \\\n 2 3\n / \\ / \\\n4 5 6 7" }, { "code": null, "e": 37669, "s": 37299, "text": "The tree has 5 vertical linesVertical-Line-1 has only one node 4 => vertical sum is 4 Vertical-Line-2: has only one node 2=> vertical sum is 2 Vertical-Line-3: has three nodes: 1,5,6 => vertical sum is 1+5+6 = 12 Vertical-Line-4: has only one node 3 => vertical sum is 3 Vertical-Line-5: has only one node 7 => vertical sum is 7So expected output is 4, 2, 12, 3 and 7 " }, { "code": null, "e": 38672, "s": 37669, "text": "We need to check the Horizontal Distances from the root for all nodes. If two nodes have the same Horizontal Distance (HD), then they are on the same vertical line. The idea of HD is simple. HD for root is 0, a right edge (edge connecting to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1 horizontal distance. For example, in the above tree, HD for Node 4 is at -2, HD for Node 2 is -1, HD for 5 and 6 is 0 and HD for node 7 is +2. We can do an in-order traversal of the given Binary Tree. While traversing the tree, we can recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1.Following is Java implementation for the same. HashMap is used to store the vertical sums for different horizontal distances. Thanks to Nages for suggesting this method. " }, { "code": null, "e": 38676, "s": 38672, "text": "C++" }, { "code": null, "e": 38681, "s": 38676, "text": "Java" }, { "code": null, "e": 38689, "s": 38681, "text": "Python3" }, { "code": null, "e": 38692, "s": 38689, "text": "C#" }, { "code": null, "e": 38703, "s": 38692, "text": "Javascript" }, { "code": "// C++ program to find Vertical Sum in// a given Binary Tree#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to create a new// Binary Tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Traverses the tree in in-order form and// populates a hashMap that contains the// vertical sumvoid verticalSumUtil(Node *node, int hd, map<int, int> &Map){ // Base case if (node == NULL) return; // Recur for left subtree verticalSumUtil(node->left, hd-1, Map); // Add val of current node to // map entry of corresponding hd Map[hd] += node->data; // Recur for right subtree verticalSumUtil(node->right, hd+1, Map);} // Function to find vertical sumvoid verticalSum(Node *root){ // a map to store sum of nodes for each // horizontal distance map < int, int> Map; map < int, int> :: iterator it; // populate the map verticalSumUtil(root, 0, Map); // Prints the values stored by VerticalSumUtil() for (it = Map.begin(); it != Map.end(); ++it) { cout << it->first << \": \" << it->second << endl; }} // Driver program to test above functionsint main(){ // Create binary tree as shown in above figure Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); root->right->right->right = newNode(9); cout << \"Following are the values of vertical\" \" sums with the positions of the \" \"columns with respect to root\\n\"; verticalSum(root); return 0;}// This code is contributed by Aditi Sharma", "e": 40580, "s": 38703, "text": null }, { "code": "import java.util.TreeMap; // Class for a tree nodeclass TreeNode { // data members private int key; private TreeNode left; private TreeNode right; // Accessor methods public int key() { return key; } public TreeNode left() { return left; } public TreeNode right() { return right; } // Constructor public TreeNode(int key) { this.key = key; left = null; right = null; } // Methods to set left and right subtrees public void setLeft(TreeNode left) { this.left = left; } public void setRight(TreeNode right) { this.right = right; }} // Class for a Binary Treeclass Tree { private TreeNode root; // Constructors public Tree() { root = null; } public Tree(TreeNode n) { root = n; } // Method to be called by the consumer classes // like Main class public void VerticalSumMain() { VerticalSum(root); } // A wrapper over VerticalSumUtil() private void VerticalSum(TreeNode root) { // base case if (root == null) { return; } // Creates an empty TreeMap hM TreeMap<Integer, Integer> hM = new TreeMap<Integer, Integer>(); // Calls the VerticalSumUtil() to store the // vertical sum values in hM VerticalSumUtil(root, 0, hM); // Prints the values stored by VerticalSumUtil() if (hM != null) { System.out.println(hM.entrySet()); } } // Traverses the tree in in-order form and builds // a hashMap hM that contains the vertical sum private void VerticalSumUtil(TreeNode root, int hD, TreeMap<Integer, Integer> hM) { // base case if (root == null) { return; } // Store the values in hM for left subtree VerticalSumUtil(root.left(), hD - 1, hM); // Update vertical sum for hD of this node int prevSum = (hM.get(hD) == null) ? 0 : hM.get(hD); hM.put(hD, prevSum + root.key()); // Store the values in hM for right subtree VerticalSumUtil(root.right(), hD + 1, hM); }} // Driver class to test the verticalSum methodspublic class Main { public static void main(String[] args) { /* Create the following Binary Tree 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ TreeNode root = new TreeNode(1); root.setLeft(new TreeNode(2)); root.setRight(new TreeNode(3)); root.left().setLeft(new TreeNode(4)); root.left().setRight(new TreeNode(5)); root.right().setLeft(new TreeNode(6)); root.right().setRight(new TreeNode(7)); Tree t = new Tree(root); System.out.println(\"Following are the values of\" + \" vertical sums with the positions\" + \" of the columns with respect to root \"); t.VerticalSumMain(); }}", "e": 43467, "s": 40580, "text": null }, { "code": "# Python3 program to find Vertical Sum in# a given Binary Tree # Node definitionclass newNode: def __init__(self, data): self.left = None self.right = None self.data = data # Traverses the tree in in-order form and# populates a hashMap that contains the# vertical sumdef verticalSumUtil(root, hd, Map): # Base case if(root == None): return # Recur for left subtree verticalSumUtil(root.left, hd - 1, Map) # Add val of current node to # map entry of corresponding hd if(hd in Map.keys()): Map[hd] = Map[hd] + root.data else: Map[hd] = root.data # Recur for right subtree verticalSumUtil(root.right, hd + 1, Map) # Function to find vertical_sumdef verticalSum(root): # a dictionary to store sum of # nodes for each horizontal distance Map = {} # Populate the dictionary verticalSumUtil(root, 0, Map); # Prints the values stored # by VerticalSumUtil() for i,j in Map.items(): print(i, \"=\", j, end = \", \") # Driver Codeif __name__ == \"__main__\": ''' Create the following Binary Tree 1 / \\ 2 3 / \\ / \\ 4 5 6 7 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) print(\"Following are the values of vertical \" \"sums with the positions of the \" \"columns with respect to root\") verticalSum(root) # This code is contributed by vipinyadav15799", "e": 45137, "s": 43467, "text": null }, { "code": "// C# program to find Vertical Sum in// a given Binary Treeusing System;using System.Collections.Generic; // Class for a tree nodeclass TreeNode{ // data members public int key; public TreeNode left; public TreeNode right; // Accessor methods public int Key() { return key; } public TreeNode Left() { return left; } public TreeNode Right() { return right; } // Constructor public TreeNode(int key) { this.key = key; left = null; right = null; } // Methods to set left and right subtrees public void setLeft(TreeNode left) { this.left = left; } public void setRight(TreeNode right) { this.right = right; }} // Class for a Binary Treeclass Tree{ private TreeNode root; // Constructors public Tree() { root = null; } public Tree(TreeNode n) { root = n; } // Method to be called by the consumer classes // like Main class public void VerticalSumMain() { VerticalSum(root); } // A wrapper over VerticalSumUtil() private void VerticalSum(TreeNode root) { // base case if (root == null) { return; } // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); // Calls the VerticalSumUtil() to store the // vertical sum values in hM VerticalSumUtil(root, 0, hM); // Prints the values stored by VerticalSumUtil() if (hM != null) { Console.Write(\"[\"); foreach(KeyValuePair<int, int> entry in hM) { Console.Write(entry.Key + \" = \" + entry.Value + \", \"); } Console.Write(\"]\"); } } // Traverses the tree in in-order form and builds // a hashMap hM that contains the vertical sum private void VerticalSumUtil(TreeNode root, int hD, Dictionary<int, int> hM) { // base case if (root == null) { return; } // Store the values in hM for left subtree VerticalSumUtil(root.Left(), hD - 1, hM); // Update vertical sum for hD of this node int prevSum = 0; if(hM.ContainsKey(hD)) { prevSum = hM[hD]; hM[hD] = prevSum + root.Key(); } else hM.Add(hD, prevSum + root.Key()); // Store the values in hM for right subtree VerticalSumUtil(root.Right(), hD + 1, hM); }} // Driver Codepublic class GFG{ public static void Main(String[] args) { /* Create the following Binary Tree 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ TreeNode root = new TreeNode(1); root.setLeft(new TreeNode(2)); root.setRight(new TreeNode(3)); root.Left().setLeft(new TreeNode(4)); root.Left().setRight(new TreeNode(5)); root.Right().setLeft(new TreeNode(6)); root.Right().setRight(new TreeNode(7)); Tree t = new Tree(root); Console.WriteLine(\"Following are the values of\" + \" vertical sums with the positions\" + \" of the columns with respect to root \"); t.VerticalSumMain(); }} // This code is contributed by Rajput-Ji", "e": 48474, "s": 45137, "text": null }, { "code": "<script>// JavaScript program to find Vertical Sum in// a given Binary Tree // Node definitionclass newNode{ constructor(data){ this.left = null this.right = null this.data = data } } // Traverses the tree in in-order form and// populates a hashMap that contains the// vertical sumfunction verticalSumUtil(root, hd, map){ // Base case if(root == null) return; // Recur for left subtree verticalSumUtil(root.left, hd - 1, map) // Add val of current node to// map entry of corresponding hd if(map.has(hd) == true) map.set(hd , map.get(hd) + root.data) else map.set(hd , root.data) // Recur for right subtree verticalSumUtil(root.right, hd + 1, map) } // Function to find vertical_sumfunction verticalSum(root){ // a dictionary to store sum of// nodes for each horizontal distance let map = new Map() // Populate the dictionary verticalSumUtil(root, 0, map); // Prints the values stored// by VerticalSumUtil() for(const [i,j] of map.entries()) document.write(i + \": \" + j) } // Driver Code // Create the following Binary Tree // 1 // / \\ // 2 3 /// \\ / \\ // 4 5 6 7 root = new newNode(1) root.left = new newNode(2) root.right = new newNode(3) root.left.left = new newNode(4) root.left.right = new newNode(5) root.right.left = new newNode(6) root.right.right = new newNode(7) root.right.left.right = new newNode(8); root.right.right.right = new newNode(9); document.write(\"Following are the values of vertical sums with the positions of the columns with respect to root\") verticalSum(root) // This code is contributed by shinjanpatra</script>", "e": 50196, "s": 48474, "text": null }, { "code": null, "e": 50327, "s": 50196, "text": "Following are the values of vertical sums with the positions of the columns with respect to root\n-2: 4\n-1: 2\n0: 12\n1: 11\n2: 7\n3: 9" }, { "code": null, "e": 50531, "s": 50327, "text": "Vertical Sum in Binary Tree | Set 2 (Space Optimized)Time Complexity: O(nlogn)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50546, "s": 50531, "text": "Shivam.Pradhan" }, { "code": null, "e": 50556, "s": 50546, "text": "Rajput-Ji" }, { "code": null, "e": 50572, "s": 50556, "text": "vipinyadav15799" }, { "code": null, "e": 50586, "s": 50572, "text": "maulikgandhi9" }, { "code": null, "e": 50596, "s": 50586, "text": "kalrap615" }, { "code": null, "e": 50609, "s": 50596, "text": "shinjanpatra" }, { "code": null, "e": 50616, "s": 50609, "text": "Amazon" }, { "code": null, "e": 50621, "s": 50616, "text": "Hash" }, { "code": null, "e": 50626, "s": 50621, "text": "Tree" }, { "code": null, "e": 50633, "s": 50626, "text": "Amazon" }, { "code": null, "e": 50638, "s": 50633, "text": "Hash" }, { "code": null, "e": 50643, "s": 50638, "text": "Tree" }, { "code": null, "e": 50741, "s": 50643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50826, "s": 50741, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 50862, "s": 50826, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 50889, "s": 50862, "text": "Count pairs with given sum" }, { "code": null, "e": 50920, "s": 50889, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 50954, "s": 50920, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 51004, "s": 50954, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 51039, "s": 51004, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 51068, "s": 51039, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 51102, "s": 51068, "text": "Level Order Binary Tree Traversal" } ]
Count square and non-square numbers before n - GeeksforGeeks
23 Feb, 2021 Given a number n, we need to count square numbers smaller than or equal to n.Examples : Input : n = 5 Output : Square Number : 2 Non-square numbers : 3 Explanation : Square numbers are 1 and 4. Non square numbers are 2, 3 and 5. Input : n = 10 Output : Square Number : 3 Non-square numbers : 7 Explanation : Square numbers are 1, 4 and 9. Non square numbers are 2, 3, 5, 6, 7, 8 and 10. A simple solution is to traverse through all numbers from 1 to n and for every number check if n is perfect square or not. An efficient solution is based on below formula.Count of square numbers that are greater than 0 and smaller than or equal to n are floor(sqrt(n)) or ⌊√(n)⌋Count of non-square numbers = n – ⌊√(n)⌋ C++ Java Python3 C# PHP Javascript // CPP program to count squares and// non-squares before a number.#include <bits/stdc++.h>using namespace std; void countSquaresNonSquares(int n){ int sc = floor(sqrt(n)); cout << "Count of squares " << sc << endl; cout << "Count of non-squares " << n - sc << endl;} // Driver Codeint main(){ int n = 10; countSquaresNonSquares(n); return 0;} // Java program to count squares and// non-squares before a number.import java.io.*;import java.math.*; class GFG{ static void countSquaresNonSquares(int n) { int sc = (int)(Math.floor(Math.sqrt(n))); System.out.println("Count of" + " squares " + sc); System.out.println("Count of" + " non-squares " + (n - sc) ); } // Driver code public static void main(String args[]) { int n = 10; countSquaresNonSquares(n); }} // This code is contributed// by Nikita Tiwari. # Python 3 program to count# squares and non-squares# before a number.import math def countSquaresNonSquares(n) : sc = (math.floor(math.sqrt(n))) print("Count of squares ", sc) print("Count of non-squares ", (n - sc) ) # Driver coden = 10countSquaresNonSquares(n) # This code is contributed# by Nikita Tiwari. // C# program to count squares and// non-squares before a number.using System; class GFG{static void countSquaresNonSquares(int n){ int sc = (int)Math.Sqrt(n); Console.WriteLine( "Count of " + "squares " + sc) ; Console.WriteLine("Count of " + "non-squares " + (n - sc));} // Driver Code static public void Main () { int n = 10; countSquaresNonSquares(n); }} // This code is contributed by anuj_67. <?php// PHP program to count// squares and non-squares// before a number. // function to count squares// and non-squares before a// numberfunction countSquaresNonSquares($n){ $sc = floor(sqrt($n)); echo("Count of squares " . $sc . "\n"); echo("Count of non-squares " . ($n - $sc));} // Driver code$n = 10;countSquaresNonSquares($n); // This code is contributed by Ajit.?> <script> // Javascript program to count squares and// non-squares before a number. function countSquaresNonSquares(n){ let sc = Math.floor(Math.sqrt(n)); document.write("Count of squares " + sc + "<br>"); document.write("Count of non-squares " + (n - sc) + "<br>");} // Driver Code let n = 10; countSquaresNonSquares(n); //This code is contributed by Mayank Tyagi </script> Output : Count of squares 3 Count of non-squares 7 jit_t vt_m mayanktyagi1709 maths-perfect-square number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion
[ { "code": null, "e": 26496, "s": 26468, "text": "\n23 Feb, 2021" }, { "code": null, "e": 26586, "s": 26496, "text": "Given a number n, we need to count square numbers smaller than or equal to n.Examples : " }, { "code": null, "e": 26904, "s": 26586, "text": "Input : n = 5\nOutput : Square Number : 2\n Non-square numbers : 3\nExplanation : Square numbers are 1 and 4.\nNon square numbers are 2, 3 and 5.\n\nInput : n = 10\nOutput : Square Number : 3\n Non-square numbers : 7\nExplanation : Square numbers are 1, 4 and 9.\nNon square numbers are 2, 3, 5, 6, 7, 8 and 10." }, { "code": null, "e": 27226, "s": 26906, "text": "A simple solution is to traverse through all numbers from 1 to n and for every number check if n is perfect square or not. An efficient solution is based on below formula.Count of square numbers that are greater than 0 and smaller than or equal to n are floor(sqrt(n)) or ⌊√(n)⌋Count of non-square numbers = n – ⌊√(n)⌋ " }, { "code": null, "e": 27230, "s": 27226, "text": "C++" }, { "code": null, "e": 27235, "s": 27230, "text": "Java" }, { "code": null, "e": 27243, "s": 27235, "text": "Python3" }, { "code": null, "e": 27246, "s": 27243, "text": "C#" }, { "code": null, "e": 27250, "s": 27246, "text": "PHP" }, { "code": null, "e": 27261, "s": 27250, "text": "Javascript" }, { "code": "// CPP program to count squares and// non-squares before a number.#include <bits/stdc++.h>using namespace std; void countSquaresNonSquares(int n){ int sc = floor(sqrt(n)); cout << \"Count of squares \" << sc << endl; cout << \"Count of non-squares \" << n - sc << endl;} // Driver Codeint main(){ int n = 10; countSquaresNonSquares(n); return 0;}", "e": 27638, "s": 27261, "text": null }, { "code": "// Java program to count squares and// non-squares before a number.import java.io.*;import java.math.*; class GFG{ static void countSquaresNonSquares(int n) { int sc = (int)(Math.floor(Math.sqrt(n))); System.out.println(\"Count of\" + \" squares \" + sc); System.out.println(\"Count of\" + \" non-squares \" + (n - sc) ); } // Driver code public static void main(String args[]) { int n = 10; countSquaresNonSquares(n); }} // This code is contributed// by Nikita Tiwari.", "e": 28225, "s": 27638, "text": null }, { "code": "# Python 3 program to count# squares and non-squares# before a number.import math def countSquaresNonSquares(n) : sc = (math.floor(math.sqrt(n))) print(\"Count of squares \", sc) print(\"Count of non-squares \", (n - sc) ) # Driver coden = 10countSquaresNonSquares(n) # This code is contributed# by Nikita Tiwari.", "e": 28553, "s": 28225, "text": null }, { "code": "// C# program to count squares and// non-squares before a number.using System; class GFG{static void countSquaresNonSquares(int n){ int sc = (int)Math.Sqrt(n); Console.WriteLine( \"Count of \" + \"squares \" + sc) ; Console.WriteLine(\"Count of \" + \"non-squares \" + (n - sc));} // Driver Code static public void Main () { int n = 10; countSquaresNonSquares(n); }} // This code is contributed by anuj_67.", "e": 29075, "s": 28553, "text": null }, { "code": "<?php// PHP program to count// squares and non-squares// before a number. // function to count squares// and non-squares before a// numberfunction countSquaresNonSquares($n){ $sc = floor(sqrt($n)); echo(\"Count of squares \" . $sc . \"\\n\"); echo(\"Count of non-squares \" . ($n - $sc));} // Driver code$n = 10;countSquaresNonSquares($n); // This code is contributed by Ajit.?>", "e": 29494, "s": 29075, "text": null }, { "code": "<script> // Javascript program to count squares and// non-squares before a number. function countSquaresNonSquares(n){ let sc = Math.floor(Math.sqrt(n)); document.write(\"Count of squares \" + sc + \"<br>\"); document.write(\"Count of non-squares \" + (n - sc) + \"<br>\");} // Driver Code let n = 10; countSquaresNonSquares(n); //This code is contributed by Mayank Tyagi </script>", "e": 29899, "s": 29494, "text": null }, { "code": null, "e": 29910, "s": 29899, "text": "Output : " }, { "code": null, "e": 29952, "s": 29910, "text": "Count of squares 3\nCount of non-squares 7" }, { "code": null, "e": 29960, "s": 29954, "text": "jit_t" }, { "code": null, "e": 29965, "s": 29960, "text": "vt_m" }, { "code": null, "e": 29981, "s": 29965, "text": "mayanktyagi1709" }, { "code": null, "e": 30002, "s": 29981, "text": "maths-perfect-square" }, { "code": null, "e": 30016, "s": 30002, "text": "number-theory" }, { "code": null, "e": 30029, "s": 30016, "text": "Mathematical" }, { "code": null, "e": 30043, "s": 30029, "text": "number-theory" }, { "code": null, "e": 30056, "s": 30043, "text": "Mathematical" }, { "code": null, "e": 30154, "s": 30056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30178, "s": 30154, "text": "Merge two sorted arrays" }, { "code": null, "e": 30221, "s": 30178, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30235, "s": 30221, "text": "Prime Numbers" }, { "code": null, "e": 30277, "s": 30235, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30299, "s": 30277, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30372, "s": 30299, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30393, "s": 30372, "text": "Operators in C / C++" }, { "code": null, "e": 30436, "s": 30393, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30470, "s": 30436, "text": "Program for factorial of a number" } ]
Program to find the Area and Perimeter of a Semicircle - GeeksforGeeks
01 Apr, 2021 Given the radius of the semicircle as r, the task is to find out the Area and Perimeter of that semicircle.Examples: Input: r = 10 Output: Area = 157.00, Perimeter = 31.4 Input: r = 25 Output: Area =981.250000, Perimeter = 78.500000 Approach: In mathematics, a semicircle is a one-dimensional locus of points that forms half of a circle. The area of a semicircle is half the area of the circle from which it is made. Any diameter of a circle cuts it into two equal semicircles. Area of Semi-Circle = 1⁄2 * π *r2 Perimeter of Semi-Circle = π *r where “r” is the radius of the semicircle. Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ program to find the// Area and Perimeter of a Semicircle #include <iostream>using namespace std; // Function for calculating the areafloat area(float r){ // Formula for finding the area return (0.5)*(3.14)*(r * r);} // Function for calculating the perimeterfloat perimeter(float r){ // Formula for finding the perimeter return (3.14)*(r);} // driver codeint main(){ // Get the radius int r = 10; // Find the area cout << "The Area of Semicircle: " << area(r) << endl; // Find the perimeter cout << "The Perimeter of Semicircle: " << perimeter(r) << endl; return 0;} // C program to find the// Area and Perimeter of a Semicircle #include <stdio.h> // Function for calculating the areafloat area(float r){ // Formula for finding the area return (0.5)*(3.14)*(r * r);} // Function for calculating the perimeterfloat perimeter(float r){ // Formula for finding the perimeter return (3.14)*(r);} // driver codeint main(){ // Get the radius float r = 10; // Find the area printf("The Area of Semicircle: %f\n", area(r)); // Find the perimeter printf("The Perimeter of Semicircle: %f\n", perimeter(r)); return 0;} // Java program to find the// Area and Perimeter of a Semicircle import java.io.*; class GFG { // Function for calculating the areastatic float area(float r){ // Formula for finding the area return (float)((0.5)*(3.14)*(r * r));} // Function for calculating the perimeterstatic float perimeter(float r){ // Formula for finding the perimeter return (float)((3.14)*(r));} // driver code public static void main (String[] args) { // Get the radius float r = 10; // Find the area System.out.println("The Area of Semicircle: "+ area(r)); // Find the perimeter System.out.println("The Perimeter of Semicircle:"+ +perimeter(r)); }} // This code is contributed// by anuj_67.. # Python3 program to find the# Area and Perimeter of a Semicircle # Function for calculating the areadef area(r): # Formula for finding the area return (0.5)*(3.14)*(r * r) #Function for calculating the perimeterdef perimeter(r): #Formula for finding the perimeter return (3.14)*(r) # driver codeif __name__=='__main__': # Get the radius r = 10 # Find the area print ("The Area of Semicircle: " ,area(r)) # Find the perimeter print ("The Perimeter of Semicircle: " ,perimeter(r)) # This code is contributed by# SURENDRA_GANGWAR // C# program to find the// Area and Perimeter of a Semicircleusing System; class GFG { // Function for calculating the areastatic float area(float r){ // Formula for finding the area return (float)((0.5)*(3.14)*(r * r));} // Function for calculating the perimeterstatic float perimeter(float r){ // Formula for finding the perimeter return (float)((3.14)*(r));} // Driver Codepublic static void Main(){ // Get the radius float r = 10; // Find the area Console.WriteLine("The Area of Semicircle: " + area(r)); // Find the perimeter Console.WriteLine("The Perimeter of Semicircle:" + perimeter(r));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find the// Area and Perimeter of a Semicircle // Function for calculating the areafunction area($r){ // Formula for finding the area return (0.5) * (3.14) * ($r * $r);} // Function for calculating// the perimeterfunction perimeter($r){ // Formula for finding // the perimeter return (3.14) * ($r);} // Driver code // Get the radius$r = 10; // Find the areaecho "The Area of Semicircle: ", area($r),"\n" ; // Find the perimeterecho "The Perimeter of Semicircle: ", perimeter($r),"\n" ; // This code is contributed// by ANKITRAI1?> <script>// javascript program to find the// Area and Perimeter of a Semicircle // Function for calculating the area function area(r) { // Formula for finding the area return ((0.5) * (3.14) * (r * r)); } // Function for calculating the perimeter function perimeter(r) { // Formula for finding the perimeter return ((3.14) * (r)); } // driver code // Get the radius var r = 10; // Find the area document.write("The Area of Semicircle: " + area(r).toFixed(6)+"<br/>"); // Find the perimeter document.write("The Perimeter of Semicircle: " + perimeter(r).toFixed(6)+"<br/>"); // This code contributed by gauravrajput1 </script> The Area of Semicircle: 157.000000 The Perimeter of Semicircle: 31.400000 vt_m Akanksha_Rai SURENDRA_GANGWAR ankthon GauravRajput1 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. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26561, "s": 26533, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26680, "s": 26561, "text": "Given the radius of the semicircle as r, the task is to find out the Area and Perimeter of that semicircle.Examples: " }, { "code": null, "e": 26797, "s": 26680, "text": "Input: r = 10\nOutput: Area = 157.00, Perimeter = 31.4\n\nInput: r = 25\nOutput: Area =981.250000, Perimeter = 78.500000" }, { "code": null, "e": 27045, "s": 26799, "text": "Approach: In mathematics, a semicircle is a one-dimensional locus of points that forms half of a circle. The area of a semicircle is half the area of the circle from which it is made. Any diameter of a circle cuts it into two equal semicircles. " }, { "code": null, "e": 27158, "s": 27047, "text": "Area of Semi-Circle = 1⁄2 * π *r2 Perimeter of Semi-Circle = π *r where “r” is the radius of the semicircle. " }, { "code": null, "e": 27210, "s": 27158, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27214, "s": 27210, "text": "C++" }, { "code": null, "e": 27216, "s": 27214, "text": "C" }, { "code": null, "e": 27221, "s": 27216, "text": "Java" }, { "code": null, "e": 27229, "s": 27221, "text": "Python3" }, { "code": null, "e": 27232, "s": 27229, "text": "C#" }, { "code": null, "e": 27236, "s": 27232, "text": "PHP" }, { "code": null, "e": 27247, "s": 27236, "text": "Javascript" }, { "code": "// C++ program to find the// Area and Perimeter of a Semicircle #include <iostream>using namespace std; // Function for calculating the areafloat area(float r){ // Formula for finding the area return (0.5)*(3.14)*(r * r);} // Function for calculating the perimeterfloat perimeter(float r){ // Formula for finding the perimeter return (3.14)*(r);} // driver codeint main(){ // Get the radius int r = 10; // Find the area cout << \"The Area of Semicircle: \" << area(r) << endl; // Find the perimeter cout << \"The Perimeter of Semicircle: \" << perimeter(r) << endl; return 0;}", "e": 27873, "s": 27247, "text": null }, { "code": "// C program to find the// Area and Perimeter of a Semicircle #include <stdio.h> // Function for calculating the areafloat area(float r){ // Formula for finding the area return (0.5)*(3.14)*(r * r);} // Function for calculating the perimeterfloat perimeter(float r){ // Formula for finding the perimeter return (3.14)*(r);} // driver codeint main(){ // Get the radius float r = 10; // Find the area printf(\"The Area of Semicircle: %f\\n\", area(r)); // Find the perimeter printf(\"The Perimeter of Semicircle: %f\\n\", perimeter(r)); return 0;}", "e": 28463, "s": 27873, "text": null }, { "code": "// Java program to find the// Area and Perimeter of a Semicircle import java.io.*; class GFG { // Function for calculating the areastatic float area(float r){ // Formula for finding the area return (float)((0.5)*(3.14)*(r * r));} // Function for calculating the perimeterstatic float perimeter(float r){ // Formula for finding the perimeter return (float)((3.14)*(r));} // driver code public static void main (String[] args) { // Get the radius float r = 10; // Find the area System.out.println(\"The Area of Semicircle: \"+ area(r)); // Find the perimeter System.out.println(\"The Perimeter of Semicircle:\"+ +perimeter(r)); }} // This code is contributed// by anuj_67..", "e": 29184, "s": 28463, "text": null }, { "code": "# Python3 program to find the# Area and Perimeter of a Semicircle # Function for calculating the areadef area(r): # Formula for finding the area return (0.5)*(3.14)*(r * r) #Function for calculating the perimeterdef perimeter(r): #Formula for finding the perimeter return (3.14)*(r) # driver codeif __name__=='__main__': # Get the radius r = 10 # Find the area print (\"The Area of Semicircle: \" ,area(r)) # Find the perimeter print (\"The Perimeter of Semicircle: \" ,perimeter(r)) # This code is contributed by# SURENDRA_GANGWAR", "e": 29785, "s": 29184, "text": null }, { "code": "// C# program to find the// Area and Perimeter of a Semicircleusing System; class GFG { // Function for calculating the areastatic float area(float r){ // Formula for finding the area return (float)((0.5)*(3.14)*(r * r));} // Function for calculating the perimeterstatic float perimeter(float r){ // Formula for finding the perimeter return (float)((3.14)*(r));} // Driver Codepublic static void Main(){ // Get the radius float r = 10; // Find the area Console.WriteLine(\"The Area of Semicircle: \" + area(r)); // Find the perimeter Console.WriteLine(\"The Perimeter of Semicircle:\" + perimeter(r));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 30561, "s": 29785, "text": null }, { "code": "<?php// PHP program to find the// Area and Perimeter of a Semicircle // Function for calculating the areafunction area($r){ // Formula for finding the area return (0.5) * (3.14) * ($r * $r);} // Function for calculating// the perimeterfunction perimeter($r){ // Formula for finding // the perimeter return (3.14) * ($r);} // Driver code // Get the radius$r = 10; // Find the areaecho \"The Area of Semicircle: \", area($r),\"\\n\" ; // Find the perimeterecho \"The Perimeter of Semicircle: \", perimeter($r),\"\\n\" ; // This code is contributed// by ANKITRAI1?>", "e": 31135, "s": 30561, "text": null }, { "code": "<script>// javascript program to find the// Area and Perimeter of a Semicircle // Function for calculating the area function area(r) { // Formula for finding the area return ((0.5) * (3.14) * (r * r)); } // Function for calculating the perimeter function perimeter(r) { // Formula for finding the perimeter return ((3.14) * (r)); } // driver code // Get the radius var r = 10; // Find the area document.write(\"The Area of Semicircle: \" + area(r).toFixed(6)+\"<br/>\"); // Find the perimeter document.write(\"The Perimeter of Semicircle: \" + perimeter(r).toFixed(6)+\"<br/>\"); // This code contributed by gauravrajput1 </script>", "e": 31866, "s": 31135, "text": null }, { "code": null, "e": 31940, "s": 31866, "text": "The Area of Semicircle: 157.000000\nThe Perimeter of Semicircle: 31.400000" }, { "code": null, "e": 31947, "s": 31942, "text": "vt_m" }, { "code": null, "e": 31960, "s": 31947, "text": "Akanksha_Rai" }, { "code": null, "e": 31977, "s": 31960, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 31985, "s": 31977, "text": "ankthon" }, { "code": null, "e": 31999, "s": 31985, "text": "GauravRajput1" }, { "code": null, "e": 32020, "s": 31999, "text": "area-volume-programs" }, { "code": null, "e": 32030, "s": 32020, "text": "Geometric" }, { "code": null, "e": 32043, "s": 32030, "text": "Mathematical" }, { "code": null, "e": 32062, "s": 32043, "text": "School Programming" }, { "code": null, "e": 32075, "s": 32062, "text": "Mathematical" }, { "code": null, "e": 32085, "s": 32075, "text": "Geometric" }, { "code": null, "e": 32183, "s": 32085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32249, "s": 32183, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 32281, "s": 32249, "text": "Program to find slope of a line" }, { "code": null, "e": 32342, "s": 32281, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 32388, "s": 32342, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 32458, "s": 32388, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 32488, "s": 32458, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32548, "s": 32488, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32563, "s": 32548, "text": "C++ Data Types" }, { "code": null, "e": 32606, "s": 32563, "text": "Set in C++ Standard Template Library (STL)" } ]
Bar Graph in MATLAB - GeeksforGeeks
15 Nov, 2021 A Bar Graph is a diagrammatic representation of non-continuous or discrete variables. It is of 2 types vertical and horizontal. When the height axis is on the y-axis then it is a vertical Bar Graph and when the height axis is on the x-axis then it is a horizontal Bar Graph. In MATLAB we have a function named bar() which allows us to plot a bar graph. Syntax: bar(X,Y)where X and Y represent the x and the y axis of the plane. The X and Y both are vectors. Now let’s move to some examples. Example 1: A simple Bar graph: MATLAB % Coordinates of x-axisx=100:20:160;% Coordinates of y-axisy=[22 44 55 66]; % Bar function to plot the Bar graph% Set the width of each bar to 60 percent% of the total space available for each bar% Set the bar color greenbar(x,y,0.6,"green"); Output : Example 2: 3 groups of 4 bars: MATLAB % 3 groups are made with 4 bars% ";" is used to separate the groupsy=[2 5 4 1; 5 3 3 1; 2 8 4 6]; % bar function to plot the barbar(y); Output : Example 3: Display Stacked bars: MATLAB % 3 groupsy=[2 5 4 1; 5 3 3 1; 2 8 4 6]; % stacked is used to stack the bars % on each otherbar(y,'stacked'); Output : Example 4: Display negative bars: MATLAB % bars with negative valuesy=[2 5 4 -1; 5 -3 3 1; -2 8 4 6]; % bar function to display barsbar(y); Output : Example 5: Display horizontal bar graph: MATLAB % Coordinates of y axisy=[2 5 4 1]; % barh() function is used to % display bar horizontallybarh(y); Output : surinderdawra388 MATLAB Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Forward and Inverse Fourier Transform of an Image in MATLAB Boundary Extraction of image using MATLAB How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? How to Normalize a Histogram in MATLAB? How to Remove Salt and Pepper Noise from Image Using MATLAB? Double Integral in MATLAB Classes and Object in MATLAB What are different types of denoising filters in MATLAB? How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
[ { "code": null, "e": 25861, "s": 25833, "text": "\n15 Nov, 2021" }, { "code": null, "e": 26136, "s": 25861, "text": "A Bar Graph is a diagrammatic representation of non-continuous or discrete variables. It is of 2 types vertical and horizontal. When the height axis is on the y-axis then it is a vertical Bar Graph and when the height axis is on the x-axis then it is a horizontal Bar Graph." }, { "code": null, "e": 26215, "s": 26136, "text": "In MATLAB we have a function named bar() which allows us to plot a bar graph. " }, { "code": null, "e": 26223, "s": 26215, "text": "Syntax:" }, { "code": null, "e": 26320, "s": 26223, "text": "bar(X,Y)where X and Y represent the x and the y axis of the plane. The X and Y both are vectors." }, { "code": null, "e": 26353, "s": 26320, "text": "Now let’s move to some examples." }, { "code": null, "e": 26384, "s": 26353, "text": "Example 1: A simple Bar graph:" }, { "code": null, "e": 26391, "s": 26384, "text": "MATLAB" }, { "code": "% Coordinates of x-axisx=100:20:160;% Coordinates of y-axisy=[22 44 55 66]; % Bar function to plot the Bar graph% Set the width of each bar to 60 percent% of the total space available for each bar% Set the bar color greenbar(x,y,0.6,\"green\");", "e": 26635, "s": 26391, "text": null }, { "code": null, "e": 26645, "s": 26635, "text": "Output : " }, { "code": null, "e": 26676, "s": 26645, "text": "Example 2: 3 groups of 4 bars:" }, { "code": null, "e": 26683, "s": 26676, "text": "MATLAB" }, { "code": "% 3 groups are made with 4 bars% \";\" is used to separate the groupsy=[2 5 4 1; 5 3 3 1; 2 8 4 6]; % bar function to plot the barbar(y);", "e": 26820, "s": 26683, "text": null }, { "code": null, "e": 26830, "s": 26820, "text": "Output : " }, { "code": null, "e": 26863, "s": 26830, "text": "Example 3: Display Stacked bars:" }, { "code": null, "e": 26870, "s": 26863, "text": "MATLAB" }, { "code": "% 3 groupsy=[2 5 4 1; 5 3 3 1; 2 8 4 6]; % stacked is used to stack the bars % on each otherbar(y,'stacked');", "e": 26981, "s": 26870, "text": null }, { "code": null, "e": 26992, "s": 26981, "text": "Output : " }, { "code": null, "e": 27026, "s": 26992, "text": "Example 4: Display negative bars:" }, { "code": null, "e": 27033, "s": 27026, "text": "MATLAB" }, { "code": "% bars with negative valuesy=[2 5 4 -1; 5 -3 3 1; -2 8 4 6]; % bar function to display barsbar(y);", "e": 27133, "s": 27033, "text": null }, { "code": null, "e": 27142, "s": 27133, "text": "Output :" }, { "code": null, "e": 27183, "s": 27142, "text": "Example 5: Display horizontal bar graph:" }, { "code": null, "e": 27190, "s": 27183, "text": "MATLAB" }, { "code": "% Coordinates of y axisy=[2 5 4 1]; % barh() function is used to % display bar horizontallybarh(y);", "e": 27291, "s": 27190, "text": null }, { "code": null, "e": 27302, "s": 27291, "text": "Output : " }, { "code": null, "e": 27319, "s": 27302, "text": "surinderdawra388" }, { "code": null, "e": 27326, "s": 27319, "text": "MATLAB" }, { "code": null, "e": 27333, "s": 27326, "text": "Picked" }, { "code": null, "e": 27340, "s": 27333, "text": "MATLAB" }, { "code": null, "e": 27438, "s": 27340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27498, "s": 27438, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 27540, "s": 27498, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 27613, "s": 27540, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 27678, "s": 27613, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 27718, "s": 27678, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 27779, "s": 27718, "text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?" }, { "code": null, "e": 27805, "s": 27779, "text": "Double Integral in MATLAB" }, { "code": null, "e": 27834, "s": 27805, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 27891, "s": 27834, "text": "What are different types of denoising filters in MATLAB?" } ]
How to align item to the flex-end in the container using CSS ? - GeeksforGeeks
06 Apr, 2021 In this article, we will learn how to align item flex-end at the end of the container using CSS. The align-items and display property of CSS is used to align items at the end of the container. Approach: The align-items and display property of CSS are used to align items at the end of the container. To align items at the end of the container, we set the align-items value to flex-end and the display value to flex. Syntax: display:flex; align-items: flex-end; Example: HTML <!DOCTYPE html><html lang="en"> <head> <style> .gfg { border: solid 5px red; width: 50vh; height: 50vh; font-size: 50px; color: rgb(0, 167, 0); display: flex; align-items: flex-end; } </style></head> <body> <div class="gfg"> <div>GeeksforGeeks</div> </div></body> </html> Output: Before applying display and align-items property: After applying display and align-items property: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Tags Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n06 Apr, 2021" }, { "code": null, "e": 26814, "s": 26621, "text": "In this article, we will learn how to align item flex-end at the end of the container using CSS. The align-items and display property of CSS is used to align items at the end of the container." }, { "code": null, "e": 27037, "s": 26814, "text": "Approach: The align-items and display property of CSS are used to align items at the end of the container. To align items at the end of the container, we set the align-items value to flex-end and the display value to flex." }, { "code": null, "e": 27045, "s": 27037, "text": "Syntax:" }, { "code": null, "e": 27083, "s": 27045, "text": "display:flex;\nalign-items: flex-end; " }, { "code": null, "e": 27092, "s": 27083, "text": "Example:" }, { "code": null, "e": 27097, "s": 27092, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .gfg { border: solid 5px red; width: 50vh; height: 50vh; font-size: 50px; color: rgb(0, 167, 0); display: flex; align-items: flex-end; } </style></head> <body> <div class=\"gfg\"> <div>GeeksforGeeks</div> </div></body> </html>", "e": 27482, "s": 27097, "text": null }, { "code": null, "e": 27490, "s": 27482, "text": "Output:" }, { "code": null, "e": 27540, "s": 27490, "text": "Before applying display and align-items property:" }, { "code": null, "e": 27589, "s": 27540, "text": "After applying display and align-items property:" }, { "code": null, "e": 27726, "s": 27589, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27741, "s": 27726, "text": "CSS-Properties" }, { "code": null, "e": 27755, "s": 27741, "text": "CSS-Questions" }, { "code": null, "e": 27765, "s": 27755, "text": "HTML-Tags" }, { "code": null, "e": 27772, "s": 27765, "text": "Picked" }, { "code": null, "e": 27776, "s": 27772, "text": "CSS" }, { "code": null, "e": 27781, "s": 27776, "text": "HTML" }, { "code": null, "e": 27798, "s": 27781, "text": "Web Technologies" }, { "code": null, "e": 27803, "s": 27798, "text": "HTML" }, { "code": null, "e": 27901, "s": 27803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27938, "s": 27901, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27977, "s": 27938, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28006, "s": 27977, "text": "Form validation using jQuery" }, { "code": null, "e": 28048, "s": 28006, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28083, "s": 28048, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28143, "s": 28083, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28196, "s": 28143, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28257, "s": 28196, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28281, "s": 28257, "text": "REST API (Introduction)" } ]
Python - Compute the frequency of words after removing stop words and stemming - GeeksforGeeks
10 Nov, 2021 In this article we are going to tokenize sentence, paragraph, webpage contents using NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentence, paragraph, webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. bs4: Beautiful Soup (bs4) is a Python library for extracting data from HTML and XML files. To install this library, type the following command in IDE/terminal. pip install bs4 urllib: Urllib package is the Uniform Resource Locators handling library for python. It is used to fetch URLs .To install this library, type the following command in IDE/terminal. pip install urllib nltk: The NLTK library is a massive tool kit for Natural Language Processing in python, this module helps us by providing the entire NLP methodology. To install this library, type the following command in IDE/terminal. pip install nltk Step1: Save the files sentence.txt, paragraph.txt in the current directory. Open the files using the open method and store them in file operators named file1, file2. Read the file contents using read() method and store entire file contents into a single string. Display the file contents. Close the file operators. Python import nltks = input('Enter the file name which contains a sentence: ')file1 = open(s)sentence = file1.read()file1.close()p = input('Enter the file name which contains a paragraph: ')file2 = open(p)paragraph = file2.read()file2.close() Step2: Import urllib.request for opening and reading the webpage contents. From bs4 import BeautifulSoup which allows us to pull data out of HTML documents. Using urllib.request make a request to that particular url server. The server will responds and returns the Html document. Read the contents of webpage using read() method. Pass the webpage data into BeautifulSoap which helps us to organize and format the messy web data by fixing bad HTML and present to us in an easily-traversable structures. Python import urllib.requestfrom bs4 import BeautifulSoupurl = input('Enter URL of Webpage: ')print('\n')url_request = urllib.request.Request(url)url_response = urllib.request.urlopen(url)webpage_data = url_response.read()soup = BeautifulSoup(webpage_data, 'html.parser') Step3: To simplify the task of tokenizing we are going to extract an only a portion of HTML page. Using BeautifulSoup operator extract all the paragraph tags present in HTML document. Soup(‘p’) returns a list of items that contain all the paragraph tags present on the webpage. Create an empty string named web_page_data. For each tag present in the list concatenate the text enclosed between the tags to the empty string. Python web_page_paragraph_contents = soup('p')web_page_data = ''for para in web_page_paragraph_contents: web_page_data = web_page_data + str(para.text) Step4: Using re.sub() replace the non-alphabetical characters with an empty string. re.sub() takes a regular expression, new string and the input string as arguments and returns the modified string (Replaces the specified characters in the input string with the new string). ^ – means it will match the pattern written on right of it. \w – #Return a match at every non-alphabeticalthe character(characters NOT between a and Z. Like “!”, “?” white-space, numbers including underscore etc.) and \s – matches a blank space. Python from nltk.tokenize import word_tokenizeimport resentence_without_punctuations = re.sub(r'[^\w\s]', '', sentence)paragraph_without_punctuations = re.sub(r'[^\w\s]', '', paragraph)web_page_paragraphs_without_punctuations = re.sub(r'[^\w\s]', '', web_page_data) Step5: Pass sentence, paragraph, webpage contents after removing punctuations, unnecessary characters into word_tokenize() which returns tokenized text, paragraph, web string. Display the contents of the tokenized sentence, tokenized paragraph, tokenized web string. Python sentence_after_tokenizing = word_tokenize(sentence_without_punctuations)paragraph_after_tokenizing = word_tokenize(paragraph_without_punctuations)webpage_after_tokenizing = word_tokenize(web_page_paragraphs_without_punctuations) Step6: from nltk.corpus import stopwords. Download stopwords using nltk.download(‘stopwords’). Store the English stop words in nltk_stop_words. Compare each word in tokenized sentence, tokenized paragraph tokenized web string with words present in nltk_stop_words if any of the words in our data occurs in nltk stop words we are going to ignore those words. Python from nltk.corpus import stopwordsnltk.download('stopwords')nltk_stop_words = stopwords.words('english')sentence_without_stopwords = [i for i in sentence_after_tokenizing if not i.lower() in nltk_stop_words]paragraph_without_stopwords = [j for j in paragraph_after_tokenizing if not j.lower() in nltk_stop_words]webpage_without_stopwords = [k for k in webpage_after_tokenizing if not k.lower() in nltk_stop_words] Step7: from nltk.stem.porter import PorterStemmer. Do Stemming using nltk : removing the suffix and considering the root word. Create three empty lists for storing stemmed words of sentence, paragraph, webpage. Using stemmer.stem() stem each word present in the previous list and store it in newly created lists. Python from nltk.stem.porter import PorterStemmerstemmer = PorterStemmer()sentence_after_stemming= []paragraph_after_stemming =[]webpage_after_stemming = [] #creating empty lists for storing stemmed wordsfor word in sentence_without_stopwords: sentence_after_stemming.append(stemmer.stem(word))for word in paragraph_without_stopwords: paragraph_after_stemming.append(stemmer.stem(word))for word in webpage_without_stopwords: webpage_after_stemming.append(stemmer.stem(word)) Step8: Sometimes after doing stemming it may result in misspelled words because it is an implementation issue. Using TextBlob module we can find the relevant correct words for a particular misspelled word. For each word in sentence_after_stemming, paragraph_after_stemming, webpage_after_stemming find the actual correct for that word using correct() method. Check whether the correct word present in stop words. If it is not present in stop words replace the correct word with the misspelled word. Python from textblob import TextBlobfinal_words_sentence=[]final_words_paragraph=[]final_words_webpage=[] for i in range(len(sentence_after_stemming)): final_words_sentence.append(0) present_word=sentence_after_stemming[i] b=TextBlob(sentence_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_sentence[i]=present_word else: final_words_sentence[i]=str(b.correct())print(final_words_sentence)print('\n') for i in range(len(paragraph_after_stemming)): final_words_paragraph.append(0) present_word = paragraph_after_stemming[i] b = TextBlob(paragraph_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_paragraph[i] = present_word else: final_words_paragraph[i] = str(b.correct()) print(final_words_paragraph)print('\n') for i in range(len(webpage_after_stemming)): final_words_webpage.append(0) present_word = webpage_after_stemming[i] b = TextBlob(webpage_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_webpage[i] = present_word else: final_words_webpage[i] = str(b.correct())print(final_words_webpage)print('\n') Step9: Using Counter method in the Collections module find the frequency of words in sentences, paragraphs, webpage. Python Counter is a container that will hold the count of each of the elements present in the container. Counter method returns a dictionary with key-value pair as {‘word’,word_count}. Python from collections import Countersentence_count = Counter(final_words_sentence)paragraph_count = Counter(final_words_paragraph)webpage_count = Counter(final_words_webpage) Python import nltks = input('Enter the file name which contains a sentence: ')file1 = open(s)sentence = file1.read()file1.close()p = input('Enter the file name which contains a paragraph: ')file2 = open(p)paragraph = file2.read()file2.close() import urllib.requestfrom bs4 import BeautifulSoupurl = input('Enter URL of Webpage: ')print( '\n' )url_request = urllib.request.Request(url)url_response = urllib.request.urlopen(url)webpage_data = url_response.read()soup = BeautifulSoup(webpage_data, 'html.parser') print('<------------------------------------------Initial Contents of Sentence are-------------------------------------------> \n')print(sentence)print( '\n' ) print('<------------------------------------------Initial Contents of Paragraph are-------------------------------------------> \n')print(paragraph)print( '\n' ) print('<------------------------------------------Initial Contents of Webpage are---------------------------------------------> \n')print(soup)print( '\n' ) web_page_paragraph_contents=soup('p')web_page_data = ''for para in web_page_paragraph_contents: web_page_data = web_page_data + str(para.text) print('<------------------------------------------Contents enclosed between the paragraph tags in the web page are---------------------------------------------> \n')print(web_page_data)print('\n') from nltk.tokenize import word_tokenizeimport resentence_without_punctuations = re.sub(r'[^\w\s]', '', sentence)paragraph_without_punctuations = re.sub(r'[^\w\s]', '', paragraph)web_page_paragraphs_without_punctuations = re.sub(r'[^\w\s]', '', web_page_data)print('<------------------------------------------Contents of sentence after removing punctuations---------------------------------------------> \n')print(sentence_without_punctuations)print('\n')print('<------------------------------------------Contents of paragraph after removing punctuations---------------------------------------------> \n')print(paragraph_without_punctuations)print('\n')print('<------------------------------------------Contents of webpage after removing punctuations-----------------------------------------------> \n')print(web_page_paragraphs_without_punctuations)print('\n') sentence_after_tokenizing = word_tokenize(sentence_without_punctuations)paragraph_after_tokenizing = word_tokenize(paragraph_without_punctuations)webpage_after_tokenizing = word_tokenize(web_page_paragraphs_without_punctuations)print('<------------------------------------------Contents of sentence after tokenizing----------------------------------------------> \n')print(sentence_after_tokenizing)print( '\n' )print('<------------------ ------------------------Contents of paragraph after tokenizing---------------------------------------------> \n')print(paragraph_after_tokenizing)print( '\n' )print('<------------------------------------------Contents of webpage after tokenizing-----------------------------------------------> \n')print(webpage_after_tokenizing)print( '\n' ) from nltk.corpus import stopwordsnltk.download('stopwords')nltk_stop_words = stopwords.words('english')sentence_without_stopwords = [i for i in sentence_after_tokenizing if not i.lower() in nltk_stop_words]paragraph_without_stopwords = [j for j in paragraph_after_tokenizing if not j.lower() in nltk_stop_words]webpage_without_stopwords = [k for k in webpage_after_tokenizing if not k.lower() in nltk_stop_words]print('<------------------------------------------Contents of sentence after removing stopwords---------------------------------------------> \n')print(sentence_without_stopwords)print( '\n' )print('<------------------------------------------Contents of paragraph after removing stopwords---------------------------------------------> \n')print(paragraph_without_stopwords)print( '\n' )print('<------------------------------------------Contents of webpage after removing stopwords-----------------------------------------------> \n')print(webpage_without_stopwords)print( '\n' ) from nltk.stem.porter import PorterStemmerstemmer = PorterStemmer()sentence_after_stemming = []paragraph_after_stemming = []webpage_after_stemming = [] #creating empty lists for storing stemmed wordsfor word in sentence_without_stopwords: sentence_after_stemming.append(stemmer.stem(word))for word in paragraph_without_stopwords: paragraph_after_stemming.append(stemmer.stem(word))for word in webpage_without_stopwords: webpage_after_stemming.append(stemmer.stem(word))print('<------------------------------------------Contents of sentence after doing stemming---------------------------------------------> \n')print(sentence_after_stemming)print( '\n' )print('<------------------------------------------Contents of paragraph after doing stemming---------------------------------------------> \n')print(paragraph_after_stemming)print( '\n' )print('<------------------------------------------Contents of webpage after doing stemming-----------------------------------------------> \n')print(webpage_after_stemming)print( '\n' ) from textblob import TextBlobfinal_words_sentence=[]final_words_paragraph=[]final_words_webpage=[] for i in range(len(sentence_after_stemming)): final_words_sentence.append(0) present_word=sentence_after_stemming[i] b=TextBlob(sentence_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_sentence[i]=present_word else: final_words_sentence[i]=str(b.correct())print('<------------------------------------------Contents of sentence after correcting mispelled words-----------------------------------------------> \n')print(final_words_sentence)print('\n') for i in range(len(paragraph_after_stemming)): final_words_paragraph.append(0) present_word = paragraph_after_stemming[i] b = TextBlob(paragraph_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_paragraph[i] = present_word else: final_words_paragraph[i] = str(b.correct())print('<------------------------------------------Contents of paragraph after correcting mispelled words-----------------------------------------------> \n')print(final_words_paragraph)print('\n') for i in range(len(webpage_after_stemming)): final_words_webpage.append(0) present_word = webpage_after_stemming[i] b = TextBlob(webpage_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_webpage[i] = present_word else: final_words_webpage[i] = str(b.correct())print('<------------------------------------------Contents of webpage after correcting mispelled words-----------------------------------------------> \n')print(final_words_webpage)print('\n') from collections import Countersentence_count = Counter(final_words_sentence)paragraph_count = Counter(final_words_paragraph)webpage_count = Counter(final_words_webpage)print('<------------------------------------------Frequency of words in sentence ---------------------------------------------> \n')print(sentence_count)print( '\n' )print('<------------------------------------------Frequency of words in paragraph ---------------------------------------------> \n')print(paragraph_count)print( '\n' )print('<------------------------------------------Frequency of words in webpage -----------------------------------------------> \n')print(webpage_count) Python-nltk Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n10 Nov, 2021" }, { "code": null, "e": 25874, "s": 25563, "text": "In this article we are going to tokenize sentence, paragraph, webpage contents using NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentence, paragraph, webpage. Finally, we will Compute the frequency of words after removing stop words and stemming." }, { "code": null, "e": 26034, "s": 25874, "text": "bs4: Beautiful Soup (bs4) is a Python library for extracting data from HTML and XML files. To install this library, type the following command in IDE/terminal." }, { "code": null, "e": 26050, "s": 26034, "text": "pip install bs4" }, { "code": null, "e": 26230, "s": 26050, "text": "urllib: Urllib package is the Uniform Resource Locators handling library for python. It is used to fetch URLs .To install this library, type the following command in IDE/terminal." }, { "code": null, "e": 26249, "s": 26230, "text": "pip install urllib" }, { "code": null, "e": 26468, "s": 26249, "text": "nltk: The NLTK library is a massive tool kit for Natural Language Processing in python, this module helps us by providing the entire NLP methodology. To install this library, type the following command in IDE/terminal." }, { "code": null, "e": 26485, "s": 26468, "text": "pip install nltk" }, { "code": null, "e": 26492, "s": 26485, "text": "Step1:" }, { "code": null, "e": 26561, "s": 26492, "text": "Save the files sentence.txt, paragraph.txt in the current directory." }, { "code": null, "e": 26651, "s": 26561, "text": "Open the files using the open method and store them in file operators named file1, file2." }, { "code": null, "e": 26747, "s": 26651, "text": "Read the file contents using read() method and store entire file contents into a single string." }, { "code": null, "e": 26774, "s": 26747, "text": "Display the file contents." }, { "code": null, "e": 26800, "s": 26774, "text": "Close the file operators." }, { "code": null, "e": 26807, "s": 26800, "text": "Python" }, { "code": "import nltks = input('Enter the file name which contains a sentence: ')file1 = open(s)sentence = file1.read()file1.close()p = input('Enter the file name which contains a paragraph: ')file2 = open(p)paragraph = file2.read()file2.close()", "e": 27043, "s": 26807, "text": null }, { "code": null, "e": 27050, "s": 27043, "text": "Step2:" }, { "code": null, "e": 27118, "s": 27050, "text": "Import urllib.request for opening and reading the webpage contents." }, { "code": null, "e": 27200, "s": 27118, "text": "From bs4 import BeautifulSoup which allows us to pull data out of HTML documents." }, { "code": null, "e": 27267, "s": 27200, "text": "Using urllib.request make a request to that particular url server." }, { "code": null, "e": 27323, "s": 27267, "text": "The server will responds and returns the Html document." }, { "code": null, "e": 27373, "s": 27323, "text": "Read the contents of webpage using read() method." }, { "code": null, "e": 27545, "s": 27373, "text": "Pass the webpage data into BeautifulSoap which helps us to organize and format the messy web data by fixing bad HTML and present to us in an easily-traversable structures." }, { "code": null, "e": 27552, "s": 27545, "text": "Python" }, { "code": "import urllib.requestfrom bs4 import BeautifulSoupurl = input('Enter URL of Webpage: ')print('\\n')url_request = urllib.request.Request(url)url_response = urllib.request.urlopen(url)webpage_data = url_response.read()soup = BeautifulSoup(webpage_data, 'html.parser')", "e": 27817, "s": 27552, "text": null }, { "code": null, "e": 27824, "s": 27817, "text": "Step3:" }, { "code": null, "e": 27915, "s": 27824, "text": "To simplify the task of tokenizing we are going to extract an only a portion of HTML page." }, { "code": null, "e": 28001, "s": 27915, "text": "Using BeautifulSoup operator extract all the paragraph tags present in HTML document." }, { "code": null, "e": 28095, "s": 28001, "text": "Soup(‘p’) returns a list of items that contain all the paragraph tags present on the webpage." }, { "code": null, "e": 28139, "s": 28095, "text": "Create an empty string named web_page_data." }, { "code": null, "e": 28240, "s": 28139, "text": "For each tag present in the list concatenate the text enclosed between the tags to the empty string." }, { "code": null, "e": 28247, "s": 28240, "text": "Python" }, { "code": "web_page_paragraph_contents = soup('p')web_page_data = ''for para in web_page_paragraph_contents: web_page_data = web_page_data + str(para.text)", "e": 28395, "s": 28247, "text": null }, { "code": null, "e": 28402, "s": 28395, "text": "Step4:" }, { "code": null, "e": 28479, "s": 28402, "text": "Using re.sub() replace the non-alphabetical characters with an empty string." }, { "code": null, "e": 28670, "s": 28479, "text": "re.sub() takes a regular expression, new string and the input string as arguments and returns the modified string (Replaces the specified characters in the input string with the new string)." }, { "code": null, "e": 28730, "s": 28670, "text": "^ – means it will match the pattern written on right of it." }, { "code": null, "e": 28916, "s": 28730, "text": "\\w – #Return a match at every non-alphabeticalthe character(characters NOT between a and Z. Like “!”, “?” white-space, numbers including underscore etc.) and \\s – matches a blank space." }, { "code": null, "e": 28923, "s": 28916, "text": "Python" }, { "code": "from nltk.tokenize import word_tokenizeimport resentence_without_punctuations = re.sub(r'[^\\w\\s]', '', sentence)paragraph_without_punctuations = re.sub(r'[^\\w\\s]', '', paragraph)web_page_paragraphs_without_punctuations = re.sub(r'[^\\w\\s]', '', web_page_data)", "e": 29182, "s": 28923, "text": null }, { "code": null, "e": 29189, "s": 29182, "text": "Step5:" }, { "code": null, "e": 29358, "s": 29189, "text": "Pass sentence, paragraph, webpage contents after removing punctuations, unnecessary characters into word_tokenize() which returns tokenized text, paragraph, web string." }, { "code": null, "e": 29449, "s": 29358, "text": "Display the contents of the tokenized sentence, tokenized paragraph, tokenized web string." }, { "code": null, "e": 29456, "s": 29449, "text": "Python" }, { "code": "sentence_after_tokenizing = word_tokenize(sentence_without_punctuations)paragraph_after_tokenizing = word_tokenize(paragraph_without_punctuations)webpage_after_tokenizing = word_tokenize(web_page_paragraphs_without_punctuations)", "e": 29685, "s": 29456, "text": null }, { "code": null, "e": 29692, "s": 29685, "text": "Step6:" }, { "code": null, "e": 29727, "s": 29692, "text": "from nltk.corpus import stopwords." }, { "code": null, "e": 29780, "s": 29727, "text": "Download stopwords using nltk.download(‘stopwords’)." }, { "code": null, "e": 29829, "s": 29780, "text": "Store the English stop words in nltk_stop_words." }, { "code": null, "e": 30043, "s": 29829, "text": "Compare each word in tokenized sentence, tokenized paragraph tokenized web string with words present in nltk_stop_words if any of the words in our data occurs in nltk stop words we are going to ignore those words." }, { "code": null, "e": 30050, "s": 30043, "text": "Python" }, { "code": "from nltk.corpus import stopwordsnltk.download('stopwords')nltk_stop_words = stopwords.words('english')sentence_without_stopwords = [i for i in sentence_after_tokenizing if not i.lower() in nltk_stop_words]paragraph_without_stopwords = [j for j in paragraph_after_tokenizing if not j.lower() in nltk_stop_words]webpage_without_stopwords = [k for k in webpage_after_tokenizing if not k.lower() in nltk_stop_words]", "e": 30463, "s": 30050, "text": null }, { "code": null, "e": 30470, "s": 30463, "text": "Step7:" }, { "code": null, "e": 30514, "s": 30470, "text": "from nltk.stem.porter import PorterStemmer." }, { "code": null, "e": 30590, "s": 30514, "text": "Do Stemming using nltk : removing the suffix and considering the root word." }, { "code": null, "e": 30674, "s": 30590, "text": "Create three empty lists for storing stemmed words of sentence, paragraph, webpage." }, { "code": null, "e": 30776, "s": 30674, "text": "Using stemmer.stem() stem each word present in the previous list and store it in newly created lists." }, { "code": null, "e": 30783, "s": 30776, "text": "Python" }, { "code": "from nltk.stem.porter import PorterStemmerstemmer = PorterStemmer()sentence_after_stemming= []paragraph_after_stemming =[]webpage_after_stemming = [] #creating empty lists for storing stemmed wordsfor word in sentence_without_stopwords: sentence_after_stemming.append(stemmer.stem(word))for word in paragraph_without_stopwords: paragraph_after_stemming.append(stemmer.stem(word))for word in webpage_without_stopwords: webpage_after_stemming.append(stemmer.stem(word))", "e": 31261, "s": 30783, "text": null }, { "code": null, "e": 31268, "s": 31261, "text": "Step8:" }, { "code": null, "e": 31372, "s": 31268, "text": "Sometimes after doing stemming it may result in misspelled words because it is an implementation issue." }, { "code": null, "e": 31467, "s": 31372, "text": "Using TextBlob module we can find the relevant correct words for a particular misspelled word." }, { "code": null, "e": 31620, "s": 31467, "text": "For each word in sentence_after_stemming, paragraph_after_stemming, webpage_after_stemming find the actual correct for that word using correct() method." }, { "code": null, "e": 31760, "s": 31620, "text": "Check whether the correct word present in stop words. If it is not present in stop words replace the correct word with the misspelled word." }, { "code": null, "e": 31767, "s": 31760, "text": "Python" }, { "code": "from textblob import TextBlobfinal_words_sentence=[]final_words_paragraph=[]final_words_webpage=[] for i in range(len(sentence_after_stemming)): final_words_sentence.append(0) present_word=sentence_after_stemming[i] b=TextBlob(sentence_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_sentence[i]=present_word else: final_words_sentence[i]=str(b.correct())print(final_words_sentence)print('\\n') for i in range(len(paragraph_after_stemming)): final_words_paragraph.append(0) present_word = paragraph_after_stemming[i] b = TextBlob(paragraph_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_paragraph[i] = present_word else: final_words_paragraph[i] = str(b.correct()) print(final_words_paragraph)print('\\n') for i in range(len(webpage_after_stemming)): final_words_webpage.append(0) present_word = webpage_after_stemming[i] b = TextBlob(webpage_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_webpage[i] = present_word else: final_words_webpage[i] = str(b.correct())print(final_words_webpage)print('\\n')", "e": 32952, "s": 31767, "text": null }, { "code": null, "e": 32959, "s": 32952, "text": "Step9:" }, { "code": null, "e": 33174, "s": 32959, "text": "Using Counter method in the Collections module find the frequency of words in sentences, paragraphs, webpage. Python Counter is a container that will hold the count of each of the elements present in the container." }, { "code": null, "e": 33254, "s": 33174, "text": "Counter method returns a dictionary with key-value pair as {‘word’,word_count}." }, { "code": null, "e": 33261, "s": 33254, "text": "Python" }, { "code": "from collections import Countersentence_count = Counter(final_words_sentence)paragraph_count = Counter(final_words_paragraph)webpage_count = Counter(final_words_webpage)", "e": 33431, "s": 33261, "text": null }, { "code": null, "e": 33438, "s": 33431, "text": "Python" }, { "code": "import nltks = input('Enter the file name which contains a sentence: ')file1 = open(s)sentence = file1.read()file1.close()p = input('Enter the file name which contains a paragraph: ')file2 = open(p)paragraph = file2.read()file2.close() import urllib.requestfrom bs4 import BeautifulSoupurl = input('Enter URL of Webpage: ')print( '\\n' )url_request = urllib.request.Request(url)url_response = urllib.request.urlopen(url)webpage_data = url_response.read()soup = BeautifulSoup(webpage_data, 'html.parser') print('<------------------------------------------Initial Contents of Sentence are-------------------------------------------> \\n')print(sentence)print( '\\n' ) print('<------------------------------------------Initial Contents of Paragraph are-------------------------------------------> \\n')print(paragraph)print( '\\n' ) print('<------------------------------------------Initial Contents of Webpage are---------------------------------------------> \\n')print(soup)print( '\\n' ) web_page_paragraph_contents=soup('p')web_page_data = ''for para in web_page_paragraph_contents: web_page_data = web_page_data + str(para.text) print('<------------------------------------------Contents enclosed between the paragraph tags in the web page are---------------------------------------------> \\n')print(web_page_data)print('\\n') from nltk.tokenize import word_tokenizeimport resentence_without_punctuations = re.sub(r'[^\\w\\s]', '', sentence)paragraph_without_punctuations = re.sub(r'[^\\w\\s]', '', paragraph)web_page_paragraphs_without_punctuations = re.sub(r'[^\\w\\s]', '', web_page_data)print('<------------------------------------------Contents of sentence after removing punctuations---------------------------------------------> \\n')print(sentence_without_punctuations)print('\\n')print('<------------------------------------------Contents of paragraph after removing punctuations---------------------------------------------> \\n')print(paragraph_without_punctuations)print('\\n')print('<------------------------------------------Contents of webpage after removing punctuations-----------------------------------------------> \\n')print(web_page_paragraphs_without_punctuations)print('\\n') sentence_after_tokenizing = word_tokenize(sentence_without_punctuations)paragraph_after_tokenizing = word_tokenize(paragraph_without_punctuations)webpage_after_tokenizing = word_tokenize(web_page_paragraphs_without_punctuations)print('<------------------------------------------Contents of sentence after tokenizing----------------------------------------------> \\n')print(sentence_after_tokenizing)print( '\\n' )print('<------------------ ------------------------Contents of paragraph after tokenizing---------------------------------------------> \\n')print(paragraph_after_tokenizing)print( '\\n' )print('<------------------------------------------Contents of webpage after tokenizing-----------------------------------------------> \\n')print(webpage_after_tokenizing)print( '\\n' ) from nltk.corpus import stopwordsnltk.download('stopwords')nltk_stop_words = stopwords.words('english')sentence_without_stopwords = [i for i in sentence_after_tokenizing if not i.lower() in nltk_stop_words]paragraph_without_stopwords = [j for j in paragraph_after_tokenizing if not j.lower() in nltk_stop_words]webpage_without_stopwords = [k for k in webpage_after_tokenizing if not k.lower() in nltk_stop_words]print('<------------------------------------------Contents of sentence after removing stopwords---------------------------------------------> \\n')print(sentence_without_stopwords)print( '\\n' )print('<------------------------------------------Contents of paragraph after removing stopwords---------------------------------------------> \\n')print(paragraph_without_stopwords)print( '\\n' )print('<------------------------------------------Contents of webpage after removing stopwords-----------------------------------------------> \\n')print(webpage_without_stopwords)print( '\\n' ) from nltk.stem.porter import PorterStemmerstemmer = PorterStemmer()sentence_after_stemming = []paragraph_after_stemming = []webpage_after_stemming = [] #creating empty lists for storing stemmed wordsfor word in sentence_without_stopwords: sentence_after_stemming.append(stemmer.stem(word))for word in paragraph_without_stopwords: paragraph_after_stemming.append(stemmer.stem(word))for word in webpage_without_stopwords: webpage_after_stemming.append(stemmer.stem(word))print('<------------------------------------------Contents of sentence after doing stemming---------------------------------------------> \\n')print(sentence_after_stemming)print( '\\n' )print('<------------------------------------------Contents of paragraph after doing stemming---------------------------------------------> \\n')print(paragraph_after_stemming)print( '\\n' )print('<------------------------------------------Contents of webpage after doing stemming-----------------------------------------------> \\n')print(webpage_after_stemming)print( '\\n' ) from textblob import TextBlobfinal_words_sentence=[]final_words_paragraph=[]final_words_webpage=[] for i in range(len(sentence_after_stemming)): final_words_sentence.append(0) present_word=sentence_after_stemming[i] b=TextBlob(sentence_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_sentence[i]=present_word else: final_words_sentence[i]=str(b.correct())print('<------------------------------------------Contents of sentence after correcting mispelled words-----------------------------------------------> \\n')print(final_words_sentence)print('\\n') for i in range(len(paragraph_after_stemming)): final_words_paragraph.append(0) present_word = paragraph_after_stemming[i] b = TextBlob(paragraph_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_paragraph[i] = present_word else: final_words_paragraph[i] = str(b.correct())print('<------------------------------------------Contents of paragraph after correcting mispelled words-----------------------------------------------> \\n')print(final_words_paragraph)print('\\n') for i in range(len(webpage_after_stemming)): final_words_webpage.append(0) present_word = webpage_after_stemming[i] b = TextBlob(webpage_after_stemming[i]) if str(b.correct()).lower() in nltk_stop_words: final_words_webpage[i] = present_word else: final_words_webpage[i] = str(b.correct())print('<------------------------------------------Contents of webpage after correcting mispelled words-----------------------------------------------> \\n')print(final_words_webpage)print('\\n') from collections import Countersentence_count = Counter(final_words_sentence)paragraph_count = Counter(final_words_paragraph)webpage_count = Counter(final_words_webpage)print('<------------------------------------------Frequency of words in sentence ---------------------------------------------> \\n')print(sentence_count)print( '\\n' )print('<------------------------------------------Frequency of words in paragraph ---------------------------------------------> \\n')print(paragraph_count)print( '\\n' )print('<------------------------------------------Frequency of words in webpage -----------------------------------------------> \\n')print(webpage_count)", "e": 40759, "s": 33438, "text": null }, { "code": null, "e": 40771, "s": 40759, "text": "Python-nltk" }, { "code": null, "e": 40784, "s": 40771, "text": "Web-scraping" }, { "code": null, "e": 40791, "s": 40784, "text": "Python" }, { "code": null, "e": 40889, "s": 40791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40921, "s": 40889, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 40963, "s": 40921, "text": "Check if element exists in list in Python" }, { "code": null, "e": 41005, "s": 40963, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 41061, "s": 41005, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 41088, "s": 41061, "text": "Python Classes and Objects" }, { "code": null, "e": 41127, "s": 41088, "text": "Python | Get unique values from a list" }, { "code": null, "e": 41158, "s": 41127, "text": "Python | os.path.join() method" }, { "code": null, "e": 41180, "s": 41158, "text": "Defaultdict in Python" }, { "code": null, "e": 41209, "s": 41180, "text": "Create a directory in Python" } ]
Recursion in Perl - GeeksforGeeks
27 Jun, 2021 Recursion is a mechanism when a function calls itself again and again till the required condition is met. When the function call statement is written inside the same function then such a function is referred to as a recursive function.The argument passed to a function is retrieved from the default array @_ whereas each value can be accessed by $_[0], $_[1] and so on.Example 1: The example below finds factorial of a number. Factorial of any number n is (n)*(n-1)*(n-2)*....*1. e.g.: 4! = 4*3*2*1 = 24 3! = 3*2*1 = 6 2! = 2*1 = 2 1! = 1 0! = 0 Perl #!/usr/bin/perl # Perl Program to calculate Factorialsub fact{ # Retrieving the first argument# passed with function callingmy $x = $_[0]; # checking if that value is 0 or 1if ($x == 0 || $x == 1){ return 1;} # Recursively calling function with the next value# which is one less than current oneelse{ return $x * fact($x - 1);}} # Driver Code$a = 5; # Function call and printing result after returnprint "Factorial of a number $a is ", fact($a); Here is how the program works : Step 1- When the value of scalar a is 0 or 1, the function will return 1 because the value of both 0! and 1! is 1. Step 2- When the value of scalar a is 2 then fac(x-1) makes a call to fac(1) and this function returns 1. So, it is 2*factorial(1) = 2*1 = 2.So, it will return 2. Step 3- Similarly when higher values are passed to function at every call argument value decreases by 1 and computes till the value reaches 1.Example 2: Example below computes the Fibonacci series till a given number. Perl #!/usr/bin/perl # Perl Program to print Fibonacci seriessub fib{ # Retrieving values from the parameter my $x = shift; my $y = shift; # Number till which the series is to be printed my $n = shift; # Check for the end value if ($y > $n) { return 1; } # Printing the number print " $y"; # Recursive Function Call fib($y, $x + $y, $n); } # Driver Code # Number till which series is to be printed$a = 5; # First two elements of the series$c = 0;$d = 1; print "$c"; # Function call with required parametersfib($c, $d, $a); Here is how the program works : Step 1- Function fib() is called with 3 parameters starting values which will be 0 and 1 while $n is a number till which a series is to be printed Step 2- These values are transferred in the form of an array whose values are retrieved with the use of shift. Step 3- At each call first two values are retrieved using shift and these values are stored in scalars x and y. Now these two values are added to get the next value in the series. This step continues till the value reaches the ending value provided by the user akshaysingh98088 Algorithms-Recursion Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Polymorphism in OOPs Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | length() Function Perl | join() Function Perl | Basic Syntax of a Perl Program Perl | substitution Operator Perl | Regex Cheat Sheet
[ { "code": null, "e": 25543, "s": 25515, "text": "\n27 Jun, 2021" }, { "code": null, "e": 25972, "s": 25543, "text": "Recursion is a mechanism when a function calls itself again and again till the required condition is met. When the function call statement is written inside the same function then such a function is referred to as a recursive function.The argument passed to a function is retrieved from the default array @_ whereas each value can be accessed by $_[0], $_[1] and so on.Example 1: The example below finds factorial of a number. " }, { "code": null, "e": 26091, "s": 25972, "text": "Factorial of any number n is (n)*(n-1)*(n-2)*....*1.\ne.g.:\n4! = 4*3*2*1 = 24\n3! = 3*2*1 = 6\n2! = 2*1 = 2\n1! = 1\n0! = 0" }, { "code": null, "e": 26098, "s": 26093, "text": "Perl" }, { "code": "#!/usr/bin/perl # Perl Program to calculate Factorialsub fact{ # Retrieving the first argument# passed with function callingmy $x = $_[0]; # checking if that value is 0 or 1if ($x == 0 || $x == 1){ return 1;} # Recursively calling function with the next value# which is one less than current oneelse{ return $x * fact($x - 1);}} # Driver Code$a = 5; # Function call and printing result after returnprint \"Factorial of a number $a is \", fact($a);", "e": 26554, "s": 26098, "text": null }, { "code": null, "e": 27084, "s": 26554, "text": "Here is how the program works : Step 1- When the value of scalar a is 0 or 1, the function will return 1 because the value of both 0! and 1! is 1. Step 2- When the value of scalar a is 2 then fac(x-1) makes a call to fac(1) and this function returns 1. So, it is 2*factorial(1) = 2*1 = 2.So, it will return 2. Step 3- Similarly when higher values are passed to function at every call argument value decreases by 1 and computes till the value reaches 1.Example 2: Example below computes the Fibonacci series till a given number. " }, { "code": null, "e": 27089, "s": 27084, "text": "Perl" }, { "code": "#!/usr/bin/perl # Perl Program to print Fibonacci seriessub fib{ # Retrieving values from the parameter my $x = shift; my $y = shift; # Number till which the series is to be printed my $n = shift; # Check for the end value if ($y > $n) { return 1; } # Printing the number print \" $y\"; # Recursive Function Call fib($y, $x + $y, $n); } # Driver Code # Number till which series is to be printed$a = 5; # First two elements of the series$c = 0;$d = 1; print \"$c\"; # Function call with required parametersfib($c, $d, $a);", "e": 27672, "s": 27089, "text": null }, { "code": null, "e": 28224, "s": 27672, "text": "Here is how the program works : Step 1- Function fib() is called with 3 parameters starting values which will be 0 and 1 while $n is a number till which a series is to be printed Step 2- These values are transferred in the form of an array whose values are retrieved with the use of shift. Step 3- At each call first two values are retrieved using shift and these values are stored in scalars x and y. Now these two values are added to get the next value in the series. This step continues till the value reaches the ending value provided by the user " }, { "code": null, "e": 28241, "s": 28224, "text": "akshaysingh98088" }, { "code": null, "e": 28262, "s": 28241, "text": "Algorithms-Recursion" }, { "code": null, "e": 28269, "s": 28262, "text": "Picked" }, { "code": null, "e": 28274, "s": 28269, "text": "Perl" }, { "code": null, "e": 28279, "s": 28274, "text": "Perl" }, { "code": null, "e": 28377, "s": 28279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28419, "s": 28377, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 28447, "s": 28419, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 28461, "s": 28447, "text": "Perl | Arrays" }, { "code": null, "e": 28502, "s": 28461, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 28535, "s": 28502, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 28560, "s": 28535, "text": "Perl | length() Function" }, { "code": null, "e": 28583, "s": 28560, "text": "Perl | join() Function" }, { "code": null, "e": 28621, "s": 28583, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 28650, "s": 28621, "text": "Perl | substitution Operator" } ]
Circular Linked List | Set 2 (Traversal) - GeeksforGeeks
20 Oct, 2021 We have discussed Circular Linked List Introduction and Applications, in the previous post on Circular Linked List. In this post, traversal operation is discussed. In a conventional linked list, we traverse the list from the head node and stop the traversal when we reach NULL. In a circular linked list, we stop traversal when we reach the first node again. Following is the C code for the linked list traversal. C++ C Java Python3 C# Javascript /* Function to print nodes ina given Circular linked list */void printList(Node* head){ Node* temp = head; // If linked list is not empty if (head != NULL) { // Print nodes till we reach first node again do { cout << temp->data << " "; temp = temp->next; } while (temp != head); }} // This code is contributed by rajsanghavi9 /* Function to traverse a given Circular linked list and print nodes */void printList(struct Node *first){ struct Node *temp = first; // If linked list is not empty if (first != NULL) { // Keep printing nodes till we reach the first node again do { printf("%d ", temp->data); temp = temp->next; } while (temp != first); }} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; // If linked list is not empty if (head != null) { // Keep printing nodes till we reach the first node // again do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); }} // This code is contributed by pratham76. # Function to print nodes in a given Circular linked listdef printList(self): temp = self.head # If linked list is not empty if self.head is not None: while(True): # Print nodes till we reach first node again print(temp.data, end = " ") temp = temp.next if (temp == self.head): break # This code is contributed by shivanisinghss2110 /* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; // If linked list is not empty if (head != null) { // Keep printing nodes till we reach the first node // again do { Console.Write(temp.data + " "); temp = temp.next; } while (temp != head); }} //This code is contributed by rutvik_56 <script>/* Function to print nodes in agiven Circular linked list */function printList(head){ var temp = head; // If linked list is not empty if (head != null) { // Keep printing nodes till we reach the first node // again do { document.write(temp.data + " "); temp = temp.next; } while (temp != head); }} // This code contributed by umadevi9616</script> Complete program to demonstrate traversal. Following are complete programs to demonstrate traversal of circular linked list. C++ C Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; /* structure for a node */class Node{ public: int data; Node *next;}; /* Function to insert a node at the beginningof a Circular linked list */void push(Node **head_ref, int data){ Node *ptr1 = new Node(); Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1;} /* Function to print nodes ina given Circular linked list */void printList(Node *head){ Node *temp = head; if (head != NULL) { do { cout << temp->data << " "; temp = temp->next; } while (temp != head); }} /* Driver program to test above functions */int main(){ /* Initialize lists as empty */ Node *head = NULL; /* Created linked list will be 11->2->56->12 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << "Contents of Circular Linked List\n "; printList(head); return 0;} // This is code is contributed by rathbhupendra // C program to implement// the above approach#include<stdio.h>#include<stdlib.h> /* structure for a node */struct Node{ int data; struct Node *next;}; /* Function to insert a node at the beginning of a Circular linked list */void push(struct Node **head_ref, int data){ struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); struct Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1;} /* Function to print nodes in a given Circular linked list */void printList(struct Node *head){ struct Node *temp = head; if (head != NULL) { do { printf("%d ", temp->data); temp = temp->next; } while (temp != head); }} /* Driver program to test above functions */int main(){ /* Initialize lists as empty */ struct Node *head = NULL; /* Created linked list will be 11->2->56->12 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); printf("Contents of Circular Linked List\n "); printList(head); return 0;} // Java program to implement// the above approachclass GFG{ // nodestatic class Node{ int data; Node next;}; /* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; if (head != null) { do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); }} // Driver Codepublic static void main(String args[]){ /* Initialize lists as empty */ Node head = null; /* Created linked list will be 11.2.56.12 */ head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); System.out.println("Contents of Circular " + "Linked List:"); printList(head);}} // This code is contributed// by Arnab Kundu # Python program to demonstrate# circular linked list traversal # Structure for a Nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None class CircularLinkedList: # Constructor to create a empty circular linked list def __init__(self): self.head = None # Function to insert a node at the beginning of a # circular linked list def push(self, data): ptr1 = Node(data) temp = self.head ptr1.next = self.head # If linked list is not None then set the next of # last node if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = ptr1 else: ptr1.next = ptr1 # For the first node self.head = ptr1 # Function to print nodes in a given circular linked list def printList(self): temp = self.head if self.head is not None: while(True): print (temp.data, end=" ") temp = temp.next if (temp == self.head): break # Driver program to test above function # Initialize list as emptycllist = CircularLinkedList() # Created linked list will be 11->2->56->12cllist.push(12)cllist.push(56)cllist.push(2)cllist.push(11) print ("Contents of circular Linked List")cllist.printList() # This code is contributed by# Nikhil Kumar Singh(nickzuck_007) // C# program to implement// the above approachusing System;class GFG{ // nodeclass Node{ public int data; public Node next;}; /* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; if (head != null) { do { Console.Write(temp.data + " "); temp = temp.next; } while (temp != head); }} // Driver Codestatic public void Main(String []args){ /* Initialize lists as empty */ Node head = null; /* Created linked list will be 11.2.56.12 */ head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); Console.WriteLine("Contents of Circular " + "Linked List:"); printList(head);}} // This code is contributed// by Arnab Kundu <script> // JavaScript program to implement// the above approach // nodeclass Node{ constructor(data) { this.data=data; this.next=null; }} /* Function to insert a nodeat the beginning of a Circularlinked list */function push(head_ref, data){ let ptr1 = new Node(); let temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} /* Function to print nodes in agiven Circular linked list */function printList(head){ let temp = head; if (head != null) { do { document.write(temp.data + " "); temp = temp.next; } while (temp != head); }} // Driver Code/* Initialize lists as empty */let head = null; /* Created linked list will be 11.2.56.12 */head = push(head, 12);head = push(head, 56);head = push(head, 2);head = push(head, 11); document.write("Contents of Circular " + "Linked List:<br>");printList(head); // This code is contributed by avanitrachhadiya2155 </script> Output: Contents of Circular Linked List 11 2 56 12 You may like to see the following posts on Circular Linked List Split a Circular Linked List into two halves Sorted insert for circular linked list We will soon be discussing the implementation of insert delete operations for circular linked lists.Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem andrew1234 rathbhupendra shubham_singh rutvik_56 pratham76 umadevi9616 rajsanghavi9 avanitrachhadiya2155 shivanisinghss2110 darsu2000sharma simranarora5sos circular linked list Functions Traversal Linked List Linked List Traversal Functions circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reverse a linked list LinkedList in Java Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists Detect loop in a linked list Find the middle of a given linked list Implement a stack using singly linked list Implementing a Linked List in Java using Class Merge Sort for Linked Lists Remove duplicates from a sorted linked list
[ { "code": null, "e": 39003, "s": 38975, "text": "\n20 Oct, 2021" }, { "code": null, "e": 39168, "s": 39003, "text": "We have discussed Circular Linked List Introduction and Applications, in the previous post on Circular Linked List. In this post, traversal operation is discussed. " }, { "code": null, "e": 39420, "s": 39168, "text": "In a conventional linked list, we traverse the list from the head node and stop the traversal when we reach NULL. In a circular linked list, we stop traversal when we reach the first node again. Following is the C code for the linked list traversal. " }, { "code": null, "e": 39424, "s": 39420, "text": "C++" }, { "code": null, "e": 39426, "s": 39424, "text": "C" }, { "code": null, "e": 39431, "s": 39426, "text": "Java" }, { "code": null, "e": 39439, "s": 39431, "text": "Python3" }, { "code": null, "e": 39442, "s": 39439, "text": "C#" }, { "code": null, "e": 39453, "s": 39442, "text": "Javascript" }, { "code": "/* Function to print nodes ina given Circular linked list */void printList(Node* head){ Node* temp = head; // If linked list is not empty if (head != NULL) { // Print nodes till we reach first node again do { cout << temp->data << \" \"; temp = temp->next; } while (temp != head); }} // This code is contributed by rajsanghavi9", "e": 39836, "s": 39453, "text": null }, { "code": "/* Function to traverse a given Circular linked list and print nodes */void printList(struct Node *first){ struct Node *temp = first; // If linked list is not empty if (first != NULL) { // Keep printing nodes till we reach the first node again do { printf(\"%d \", temp->data); temp = temp->next; } while (temp != first); }}", "e": 40232, "s": 39836, "text": null }, { "code": "/* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; // If linked list is not empty if (head != null) { // Keep printing nodes till we reach the first node // again do { System.out.print(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // This code is contributed by pratham76.", "e": 40665, "s": 40232, "text": null }, { "code": "# Function to print nodes in a given Circular linked listdef printList(self): temp = self.head # If linked list is not empty if self.head is not None: while(True): # Print nodes till we reach first node again print(temp.data, end = \" \") temp = temp.next if (temp == self.head): break # This code is contributed by shivanisinghss2110", "e": 41097, "s": 40665, "text": null }, { "code": "/* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; // If linked list is not empty if (head != null) { // Keep printing nodes till we reach the first node // again do { Console.Write(temp.data + \" \"); temp = temp.next; } while (temp != head); }} //This code is contributed by rutvik_56", "e": 41515, "s": 41097, "text": null }, { "code": "<script>/* Function to print nodes in agiven Circular linked list */function printList(head){ var temp = head; // If linked list is not empty if (head != null) { // Keep printing nodes till we reach the first node // again do { document.write(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // This code contributed by umadevi9616</script>", "e": 41953, "s": 41515, "text": null }, { "code": null, "e": 42080, "s": 41953, "text": "Complete program to demonstrate traversal. Following are complete programs to demonstrate traversal of circular linked list. " }, { "code": null, "e": 42084, "s": 42080, "text": "C++" }, { "code": null, "e": 42086, "s": 42084, "text": "C" }, { "code": null, "e": 42091, "s": 42086, "text": "Java" }, { "code": null, "e": 42099, "s": 42091, "text": "Python3" }, { "code": null, "e": 42102, "s": 42099, "text": "C#" }, { "code": null, "e": 42113, "s": 42102, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; /* structure for a node */class Node{ public: int data; Node *next;}; /* Function to insert a node at the beginningof a Circular linked list */void push(Node **head_ref, int data){ Node *ptr1 = new Node(); Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1;} /* Function to print nodes ina given Circular linked list */void printList(Node *head){ Node *temp = head; if (head != NULL) { do { cout << temp->data << \" \"; temp = temp->next; } while (temp != head); }} /* Driver program to test above functions */int main(){ /* Initialize lists as empty */ Node *head = NULL; /* Created linked list will be 11->2->56->12 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << \"Contents of Circular Linked List\\n \"; printList(head); return 0;} // This is code is contributed by rathbhupendra", "e": 43428, "s": 42113, "text": null }, { "code": "// C program to implement// the above approach#include<stdio.h>#include<stdlib.h> /* structure for a node */struct Node{ int data; struct Node *next;}; /* Function to insert a node at the beginning of a Circular linked list */void push(struct Node **head_ref, int data){ struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); struct Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1;} /* Function to print nodes in a given Circular linked list */void printList(struct Node *head){ struct Node *temp = head; if (head != NULL) { do { printf(\"%d \", temp->data); temp = temp->next; } while (temp != head); }} /* Driver program to test above functions */int main(){ /* Initialize lists as empty */ struct Node *head = NULL; /* Created linked list will be 11->2->56->12 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); printf(\"Contents of Circular Linked List\\n \"); printList(head); return 0;}", "e": 44756, "s": 43428, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // nodestatic class Node{ int data; Node next;}; /* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; if (head != null) { do { System.out.print(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // Driver Codepublic static void main(String args[]){ /* Initialize lists as empty */ Node head = null; /* Created linked list will be 11.2.56.12 */ head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); System.out.println(\"Contents of Circular \" + \"Linked List:\"); printList(head);}} // This code is contributed// by Arnab Kundu", "e": 46088, "s": 44756, "text": null }, { "code": "# Python program to demonstrate# circular linked list traversal # Structure for a Nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None class CircularLinkedList: # Constructor to create a empty circular linked list def __init__(self): self.head = None # Function to insert a node at the beginning of a # circular linked list def push(self, data): ptr1 = Node(data) temp = self.head ptr1.next = self.head # If linked list is not None then set the next of # last node if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = ptr1 else: ptr1.next = ptr1 # For the first node self.head = ptr1 # Function to print nodes in a given circular linked list def printList(self): temp = self.head if self.head is not None: while(True): print (temp.data, end=\" \") temp = temp.next if (temp == self.head): break # Driver program to test above function # Initialize list as emptycllist = CircularLinkedList() # Created linked list will be 11->2->56->12cllist.push(12)cllist.push(56)cllist.push(2)cllist.push(11) print (\"Contents of circular Linked List\")cllist.printList() # This code is contributed by# Nikhil Kumar Singh(nickzuck_007)", "e": 47573, "s": 46088, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // nodeclass Node{ public int data; public Node next;}; /* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} /* Function to print nodes in agiven Circular linked list */static void printList(Node head){ Node temp = head; if (head != null) { do { Console.Write(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // Driver Codestatic public void Main(String []args){ /* Initialize lists as empty */ Node head = null; /* Created linked list will be 11.2.56.12 */ head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); Console.WriteLine(\"Contents of Circular \" + \"Linked List:\"); printList(head);}} // This code is contributed// by Arnab Kundu", "e": 48915, "s": 47573, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // nodeclass Node{ constructor(data) { this.data=data; this.next=null; }} /* Function to insert a nodeat the beginning of a Circularlinked list */function push(head_ref, data){ let ptr1 = new Node(); let temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;} /* Function to print nodes in agiven Circular linked list */function printList(head){ let temp = head; if (head != null) { do { document.write(temp.data + \" \"); temp = temp.next; } while (temp != head); }} // Driver Code/* Initialize lists as empty */let head = null; /* Created linked list will be 11.2.56.12 */head = push(head, 12);head = push(head, 56);head = push(head, 2);head = push(head, 11); document.write(\"Contents of Circular \" + \"Linked List:<br>\");printList(head); // This code is contributed by avanitrachhadiya2155 </script>", "e": 50185, "s": 48915, "text": null }, { "code": null, "e": 50195, "s": 50185, "text": "Output: " }, { "code": null, "e": 50239, "s": 50195, "text": "Contents of Circular Linked List\n11 2 56 12" }, { "code": null, "e": 50387, "s": 50239, "text": "You may like to see the following posts on Circular Linked List Split a Circular Linked List into two halves Sorted insert for circular linked list" }, { "code": null, "e": 50604, "s": 50387, "text": "We will soon be discussing the implementation of insert delete operations for circular linked lists.Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem " }, { "code": null, "e": 50615, "s": 50604, "text": "andrew1234" }, { "code": null, "e": 50629, "s": 50615, "text": "rathbhupendra" }, { "code": null, "e": 50643, "s": 50629, "text": "shubham_singh" }, { "code": null, "e": 50653, "s": 50643, "text": "rutvik_56" }, { "code": null, "e": 50663, "s": 50653, "text": "pratham76" }, { "code": null, "e": 50675, "s": 50663, "text": "umadevi9616" }, { "code": null, "e": 50688, "s": 50675, "text": "rajsanghavi9" }, { "code": null, "e": 50709, "s": 50688, "text": "avanitrachhadiya2155" }, { "code": null, "e": 50728, "s": 50709, "text": "shivanisinghss2110" }, { "code": null, "e": 50744, "s": 50728, "text": "darsu2000sharma" }, { "code": null, "e": 50760, "s": 50744, "text": "simranarora5sos" }, { "code": null, "e": 50781, "s": 50760, "text": "circular linked list" }, { "code": null, "e": 50791, "s": 50781, "text": "Functions" }, { "code": null, "e": 50801, "s": 50791, "text": "Traversal" }, { "code": null, "e": 50813, "s": 50801, "text": "Linked List" }, { "code": null, "e": 50825, "s": 50813, "text": "Linked List" }, { "code": null, "e": 50835, "s": 50825, "text": "Traversal" }, { "code": null, "e": 50845, "s": 50835, "text": "Functions" }, { "code": null, "e": 50866, "s": 50845, "text": "circular linked list" }, { "code": null, "e": 50964, "s": 50866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50986, "s": 50964, "text": "Reverse a linked list" }, { "code": null, "e": 51005, "s": 50986, "text": "LinkedList in Java" }, { "code": null, "e": 51061, "s": 51005, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 51091, "s": 51061, "text": "Merge two sorted linked lists" }, { "code": null, "e": 51120, "s": 51091, "text": "Detect loop in a linked list" }, { "code": null, "e": 51159, "s": 51120, "text": "Find the middle of a given linked list" }, { "code": null, "e": 51202, "s": 51159, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 51249, "s": 51202, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 51277, "s": 51249, "text": "Merge Sort for Linked Lists" } ]
Visualizing Decision Trees with Pybaobabdt | by Parul Pandey | Towards Data Science
Data visualization is the language of decision-making. Good charts effectively convey information. Great charts enable, inform, and improve decision making: Dante Vitagliano Decision trees can be visualized in multiple ways. Take, for instance, the indentation nodes where every internal and leaf node is depicted as text, while the parent-child relationship is shown by indenting the child with respect to the parent. Then there is the node-link diagram. It is one of the most commonly used methods to visualize decision trees where the nodes are represented via glyphs, and parent and child nodes are connected through links. Icicle plots are another option for the same. In addition to displaying the relationship, these plots also help depict the node size. They derive their name from the fact that the resulting visualization looks like icicles. While these techniques are helpful, they do not scale well especially when the size of data increases. In such situations, not only does it become difficult to visualize the data, but interpreting and understanding the tree is also a challenge. BaobabView is a library created to overcome such problems, and in this article, we'll look at its python implementation called pybaobabdt in detail, along with examples. We initiated the article by discussing the multiple ways of visualizing decision trees. It'll also be worthwhile to look at various libraries that help plot decision trees. We'll use Palmer's Penguins dataset as a common dataset here. It is a well-known dataset and is typically a drop-in replacement for the iris dataset, and the goal is to predict the penguin species from the given features. This is the default way and the most commonly used method. It is available as the default option with scikit-learn. The max_depth of the tree has been limited to 3 for this example. The dtreeviz library renders better-looking and intuitive visualizations while offering better interpretability options. The library derives its inspiration from the educational animation by R2D3; A visual introduction to machine learning. Link to article: A better way to visualize Decision Trees with the dtreeviz library The TensorFlow Decision forests is a library created for training, serving, inferencing, and interpreting these Decision Forest models. It provides a unified API for both tree-based models as well as neural networks. The TensorFlow Decision Forests have inbuilt interactive plotting methods to plot and help understand the tree structure. Link to article: Reviewing the TensorFlow Decision Forests library A paper titled BaobabView: Interactive construction and analysis of decision trees showcases a unique technique for visualizing decision trees. This technique is not only scalable but also enables experts to inject their domain knowledge into the construction of decision trees. The method is called BaobabView and relies on the three critical aspects of visualization, interaction, and algorithmic support. Here is an excerpt from the paper which highlights this point concretely: We think our tool provides a double example of a visual analytics approach. We show how a machine learning method can be enhanced using interaction and visualization; we also show how manual construction and analysis can be supported by algorithmic and automated support. Are you wondering about the strange name? Well, the term has its roots(pun intended) in the Adansonia digitata or the African baobab due to its uncanny resemblance to the tree structure. The pybaobabdt package is a python implementation of the BaobabView. Let's now get a little deeper into the specifics of this library starting with its installation. The package can be installed as follows: pip install pybaobabdt However, there are a few requirements that need to be fulfilled: Python version ≥ 3.6 PyGraphviz Popular python packages like sklearn, numpy, pygraphviz, matplotlib, scipy, pandas should also be installed. I experienced a few hiccups while getting to install pygraphviz. Refer to the accompanying code notebook if you face the same issues. github.com We'll continue with our penguins' dataset and build a decision tree to predict the penguin species from the given features. from sklearn.tree import DecisionTreeClassifiery = list(df['Species'])features = list(df.columns)target = df['Species']features.remove('Species')X = df.loc[:, features]clf = DecisionTreeClassifier().fit(X,y) The code above initializes and trains a classification tree. Once that is done, the next task is to visualize the tree using the pybaobabdt package, which can be accomplished in just a single line of code. ax = pybaobabdt.drawTree(clf, size=10, dpi=300, features=features, ratio=0.8,colormap='Set1') There you go! You have a decision tree classifier, where every class of species is represented with a different color. In the case of a Random Forest, it is also possible to visualize individual trees. These trees can then be saved to higher resolution images for in-depth inspection. The pybaobabdt library also offers a bunch of customizations. I'll showcase a few of them here: pybaobabdt supports all matplotlib colormaps. We have seen how a Set1 colormap looks like, but you can choose from many different options. Here are how few of them appear when used: But you are not limited to the available colormaps. You can even define one of your own. Let's say we want to highlight just one specific class in our dataset while keeping all the others in the background. Here's what we can do: from matplotlib.colors import ListedColormapcolors = ["green", "gray", "gray"]colorMap = ListedColormap(colors)ax = pybaobabdt.drawTree(clf, size=10, features=features, ratio=0.8,colormap=colorMap) The ratio option is used to set the ratio of the tree where the default value is 1. Here's a comparison of the two ratios and how they appear on the screen. ax = pybaobabdt.drawTree(clf, size=10, dpi=300, features=features, ratio=0.5,colormap='viridis') The parameter maxdepth controls the depth of the tree. A lower number limits the tree splits and also shows the top splits. If the max_depth of the above tree is set to 3, we'll get a stunted tree: ax = pybaobabdt.drawTree(clf, size=10, maxdepth = 3,features=features, ratio=1,colormap='plasma') The output graph can be saved as follows: ax.get_figure().savefig('claasifier_tree.png', format='png', dpi=300, transparent=True) The pybaobabdt package offers a fresh perspective on visualizations. It includes features that have not been seen in its counterparts. The main idea is to help the users understand and interpret the tree through meaningful visualizations. This article used a straightforward example to demonstrate the library. However, it'll be an excellent exercise to use it for much more extensive and complex datasets to see its strength in the real sense. I'll leave that as an exercise for the readers. The official Github repository of the pybaobabdt package. Interactive construction, analysis, and visualization of decision trees, Stef van den Elzen, MSc. Thesis, Eindhoven University of Technology, 2011 Understanding Decision Trees
[ { "code": null, "e": 346, "s": 172, "text": "Data visualization is the language of decision-making. Good charts effectively convey information. Great charts enable, inform, and improve decision making: Dante Vitagliano" }, { "code": null, "e": 591, "s": 346, "text": "Decision trees can be visualized in multiple ways. Take, for instance, the indentation nodes where every internal and leaf node is depicted as text, while the parent-child relationship is shown by indenting the child with respect to the parent." }, { "code": null, "e": 800, "s": 591, "text": "Then there is the node-link diagram. It is one of the most commonly used methods to visualize decision trees where the nodes are represented via glyphs, and parent and child nodes are connected through links." }, { "code": null, "e": 1024, "s": 800, "text": "Icicle plots are another option for the same. In addition to displaying the relationship, these plots also help depict the node size. They derive their name from the fact that the resulting visualization looks like icicles." }, { "code": null, "e": 1439, "s": 1024, "text": "While these techniques are helpful, they do not scale well especially when the size of data increases. In such situations, not only does it become difficult to visualize the data, but interpreting and understanding the tree is also a challenge. BaobabView is a library created to overcome such problems, and in this article, we'll look at its python implementation called pybaobabdt in detail, along with examples." }, { "code": null, "e": 1612, "s": 1439, "text": "We initiated the article by discussing the multiple ways of visualizing decision trees. It'll also be worthwhile to look at various libraries that help plot decision trees." }, { "code": null, "e": 1834, "s": 1612, "text": "We'll use Palmer's Penguins dataset as a common dataset here. It is a well-known dataset and is typically a drop-in replacement for the iris dataset, and the goal is to predict the penguin species from the given features." }, { "code": null, "e": 1950, "s": 1834, "text": "This is the default way and the most commonly used method. It is available as the default option with scikit-learn." }, { "code": null, "e": 2016, "s": 1950, "text": "The max_depth of the tree has been limited to 3 for this example." }, { "code": null, "e": 2256, "s": 2016, "text": "The dtreeviz library renders better-looking and intuitive visualizations while offering better interpretability options. The library derives its inspiration from the educational animation by R2D3; A visual introduction to machine learning." }, { "code": null, "e": 2340, "s": 2256, "text": "Link to article: A better way to visualize Decision Trees with the dtreeviz library" }, { "code": null, "e": 2679, "s": 2340, "text": "The TensorFlow Decision forests is a library created for training, serving, inferencing, and interpreting these Decision Forest models. It provides a unified API for both tree-based models as well as neural networks. The TensorFlow Decision Forests have inbuilt interactive plotting methods to plot and help understand the tree structure." }, { "code": null, "e": 2746, "s": 2679, "text": "Link to article: Reviewing the TensorFlow Decision Forests library" }, { "code": null, "e": 3154, "s": 2746, "text": "A paper titled BaobabView: Interactive construction and analysis of decision trees showcases a unique technique for visualizing decision trees. This technique is not only scalable but also enables experts to inject their domain knowledge into the construction of decision trees. The method is called BaobabView and relies on the three critical aspects of visualization, interaction, and algorithmic support." }, { "code": null, "e": 3228, "s": 3154, "text": "Here is an excerpt from the paper which highlights this point concretely:" }, { "code": null, "e": 3500, "s": 3228, "text": "We think our tool provides a double example of a visual analytics approach. We show how a machine learning method can be enhanced using interaction and visualization; we also show how manual construction and analysis can be supported by algorithmic and automated support." }, { "code": null, "e": 3687, "s": 3500, "text": "Are you wondering about the strange name? Well, the term has its roots(pun intended) in the Adansonia digitata or the African baobab due to its uncanny resemblance to the tree structure." }, { "code": null, "e": 3853, "s": 3687, "text": "The pybaobabdt package is a python implementation of the BaobabView. Let's now get a little deeper into the specifics of this library starting with its installation." }, { "code": null, "e": 3894, "s": 3853, "text": "The package can be installed as follows:" }, { "code": null, "e": 3917, "s": 3894, "text": "pip install pybaobabdt" }, { "code": null, "e": 3982, "s": 3917, "text": "However, there are a few requirements that need to be fulfilled:" }, { "code": null, "e": 4003, "s": 3982, "text": "Python version ≥ 3.6" }, { "code": null, "e": 4014, "s": 4003, "text": "PyGraphviz" }, { "code": null, "e": 4123, "s": 4014, "text": "Popular python packages like sklearn, numpy, pygraphviz, matplotlib, scipy, pandas should also be installed." }, { "code": null, "e": 4257, "s": 4123, "text": "I experienced a few hiccups while getting to install pygraphviz. Refer to the accompanying code notebook if you face the same issues." }, { "code": null, "e": 4268, "s": 4257, "text": "github.com" }, { "code": null, "e": 4392, "s": 4268, "text": "We'll continue with our penguins' dataset and build a decision tree to predict the penguin species from the given features." }, { "code": null, "e": 4600, "s": 4392, "text": "from sklearn.tree import DecisionTreeClassifiery = list(df['Species'])features = list(df.columns)target = df['Species']features.remove('Species')X = df.loc[:, features]clf = DecisionTreeClassifier().fit(X,y)" }, { "code": null, "e": 4806, "s": 4600, "text": "The code above initializes and trains a classification tree. Once that is done, the next task is to visualize the tree using the pybaobabdt package, which can be accomplished in just a single line of code." }, { "code": null, "e": 4900, "s": 4806, "text": "ax = pybaobabdt.drawTree(clf, size=10, dpi=300, features=features, ratio=0.8,colormap='Set1')" }, { "code": null, "e": 5185, "s": 4900, "text": "There you go! You have a decision tree classifier, where every class of species is represented with a different color. In the case of a Random Forest, it is also possible to visualize individual trees. These trees can then be saved to higher resolution images for in-depth inspection." }, { "code": null, "e": 5281, "s": 5185, "text": "The pybaobabdt library also offers a bunch of customizations. I'll showcase a few of them here:" }, { "code": null, "e": 5463, "s": 5281, "text": "pybaobabdt supports all matplotlib colormaps. We have seen how a Set1 colormap looks like, but you can choose from many different options. Here are how few of them appear when used:" }, { "code": null, "e": 5693, "s": 5463, "text": "But you are not limited to the available colormaps. You can even define one of your own. Let's say we want to highlight just one specific class in our dataset while keeping all the others in the background. Here's what we can do:" }, { "code": null, "e": 5891, "s": 5693, "text": "from matplotlib.colors import ListedColormapcolors = [\"green\", \"gray\", \"gray\"]colorMap = ListedColormap(colors)ax = pybaobabdt.drawTree(clf, size=10, features=features, ratio=0.8,colormap=colorMap)" }, { "code": null, "e": 6048, "s": 5891, "text": "The ratio option is used to set the ratio of the tree where the default value is 1. Here's a comparison of the two ratios and how they appear on the screen." }, { "code": null, "e": 6145, "s": 6048, "text": "ax = pybaobabdt.drawTree(clf, size=10, dpi=300, features=features, ratio=0.5,colormap='viridis')" }, { "code": null, "e": 6343, "s": 6145, "text": "The parameter maxdepth controls the depth of the tree. A lower number limits the tree splits and also shows the top splits. If the max_depth of the above tree is set to 3, we'll get a stunted tree:" }, { "code": null, "e": 6441, "s": 6343, "text": "ax = pybaobabdt.drawTree(clf, size=10, maxdepth = 3,features=features, ratio=1,colormap='plasma')" }, { "code": null, "e": 6483, "s": 6441, "text": "The output graph can be saved as follows:" }, { "code": null, "e": 6571, "s": 6483, "text": "ax.get_figure().savefig('claasifier_tree.png', format='png', dpi=300, transparent=True)" }, { "code": null, "e": 7064, "s": 6571, "text": "The pybaobabdt package offers a fresh perspective on visualizations. It includes features that have not been seen in its counterparts. The main idea is to help the users understand and interpret the tree through meaningful visualizations. This article used a straightforward example to demonstrate the library. However, it'll be an excellent exercise to use it for much more extensive and complex datasets to see its strength in the real sense. I'll leave that as an exercise for the readers." }, { "code": null, "e": 7122, "s": 7064, "text": "The official Github repository of the pybaobabdt package." }, { "code": null, "e": 7269, "s": 7122, "text": "Interactive construction, analysis, and visualization of decision trees, Stef van den Elzen, MSc. Thesis, Eindhoven University of Technology, 2011" } ]
HackerRank Interview Experience for SDE (Bangalore) - GeeksforGeeks
22 Feb, 2021 I applied for this role at hackerrank.com/careers Round 1(Online coding round in HackerRank): I got a Hackerrank test link. I had 2 questions asked in the test Given an array of elements, Find the count of unique elements in an array.Encrypt a string, as below Given an array of elements, Find the count of unique elements in an array. Encrypt a string, as below Original string - saaavvvvvqql (given) Encrypted string - s3v5q2l (need to return this string) I solved both the questions successfully After 1 week, I got an email saying that I will be moved to the next round. I was asked about my current CTC and my expected CTC. I didn’t have an expected CTC in my mind, rather I was looking out for what they offered. I didn’t get an answer Round 2: I was how I would design a system that will convert long urls to tiny urls. They told me to design tables for the same. They also asked me questions on load balancing, I answered them fairly well. After 2 days, I got an email saying that they have decided to move forward with other candidates. HackerRank Marketing Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience Amazon Interview Experience for SDE-1 Infosys Interview Experience for DSE 2022 Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 (On-Campus) JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ Google Interview Experience SDE-1 (Off-Campus) 2022
[ { "code": null, "e": 26371, "s": 26343, "text": "\n22 Feb, 2021" }, { "code": null, "e": 26421, "s": 26371, "text": "I applied for this role at hackerrank.com/careers" }, { "code": null, "e": 26531, "s": 26421, "text": "Round 1(Online coding round in HackerRank): I got a Hackerrank test link. I had 2 questions asked in the test" }, { "code": null, "e": 26632, "s": 26531, "text": "Given an array of elements, Find the count of unique elements in an array.Encrypt a string, as below" }, { "code": null, "e": 26707, "s": 26632, "text": "Given an array of elements, Find the count of unique elements in an array." }, { "code": null, "e": 26734, "s": 26707, "text": "Encrypt a string, as below" }, { "code": null, "e": 26829, "s": 26734, "text": "Original string - saaavvvvvqql (given)\nEncrypted string - s3v5q2l (need to return this string)" }, { "code": null, "e": 26870, "s": 26829, "text": "I solved both the questions successfully" }, { "code": null, "e": 27113, "s": 26870, "text": "After 1 week, I got an email saying that I will be moved to the next round. I was asked about my current CTC and my expected CTC. I didn’t have an expected CTC in my mind, rather I was looking out for what they offered. I didn’t get an answer" }, { "code": null, "e": 27320, "s": 27113, "text": "Round 2: I was how I would design a system that will convert long urls to tiny urls. They told me to design tables for the same. They also asked me questions on load balancing, I answered them fairly well. " }, { "code": null, "e": 27419, "s": 27320, "text": "After 2 days, I got an email saying that they have decided to move forward with other candidates. " }, { "code": null, "e": 27430, "s": 27419, "text": "HackerRank" }, { "code": null, "e": 27440, "s": 27430, "text": "Marketing" }, { "code": null, "e": 27462, "s": 27440, "text": "Interview Experiences" }, { "code": null, "e": 27560, "s": 27462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27611, "s": 27560, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 27653, "s": 27611, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 27681, "s": 27653, "text": "Amazon Interview Experience" }, { "code": null, "e": 27719, "s": 27681, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 27761, "s": 27719, "text": "Infosys Interview Experience for DSE 2022" }, { "code": null, "e": 27807, "s": 27761, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 27857, "s": 27807, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 27929, "s": 27857, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 28005, "s": 27929, "text": "Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ" } ]
Angular ng bootstrap Tooltip Component - GeeksforGeeks
19 Jul, 2021 Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will know how to use Tooltip in angular ng bootstrap. Tooltip is used to display informative text when users hover over, focus on, or tap an element. Installation syntax: ng add @ng-bootstrap/ng-bootstrap Approach: First, install the angular ng bootstrap using the above-mentioned command. Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> <link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> Import ng bootstrap module in module.tsimport { NgbModule } from ‘@ng-bootstrap/ng-bootstrap’;imports: [NgbModule] import { NgbModule } from ‘@ng-bootstrap/ng-bootstrap’; imports: [NgbModule] In app.component.html make a tooltip component. Serve the app using ng serve. Example 1: In this example, we are making a basic example of the tooltip. app.component.html <div id='geeks'> <br /><br /><br /> <button type="button" class="btn btn-primary" placement="top" ngbTooltip="GeeksforGeeks"> top </button> <hr> <button type="button" class="btn btn-success" placement="right" ngbTooltip="GeeksforGeeks"> right </button> <hr> <button type="button" class="btn btn-warning" placement="bottom" ngbTooltip="GeeksforGeeks"> bottom </button> <br /><br /><br /> <hr> <button id='gfg' type="button" class="btn btn-danger" placement="left" ngbTooltip="GeeksforGeeks"> left </button></div> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.css #gfg { margin-left:120px}#geeks { margin-left:40px} Output: Example 2: In this example, we are making a toast with a header. app.component.html <div id='geeks'> <br /><br /><br /> <button type="button" class="btn btn-primary" [disabled]='true' placement="top" ngbTooltip="GeeksforGeeks"> top </button> <hr> <button type="button" class="btn btn-success" [disabled]='true' placement="right" ngbTooltip="GeeksforGeeks"> right </button> <hr> <button type="button" class="btn btn-warning" [disabled]='true' placement="bottom" ngbTooltip="GeeksforGeeks"> bottom </button> <br /><br /><br /> <hr> <button id='gfg' type="button" class="btn btn-danger" [disabled]='true' placement="left" ngbTooltip="GeeksforGeeks"> left </button></div> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.css #gfg { margin-left:120px}#geeks { margin-left:40px} Output: Reference: https://ng-bootstrap.github.io/#/components/typeahead/examples Angular-ng-bootstrap AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular 10 (blur) Event Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 25109, "s": 25081, "text": "\n19 Jul, 2021" }, { "code": null, "e": 25367, "s": 25109, "text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will know how to use Tooltip in angular ng bootstrap." }, { "code": null, "e": 25463, "s": 25367, "text": "Tooltip is used to display informative text when users hover over, focus on, or tap an element." }, { "code": null, "e": 25484, "s": 25463, "text": "Installation syntax:" }, { "code": null, "e": 25518, "s": 25484, "text": "ng add @ng-bootstrap/ng-bootstrap" }, { "code": null, "e": 25528, "s": 25518, "text": "Approach:" }, { "code": null, "e": 25604, "s": 25528, "text": "First, install the angular ng bootstrap using the above-mentioned command. " }, { "code": null, "e": 25745, "s": 25606, "text": "Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 25846, "s": 25745, "text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 25961, "s": 25846, "text": "Import ng bootstrap module in module.tsimport { NgbModule } from ‘@ng-bootstrap/ng-bootstrap’;imports: [NgbModule]" }, { "code": null, "e": 26017, "s": 25961, "text": "import { NgbModule } from ‘@ng-bootstrap/ng-bootstrap’;" }, { "code": null, "e": 26038, "s": 26017, "text": "imports: [NgbModule]" }, { "code": null, "e": 26086, "s": 26038, "text": "In app.component.html make a tooltip component." }, { "code": null, "e": 26116, "s": 26086, "text": "Serve the app using ng serve." }, { "code": null, "e": 26190, "s": 26116, "text": "Example 1: In this example, we are making a basic example of the tooltip." }, { "code": null, "e": 26209, "s": 26190, "text": "app.component.html" }, { "code": "<div id='geeks'> <br /><br /><br /> <button type=\"button\" class=\"btn btn-primary\" placement=\"top\" ngbTooltip=\"GeeksforGeeks\"> top </button> <hr> <button type=\"button\" class=\"btn btn-success\" placement=\"right\" ngbTooltip=\"GeeksforGeeks\"> right </button> <hr> <button type=\"button\" class=\"btn btn-warning\" placement=\"bottom\" ngbTooltip=\"GeeksforGeeks\"> bottom </button> <br /><br /><br /> <hr> <button id='gfg' type=\"button\" class=\"btn btn-danger\" placement=\"left\" ngbTooltip=\"GeeksforGeeks\"> left </button></div>", "e": 26900, "s": 26209, "text": null }, { "code": null, "e": 26914, "s": 26900, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 27563, "s": 26914, "text": null }, { "code": null, "e": 27581, "s": 27563, "text": "app.component.css" }, { "code": "#gfg { margin-left:120px}#geeks { margin-left:40px}", "e": 27639, "s": 27581, "text": null }, { "code": null, "e": 27647, "s": 27639, "text": "Output:" }, { "code": null, "e": 27712, "s": 27647, "text": "Example 2: In this example, we are making a toast with a header." }, { "code": null, "e": 27731, "s": 27712, "text": "app.component.html" }, { "code": "<div id='geeks'> <br /><br /><br /> <button type=\"button\" class=\"btn btn-primary\" [disabled]='true' placement=\"top\" ngbTooltip=\"GeeksforGeeks\"> top </button> <hr> <button type=\"button\" class=\"btn btn-success\" [disabled]='true' placement=\"right\" ngbTooltip=\"GeeksforGeeks\"> right </button> <hr> <button type=\"button\" class=\"btn btn-warning\" [disabled]='true' placement=\"bottom\" ngbTooltip=\"GeeksforGeeks\"> bottom </button> <br /><br /><br /> <hr> <button id='gfg' type=\"button\" class=\"btn btn-danger\" [disabled]='true' placement=\"left\" ngbTooltip=\"GeeksforGeeks\"> left </button></div>", "e": 28519, "s": 27731, "text": null }, { "code": null, "e": 28533, "s": 28519, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 29182, "s": 28533, "text": null }, { "code": null, "e": 29200, "s": 29182, "text": "app.component.css" }, { "code": "#gfg { margin-left:120px}#geeks { margin-left:40px}", "e": 29258, "s": 29200, "text": null }, { "code": null, "e": 29266, "s": 29258, "text": "Output:" }, { "code": null, "e": 29340, "s": 29266, "text": "Reference: https://ng-bootstrap.github.io/#/components/typeahead/examples" }, { "code": null, "e": 29361, "s": 29340, "text": "Angular-ng-bootstrap" }, { "code": null, "e": 29371, "s": 29361, "text": "AngularJS" }, { "code": null, "e": 29388, "s": 29371, "text": "Web Technologies" }, { "code": null, "e": 29486, "s": 29388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29530, "s": 29486, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29554, "s": 29530, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29589, "s": 29554, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29642, "s": 29589, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29691, "s": 29642, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 29733, "s": 29691, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29795, "s": 29733, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29838, "s": 29795, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29871, "s": 29838, "text": "Installation of Node.js on Linux" } ]
GATE | GATE-CS-2003 | Question 5 - GeeksforGeeks
28 Jun, 2021 n couples are invited to a party with the condition that every husband should be accompanied by his wife. However, a wife need not be accompanied by her husband. The number of different gatherings possible at the party is(A) A(B) B(C) C(D) DAnswer: (B)Explanation: There are three options for every couple. 1) Nobody goes to gathering 2) Wife alone goes 2) Both go Since there are n couples, total possible ways of gathering are 3nQuiz of this Question GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE CS 2019 | Question 27 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2000 | Question 43 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | Gate IT 2007 | Question 30 GATE | GATE CS 2010 | Question 24
[ { "code": null, "e": 24360, "s": 24332, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24667, "s": 24360, "text": "n couples are invited to a party with the condition that every husband should be accompanied by his wife. However, a wife need not be accompanied by her husband. The number of different gatherings possible at the party is(A) A(B) B(C) C(D) DAnswer: (B)Explanation: There are three options for every couple." }, { "code": null, "e": 24725, "s": 24667, "text": "1) Nobody goes to gathering\n2) Wife alone goes\n2) Both go" }, { "code": null, "e": 24813, "s": 24725, "text": "Since there are n couples, total possible ways of gathering are 3nQuiz of this Question" }, { "code": null, "e": 24826, "s": 24813, "text": "GATE-CS-2003" }, { "code": null, "e": 24844, "s": 24826, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 24849, "s": 24844, "text": "GATE" }, { "code": null, "e": 24947, "s": 24849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24981, "s": 24947, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25015, "s": 24981, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25049, "s": 25015, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25091, "s": 25049, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25124, "s": 25091, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25166, "s": 25124, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25200, "s": 25166, "text": "GATE | GATE-CS-2000 | Question 43" }, { "code": null, "e": 25242, "s": 25200, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 25276, "s": 25242, "text": "GATE | Gate IT 2007 | Question 30" } ]
Function that returns the minimum and maximum value of an array in JavaScript
We are required to write a JavaScript function that takes in an array and return another array, the first element of this array should be the smallest element of input array and second should be the greatest element of the input array. Following is the code − Live Demo const arr = [56, 34, 23, 687, 2, 56, 567]; const findMinMax = (arr = []) => { const creds = arr.reduce((acc, val) => { let [smallest, greatest] = acc; if(val > greatest){ greatest = val; }; if(val < smallest){ smallest = val; }; return [smallest, greatest]; }, [Infinity, -Infinity]); return creds; }; console.log(findMinMax(arr)); [2, 687]
[ { "code": null, "e": 1298, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array and return another array, the first element of this array should be the smallest element of input array and second should be the greatest element of the input array." }, { "code": null, "e": 1322, "s": 1298, "text": "Following is the code −" }, { "code": null, "e": 1333, "s": 1322, "text": " Live Demo" }, { "code": null, "e": 1725, "s": 1333, "text": "const arr = [56, 34, 23, 687, 2, 56, 567];\nconst findMinMax = (arr = []) => {\n const creds = arr.reduce((acc, val) => {\n let [smallest, greatest] = acc;\n if(val > greatest){\n greatest = val;\n };\n if(val < smallest){\n smallest = val;\n };\n return [smallest, greatest];\n }, [Infinity, -Infinity]);\n return creds;\n};\nconsole.log(findMinMax(arr));" }, { "code": null, "e": 1734, "s": 1725, "text": "[2, 687]" } ]
Understanding Deep Learning Models with Integrated Gradients | by Renu Khandelwal | Towards Data Science
This post will help you to understand the two basic axioms of Integrated Gradients and how to implement Integrated Gradient using TensorFlow using a transfer learned model. What is Integrated Gradient? Integrated Gradient(IG) is an interpretability or explainability technique for deep neural networks which visualizes its input feature importance that contributes to the model's prediction Can IG be applied to only a specific use case of deep learning or only to a specific neural network architecture? Integrated Gradient(IG) computes the gradient of the model’s prediction output to its input features and requires no modification to the original deep neural network. IG can be applied to any differentiable model like image, text, or structured data. IG can be used for Understanding feature importance by extracting rules from the network Debugging deep learning models performance Identifying data skew by understanding the important features contributing to the prediction How does Integrated Gradient work? Explaining IG using a deep learning model for image classification Integrated Gradient is built on two axioms which need to be satisfied: Sensitivity andImplementation Invariance Sensitivity and Implementation Invariance To calculate the Sensitivity, we establish a Baseline image as a starting point. We then build a sequence of images which we interpolate from a baseline image to the actual image to calculate the integrated gradients. Implementation invariance is satisfied when two functionally equivalent networks have identical attributions for the same input image and the baseline image. Two networks are functionally equivalent when their outputs are equal for all inputs despite having very different implementations. Step 1: Start from the baseline where baseline can be a black image whose pixel values are all zero or an all-white image, or a random image. Baseline input is one where the prediction is neutral and is central to any explanation method and visualizing pixel feature importances. Step 2: Generate a linear interpolation between the baseline and the original image. Interpolated images are small steps(α) in the feature space between your baseline and input image and consistently increases with each interpolated image’s intensity. Step 3: Calculate gradients to measure the relationship between changes to a feature and changes in the model’s predictions. The gradient informs which pixel has the strongest effect on the models predicted class probabilities. Varying variable changes the output, and the variable will receive some attribution to help calculate the feature importances for the input image. A variable that does not affect the output gets no attribution. Step 4: Compute the numerical approximation through averaging gradients Step 5: Scale IG to the input image to ensure that the attribution values are accumulated across multiple interpolated images are all in the same units. Represent the IG on the input image with the pixel importances. How to implement an Integrated Gradient using Tensorflow? Importing required libraries import matplotlib.pylab as pltimport numpy as npimport tensorflow as tfimport tensorflow_hub as hubfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input as mobilenet_v2_preprocess_input Using MobileNetV2 as Transfer learned model on Imagenet dataset model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3), include_top=True, weights='imagenet') Loading Imagenet labels def load_imagenet_labels(file_path): labels_file = tf.keras.utils.get_file('ImageNetLabels.txt', file_path) with open(labels_file) as reader: f = reader.read() labels = f.splitlines() return np.array(labels)imagenet_labels = load_imagenet_labels('https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt') Load and preprocess images def read_image(file_name): image = tf.io.read_file(file_name) image = tf.image.decode_jpeg(image, channels=3) image = tf.image.convert_image_dtype(image, tf.float32) image = tf.image.resize_with_pad(image, target_height=224, target_width=224) return imageimg = {'Peacock':'Peacock.jpg'}img_name_tensors = {name: read_image(img_path) for (name, img_path) in img.items()} Display the original input image plt.figure(figsize=(5, 5))ax = plt.subplot(1, 1, 1)ax.imshow(img_name_tensors['Peacock'])ax.set_title("Image")ax.axis('off')plt.tight_layout() Predict the top three predictions from the model for the input image def top_k_predictions(img, k=3): image = tf.expand_dims(img, 0) predictions = model(image) probs = tf.nn.softmax(predictions, axis=-1) top_probs, top_idxs = tf.math.top_k(input=probs, k=k) top_labels = np.array(tuple(top_idxs[0]) ) return top_labels, top_probs[0]#Display the image with top 3 prediction from the modelplt.imshow(img_name_tensors['Peacock'])plt.title(name, fontweight='bold')plt.axis('off')plt.show()pred_label, pred_prob = top_k_predictions(img_name_tensors['Peacock'])for label, prob in zip(pred_label, pred_prob): print(f'{imagenet_labels[label+1]}: {prob:0.1%}') Create a black baseline image which will act as a starting point for calculating feature importance baseline = tf.zeros(shape=(224,224,3)) Generate linear interpolation between baseline and the original input image m_steps=50alphas = tf.linspace(start=0.0, stop=1.0, num=m_steps+1) def interpolate_images(baseline, image, alphas): alphas_x = alphas[:, tf.newaxis, tf.newaxis, tf.newaxis] baseline_x = tf.expand_dims(baseline, axis=0) input_x = tf.expand_dims(image, axis=0) delta = input_x - baseline_x images = baseline_x + alphas_x * delta return imagesinterpolated_images = interpolate_images( baseline=baseline, image=img_name_tensors['Peacock'], alphas=alphas) Visualizing the interpolated image fig = plt.figure(figsize=(20, 20))i = 0for alpha, image in zip(alphas[0::10], interpolated_images[0::10]): i += 1 plt.subplot(1, len(alphas[0::10]), i) plt.title(f'alpha: {alpha:.1f}') plt.imshow(image) plt.axis('off')plt.tight_layout(); Compute gradients between model outputs and interpolated inputs Computing gradients measures the relationship between changes to a feature and changes in the model’s predictions. We use tf.GradientTape to compute the gradients between the interpolated image along with the top predicted class Id indicating which pixels have the strongest influence on the models’ prediction def compute_gradients(images, target_class_idx): with tf.GradientTape() as tape: tape.watch(images) logits = model(images) probs = tf.nn.softmax(logits, axis=-1)[:, target_class_idx] return tape.gradient(probs, images)path_gradients = compute_gradients( images=interpolated_images, target_class_idx=84) Accumulate the Gradients using the Riemann Trapezoid def integral_approximation(gradients): # riemann_trapezoidal grads = (gradients[:-1] + gradients[1:]) / tf.constant(2.0) integrated_gradients = tf.math.reduce_mean(grads, axis=0) return integrated_gradients Putting all the steps in a function to calculate the integrated gradients @tf.functiondef integrated_gradients(baseline, image, target_class_idx, m_steps=50, batch_size=1): # 1. Generate alphas. alphas = tf.linspace(start=0.0, stop=1.0, num=m_steps+1)# Initialize TensorArray outside loop to collect gradients. gradient_batches = tf.TensorArray(tf.float32, size=m_steps+1) # Iterate alphas range and batch computation for speed, memory #efficiency, and scaling to larger m_steps. for alpha in tf.range(0, len(alphas), batch_size): from_ = alpha to = tf.minimum(from_ + batch_size, len(alphas)) alpha_batch = alphas[from_:to]# 2. Generate interpolated inputs between baseline and input. interpolated_path_input_batch = interpolate_images(baseline=baseline, image=image, alphas=alpha_batch)# 3. Compute gradients between model outputs and interpolated inputs. gradient_batch = compute_gradients(images=interpolated_path_input_batch, target_class_idx=target_class_idx) # Write batch indices and gradients to extend TensorArray. gradient_batches = gradient_batches.scatter(tf.range(from_, to), gradient_batch) # Stack path gradients together row-wise into single tensor. total_gradients = gradient_batches.stack()# 4. Integral approximation through averaging gradients. avg_gradients = integral_approximation(gradients=total_gradients)# 5. Scale integrated gradients with respect to input. integrated_gradients = (image - baseline) * avg_gradientsreturn integrated_gradientsig_attributions = integrated_gradients(baseline=baseline, image=img_name_tensors['Peacock'], target_class_idx=84, m_steps=283) Visualizing the attribution and the Integrated gradient to explain the prediction for the input image def plot_img_IG(baseline, image, target_class_idx, m_steps=50, cmap=None, overlay_alpha=0.4): attributions = integrated_gradients(baseline=baseline, image=image, target_class_idx=target_class_idx, m_steps=m_steps) attribution_mask = tf.reduce_sum(tf.math.abs(attributions), axis=-1) fig, axs = plt.subplots(nrows=1, ncols=2, squeeze=False, figsize= (8, 8)) axs[0, 0].set_title('Attribution mask') axs[0, 0].imshow(attribution_mask, cmap=cmap) axs[0, 0].axis('off') axs[0, 1].set_title('Overlay IG on Input image ') axs[0, 1].imshow(attribution_mask, cmap=cmap) axs[0, 1].imshow(image, alpha=overlay_alpha) axs[0, 1].axis('off') plt.tight_layout() return fig_ = plot_img_IG(image=img_name_tensors['Peacock'], baseline=baseline, target_class_idx=84, m_steps=240, cmap=plt.cm.inferno, overlay_alpha=0.4) Integrated Gradient(IG) helps you explain what a deep learning model looks at to make a prediction by highlighting the feature importances. It does this by computing the gradient of the model’s prediction output to its input features. It does not need any modification to the original deep neural network and can be applied to images, text as well as structured data. IG is based on two axioms of Sensitivity and Implementation Invariance. Axiomatic Attribution for Deep Networks
[ { "code": null, "e": 344, "s": 171, "text": "This post will help you to understand the two basic axioms of Integrated Gradients and how to implement Integrated Gradient using TensorFlow using a transfer learned model." }, { "code": null, "e": 373, "s": 344, "text": "What is Integrated Gradient?" }, { "code": null, "e": 562, "s": 373, "text": "Integrated Gradient(IG) is an interpretability or explainability technique for deep neural networks which visualizes its input feature importance that contributes to the model's prediction" }, { "code": null, "e": 676, "s": 562, "text": "Can IG be applied to only a specific use case of deep learning or only to a specific neural network architecture?" }, { "code": null, "e": 843, "s": 676, "text": "Integrated Gradient(IG) computes the gradient of the model’s prediction output to its input features and requires no modification to the original deep neural network." }, { "code": null, "e": 927, "s": 843, "text": "IG can be applied to any differentiable model like image, text, or structured data." }, { "code": null, "e": 946, "s": 927, "text": "IG can be used for" }, { "code": null, "e": 1016, "s": 946, "text": "Understanding feature importance by extracting rules from the network" }, { "code": null, "e": 1059, "s": 1016, "text": "Debugging deep learning models performance" }, { "code": null, "e": 1152, "s": 1059, "text": "Identifying data skew by understanding the important features contributing to the prediction" }, { "code": null, "e": 1187, "s": 1152, "text": "How does Integrated Gradient work?" }, { "code": null, "e": 1254, "s": 1187, "text": "Explaining IG using a deep learning model for image classification" }, { "code": null, "e": 1325, "s": 1254, "text": "Integrated Gradient is built on two axioms which need to be satisfied:" }, { "code": null, "e": 1366, "s": 1325, "text": "Sensitivity andImplementation Invariance" }, { "code": null, "e": 1382, "s": 1366, "text": "Sensitivity and" }, { "code": null, "e": 1408, "s": 1382, "text": "Implementation Invariance" }, { "code": null, "e": 1626, "s": 1408, "text": "To calculate the Sensitivity, we establish a Baseline image as a starting point. We then build a sequence of images which we interpolate from a baseline image to the actual image to calculate the integrated gradients." }, { "code": null, "e": 1784, "s": 1626, "text": "Implementation invariance is satisfied when two functionally equivalent networks have identical attributions for the same input image and the baseline image." }, { "code": null, "e": 1916, "s": 1784, "text": "Two networks are functionally equivalent when their outputs are equal for all inputs despite having very different implementations." }, { "code": null, "e": 2196, "s": 1916, "text": "Step 1: Start from the baseline where baseline can be a black image whose pixel values are all zero or an all-white image, or a random image. Baseline input is one where the prediction is neutral and is central to any explanation method and visualizing pixel feature importances." }, { "code": null, "e": 2448, "s": 2196, "text": "Step 2: Generate a linear interpolation between the baseline and the original image. Interpolated images are small steps(α) in the feature space between your baseline and input image and consistently increases with each interpolated image’s intensity." }, { "code": null, "e": 2573, "s": 2448, "text": "Step 3: Calculate gradients to measure the relationship between changes to a feature and changes in the model’s predictions." }, { "code": null, "e": 2676, "s": 2573, "text": "The gradient informs which pixel has the strongest effect on the models predicted class probabilities." }, { "code": null, "e": 2887, "s": 2676, "text": "Varying variable changes the output, and the variable will receive some attribution to help calculate the feature importances for the input image. A variable that does not affect the output gets no attribution." }, { "code": null, "e": 2959, "s": 2887, "text": "Step 4: Compute the numerical approximation through averaging gradients" }, { "code": null, "e": 3176, "s": 2959, "text": "Step 5: Scale IG to the input image to ensure that the attribution values are accumulated across multiple interpolated images are all in the same units. Represent the IG on the input image with the pixel importances." }, { "code": null, "e": 3234, "s": 3176, "text": "How to implement an Integrated Gradient using Tensorflow?" }, { "code": null, "e": 3263, "s": 3234, "text": "Importing required libraries" }, { "code": null, "e": 3467, "s": 3263, "text": "import matplotlib.pylab as pltimport numpy as npimport tensorflow as tfimport tensorflow_hub as hubfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input as mobilenet_v2_preprocess_input" }, { "code": null, "e": 3531, "s": 3467, "text": "Using MobileNetV2 as Transfer learned model on Imagenet dataset" }, { "code": null, "e": 3728, "s": 3531, "text": "model = tf.keras.applications.MobileNetV2(input_shape=(224,224,3), include_top=True, weights='imagenet')" }, { "code": null, "e": 3752, "s": 3728, "text": "Loading Imagenet labels" }, { "code": null, "e": 4089, "s": 3752, "text": "def load_imagenet_labels(file_path): labels_file = tf.keras.utils.get_file('ImageNetLabels.txt', file_path) with open(labels_file) as reader: f = reader.read() labels = f.splitlines() return np.array(labels)imagenet_labels = load_imagenet_labels('https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')" }, { "code": null, "e": 4116, "s": 4089, "text": "Load and preprocess images" }, { "code": null, "e": 4493, "s": 4116, "text": "def read_image(file_name): image = tf.io.read_file(file_name) image = tf.image.decode_jpeg(image, channels=3) image = tf.image.convert_image_dtype(image, tf.float32) image = tf.image.resize_with_pad(image, target_height=224, target_width=224) return imageimg = {'Peacock':'Peacock.jpg'}img_name_tensors = {name: read_image(img_path) for (name, img_path) in img.items()}" }, { "code": null, "e": 4526, "s": 4493, "text": "Display the original input image" }, { "code": null, "e": 4669, "s": 4526, "text": "plt.figure(figsize=(5, 5))ax = plt.subplot(1, 1, 1)ax.imshow(img_name_tensors['Peacock'])ax.set_title(\"Image\")ax.axis('off')plt.tight_layout()" }, { "code": null, "e": 4738, "s": 4669, "text": "Predict the top three predictions from the model for the input image" }, { "code": null, "e": 5330, "s": 4738, "text": "def top_k_predictions(img, k=3): image = tf.expand_dims(img, 0) predictions = model(image) probs = tf.nn.softmax(predictions, axis=-1) top_probs, top_idxs = tf.math.top_k(input=probs, k=k) top_labels = np.array(tuple(top_idxs[0]) ) return top_labels, top_probs[0]#Display the image with top 3 prediction from the modelplt.imshow(img_name_tensors['Peacock'])plt.title(name, fontweight='bold')plt.axis('off')plt.show()pred_label, pred_prob = top_k_predictions(img_name_tensors['Peacock'])for label, prob in zip(pred_label, pred_prob): print(f'{imagenet_labels[label+1]}: {prob:0.1%}')" }, { "code": null, "e": 5430, "s": 5330, "text": "Create a black baseline image which will act as a starting point for calculating feature importance" }, { "code": null, "e": 5469, "s": 5430, "text": "baseline = tf.zeros(shape=(224,224,3))" }, { "code": null, "e": 5545, "s": 5469, "text": "Generate linear interpolation between baseline and the original input image" }, { "code": null, "e": 6056, "s": 5545, "text": "m_steps=50alphas = tf.linspace(start=0.0, stop=1.0, num=m_steps+1) def interpolate_images(baseline, image, alphas): alphas_x = alphas[:, tf.newaxis, tf.newaxis, tf.newaxis] baseline_x = tf.expand_dims(baseline, axis=0) input_x = tf.expand_dims(image, axis=0) delta = input_x - baseline_x images = baseline_x + alphas_x * delta return imagesinterpolated_images = interpolate_images( baseline=baseline, image=img_name_tensors['Peacock'], alphas=alphas)" }, { "code": null, "e": 6091, "s": 6056, "text": "Visualizing the interpolated image" }, { "code": null, "e": 6334, "s": 6091, "text": "fig = plt.figure(figsize=(20, 20))i = 0for alpha, image in zip(alphas[0::10], interpolated_images[0::10]): i += 1 plt.subplot(1, len(alphas[0::10]), i) plt.title(f'alpha: {alpha:.1f}') plt.imshow(image) plt.axis('off')plt.tight_layout();" }, { "code": null, "e": 6398, "s": 6334, "text": "Compute gradients between model outputs and interpolated inputs" }, { "code": null, "e": 6709, "s": 6398, "text": "Computing gradients measures the relationship between changes to a feature and changes in the model’s predictions. We use tf.GradientTape to compute the gradients between the interpolated image along with the top predicted class Id indicating which pixels have the strongest influence on the models’ prediction" }, { "code": null, "e": 7029, "s": 6709, "text": "def compute_gradients(images, target_class_idx): with tf.GradientTape() as tape: tape.watch(images) logits = model(images) probs = tf.nn.softmax(logits, axis=-1)[:, target_class_idx] return tape.gradient(probs, images)path_gradients = compute_gradients( images=interpolated_images, target_class_idx=84)" }, { "code": null, "e": 7082, "s": 7029, "text": "Accumulate the Gradients using the Riemann Trapezoid" }, { "code": null, "e": 7293, "s": 7082, "text": "def integral_approximation(gradients): # riemann_trapezoidal grads = (gradients[:-1] + gradients[1:]) / tf.constant(2.0) integrated_gradients = tf.math.reduce_mean(grads, axis=0) return integrated_gradients" }, { "code": null, "e": 7367, "s": 7293, "text": "Putting all the steps in a function to calculate the integrated gradients" }, { "code": null, "e": 9294, "s": 7367, "text": "@tf.functiondef integrated_gradients(baseline, image, target_class_idx, m_steps=50, batch_size=1): # 1. Generate alphas. alphas = tf.linspace(start=0.0, stop=1.0, num=m_steps+1)# Initialize TensorArray outside loop to collect gradients. gradient_batches = tf.TensorArray(tf.float32, size=m_steps+1) # Iterate alphas range and batch computation for speed, memory #efficiency, and scaling to larger m_steps. for alpha in tf.range(0, len(alphas), batch_size): from_ = alpha to = tf.minimum(from_ + batch_size, len(alphas)) alpha_batch = alphas[from_:to]# 2. Generate interpolated inputs between baseline and input. interpolated_path_input_batch = interpolate_images(baseline=baseline, image=image, alphas=alpha_batch)# 3. Compute gradients between model outputs and interpolated inputs. gradient_batch = compute_gradients(images=interpolated_path_input_batch, target_class_idx=target_class_idx) # Write batch indices and gradients to extend TensorArray. gradient_batches = gradient_batches.scatter(tf.range(from_, to), gradient_batch) # Stack path gradients together row-wise into single tensor. total_gradients = gradient_batches.stack()# 4. Integral approximation through averaging gradients. avg_gradients = integral_approximation(gradients=total_gradients)# 5. Scale integrated gradients with respect to input. integrated_gradients = (image - baseline) * avg_gradientsreturn integrated_gradientsig_attributions = integrated_gradients(baseline=baseline, image=img_name_tensors['Peacock'], target_class_idx=84, m_steps=283)" }, { "code": null, "e": 9396, "s": 9294, "text": "Visualizing the attribution and the Integrated gradient to explain the prediction for the input image" }, { "code": null, "e": 10576, "s": 9396, "text": "def plot_img_IG(baseline, image, target_class_idx, m_steps=50, cmap=None, overlay_alpha=0.4): attributions = integrated_gradients(baseline=baseline, image=image, target_class_idx=target_class_idx, m_steps=m_steps) attribution_mask = tf.reduce_sum(tf.math.abs(attributions), axis=-1) fig, axs = plt.subplots(nrows=1, ncols=2, squeeze=False, figsize= (8, 8)) axs[0, 0].set_title('Attribution mask') axs[0, 0].imshow(attribution_mask, cmap=cmap) axs[0, 0].axis('off') axs[0, 1].set_title('Overlay IG on Input image ') axs[0, 1].imshow(attribution_mask, cmap=cmap) axs[0, 1].imshow(image, alpha=overlay_alpha) axs[0, 1].axis('off') plt.tight_layout() return fig_ = plot_img_IG(image=img_name_tensors['Peacock'], baseline=baseline, target_class_idx=84, m_steps=240, cmap=plt.cm.inferno, overlay_alpha=0.4)" }, { "code": null, "e": 11016, "s": 10576, "text": "Integrated Gradient(IG) helps you explain what a deep learning model looks at to make a prediction by highlighting the feature importances. It does this by computing the gradient of the model’s prediction output to its input features. It does not need any modification to the original deep neural network and can be applied to images, text as well as structured data. IG is based on two axioms of Sensitivity and Implementation Invariance." } ]
Learn Web Scraping using Python in under 5 minutes | by Kaustumbh Jaiswal | Towards Data Science
Web scraping is harvesting or extracting desired information from a webpage. For web scraping we are going to use the very popular Python library called BeautifulSoup. For web scraping you first need to have some basic knowledge about the HTML tags. Some of the tags used in HTML are shown below. For more information on HTML tags please refer to https://www.w3schools.com/tags/. To get started with scraping make sure you have Python (version 3+) and BeautifulSoup installed on your system. If you don’t have BeautifulSoup installed, then just type the following command in your Terminal/Command Prompt- pip install beautifulsoup4 The first step in scraping is to select the website you wish to scrape data from and inspect it. In this tutorial we will try to scrape information from this article published on BBC. To inspect a website right click anywhere on the page and choose ‘Inspect Element’ / ‘View Page Source’ . To view the location of a particular entity on a webpage like text or image, select that portion on the webpage and then right click and choose ‘Inspect Element’ / ‘View Page Source’. After you inspect a webpage, a window will pop up showing you the exact location of the selected content in HTML code of the page as shown below. Since our aim is to extract the entire body of the article, it is important to make a note of the <div> tag under which the entire text of the article is enclosed. Now let’s take a closer look at the webpage and identify the <div> tag. As we can see, <div class=”story-body sp-story-body gel-body-copy”> is the tag we are looking for. Now, we have all we need so let’s straight dive into the code and do some scraping! Now we can begin parsing the webpage and searching for the specific elements we need using BeautifulSoup. For connecting to the website and getting the HTML we will use Python’s urllib. Let us import the required libraries- from urllib.request import urlopenfrom bs4 import BeautifulSoup Get the url- url = "https://www.bbc.com/sport/football/46897172" Connecting to the website- # We use try-except incase the request was unsuccessful because of # wrong URLtry: page = urlopen(url)except: print("Error opening the URL") Create a BeautifulSoup object for parsing- soup = BeautifulSoup(page, 'html.parser') We now use BeautifulSoup’s soup.find() method to search for the tag <div class=”story-body sp-story-body gel-body-copy”> which contains the text of the article we are interested in. content = soup.find('div', {"class": "story-body sp-story-body gel- body-copy"}) We now iterate through content to find all the <p> (paragraph) tags in it to get the entire body of the article. article = ''for i in content.findAll('p'): article = article + ' ' + i.text We can save the information we scraped in a .txt or .csv file. with open('scraped_text.txt', 'w') as file: file.write(article) The entire code- Output- Cristiano Ronaldo’s header was enough for Juventus to beat AC Milan and claim a record eighth Supercoppa Italiana in a game played in Jeddah, Saudi Arabia. The Portugal forward nodded in Miralem Pjanic’s lofted pass in the second half to settle a meeting between Italian football’s two most successful clubs. It was Ronaldo’s 16th goal of the season for the Serie A leaders. Patrick Cutrone hit the crossbar for Milan, who had Ivorian midfielder Franck Kessie sent off. Gonzalo Higuain, reportedly the subject of interest from Chelsea, was introduced as a substitute by Milan boss Gennaro Gattuso in Italy’s version of the Community Shield. But the 31-year-old Argentina forward, who is currently on loan from Juventus, was unable to deliver an equalising goal for the Rossoneri, who were beaten 4–0 by Juve in the Coppa Italia final in May. Web scraping can be really useful when you want to gather data from multiple sources for analysis or for research. BeautifulSoup is an excellent web scraping library which can be used for small projects but for large projects other libraries like Scrapy are more suitable. Hope you have understood the concept of web scraping and can now scrape data from different websites as per your need. Thanks for reading. Happy scraping! 😊
[ { "code": null, "e": 248, "s": 171, "text": "Web scraping is harvesting or extracting desired information from a webpage." }, { "code": null, "e": 468, "s": 248, "text": "For web scraping we are going to use the very popular Python library called BeautifulSoup. For web scraping you first need to have some basic knowledge about the HTML tags. Some of the tags used in HTML are shown below." }, { "code": null, "e": 551, "s": 468, "text": "For more information on HTML tags please refer to https://www.w3schools.com/tags/." }, { "code": null, "e": 776, "s": 551, "text": "To get started with scraping make sure you have Python (version 3+) and BeautifulSoup installed on your system. If you don’t have BeautifulSoup installed, then just type the following command in your Terminal/Command Prompt-" }, { "code": null, "e": 803, "s": 776, "text": "pip install beautifulsoup4" }, { "code": null, "e": 987, "s": 803, "text": "The first step in scraping is to select the website you wish to scrape data from and inspect it. In this tutorial we will try to scrape information from this article published on BBC." }, { "code": null, "e": 1277, "s": 987, "text": "To inspect a website right click anywhere on the page and choose ‘Inspect Element’ / ‘View Page Source’ . To view the location of a particular entity on a webpage like text or image, select that portion on the webpage and then right click and choose ‘Inspect Element’ / ‘View Page Source’." }, { "code": null, "e": 1423, "s": 1277, "text": "After you inspect a webpage, a window will pop up showing you the exact location of the selected content in HTML code of the page as shown below." }, { "code": null, "e": 1659, "s": 1423, "text": "Since our aim is to extract the entire body of the article, it is important to make a note of the <div> tag under which the entire text of the article is enclosed. Now let’s take a closer look at the webpage and identify the <div> tag." }, { "code": null, "e": 1842, "s": 1659, "text": "As we can see, <div class=”story-body sp-story-body gel-body-copy”> is the tag we are looking for. Now, we have all we need so let’s straight dive into the code and do some scraping!" }, { "code": null, "e": 2066, "s": 1842, "text": "Now we can begin parsing the webpage and searching for the specific elements we need using BeautifulSoup. For connecting to the website and getting the HTML we will use Python’s urllib. Let us import the required libraries-" }, { "code": null, "e": 2130, "s": 2066, "text": "from urllib.request import urlopenfrom bs4 import BeautifulSoup" }, { "code": null, "e": 2143, "s": 2130, "text": "Get the url-" }, { "code": null, "e": 2195, "s": 2143, "text": "url = \"https://www.bbc.com/sport/football/46897172\"" }, { "code": null, "e": 2222, "s": 2195, "text": "Connecting to the website-" }, { "code": null, "e": 2367, "s": 2222, "text": "# We use try-except incase the request was unsuccessful because of # wrong URLtry: page = urlopen(url)except: print(\"Error opening the URL\")" }, { "code": null, "e": 2410, "s": 2367, "text": "Create a BeautifulSoup object for parsing-" }, { "code": null, "e": 2452, "s": 2410, "text": "soup = BeautifulSoup(page, 'html.parser')" }, { "code": null, "e": 2634, "s": 2452, "text": "We now use BeautifulSoup’s soup.find() method to search for the tag <div class=”story-body sp-story-body gel-body-copy”> which contains the text of the article we are interested in." }, { "code": null, "e": 2720, "s": 2634, "text": "content = soup.find('div', {\"class\": \"story-body sp-story-body gel- body-copy\"})" }, { "code": null, "e": 2833, "s": 2720, "text": "We now iterate through content to find all the <p> (paragraph) tags in it to get the entire body of the article." }, { "code": null, "e": 2913, "s": 2833, "text": "article = ''for i in content.findAll('p'): article = article + ' ' + i.text" }, { "code": null, "e": 2976, "s": 2913, "text": "We can save the information we scraped in a .txt or .csv file." }, { "code": null, "e": 3043, "s": 2976, "text": "with open('scraped_text.txt', 'w') as file: file.write(article)" }, { "code": null, "e": 3060, "s": 3043, "text": "The entire code-" }, { "code": null, "e": 3068, "s": 3060, "text": "Output-" }, { "code": null, "e": 3911, "s": 3068, "text": " Cristiano Ronaldo’s header was enough for Juventus to beat AC Milan and claim a record eighth Supercoppa Italiana in a game played in Jeddah, Saudi Arabia. The Portugal forward nodded in Miralem Pjanic’s lofted pass in the second half to settle a meeting between Italian football’s two most successful clubs. It was Ronaldo’s 16th goal of the season for the Serie A leaders. Patrick Cutrone hit the crossbar for Milan, who had Ivorian midfielder Franck Kessie sent off. Gonzalo Higuain, reportedly the subject of interest from Chelsea, was introduced as a substitute by Milan boss Gennaro Gattuso in Italy’s version of the Community Shield. But the 31-year-old Argentina forward, who is currently on loan from Juventus, was unable to deliver an equalising goal for the Rossoneri, who were beaten 4–0 by Juve in the Coppa Italia final in May." }, { "code": null, "e": 4026, "s": 3911, "text": "Web scraping can be really useful when you want to gather data from multiple sources for analysis or for research." }, { "code": null, "e": 4184, "s": 4026, "text": "BeautifulSoup is an excellent web scraping library which can be used for small projects but for large projects other libraries like Scrapy are more suitable." }, { "code": null, "e": 4303, "s": 4184, "text": "Hope you have understood the concept of web scraping and can now scrape data from different websites as per your need." } ]
Winner of an election | Practice | GeeksforGeeks
Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. The task is to print the name of candidates received maximum vote. If there is tie, print lexicographically smaller name. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains an Integer N denoting number of votes and the second line contains N space separated strings. Output: For each test case, print the winner of election in new line. Constraints: 1<=T<=100 2<=N<=105 1<=|String length|<=20 Example: Input: 2 6 aaa bbb ccc bbb aaa aaa 7 geeks for geeks for geeks aaa aaa Output: aaa geeks 0 rathoredivya1502 months ago #include <bits/stdc++.h>using namespace std; int main() { int t; cin>>t; while(t--) {string st; map<string,int>mp; int n; cin>>n; string s[n]; for(int i=0;i<n;i++) {string str; cin>>str; mp[str]++; }int mx=INT_MIN; for(auto a:mp) { if(mx<a.second) { mx=a.second; st=a.first; } } cout<<st<<"\n"; }//codereturn 0;} 0 snipperwolf3 months ago for _ in range(int(input())): n=int(input()) n1=input() mp={} for i in n1.split(' '): if i not in mp: mp[i]=1 else: mp[i]+=1 n=max(mp.values()) l=[] for i,v in mp.items(): if v==n: l.append(i) if len(l)==1: print(l[0]) else: print(min(l)) 0 kashyapjhon3 months ago C++ Solution: #include <bits/stdc++.h>using namespace std;int main() {//codeint t;cin>>t;// cin.ignore();while(t--){ map<string,int> s; int n; cin>>n; for(int i=0;i<n;i++){ string str; cin>>str; s[str]++; } int t=INT_MIN; for(auto it=s.begin();it!=s.end();it++){ if(t<it->second){ t=it->second; } } auto ans=s.begin(); for(auto it=s.begin();it!=s.end();it++){ if(it->second==t){ ans=it; break; } } cout<<ans->first<<endl;}return 0;} +1 badgujarsachin835 months ago #include<iostream> #include<map> using namespace std; int main() { //code int t; cin>>t; while(t--){ int n; cin>>n; string arr[100000]; for(int i=0;i<n;i++){ cin>>arr[i]; } map<string,int> mp; int maxi=0; string name; for(int i=0;i<n;i++){ mp[arr[i]]++; maxi=max(maxi,mp[arr[i]]); } for(auto it:mp){ if(it.second==maxi ){ if(name.empty()||it.first<name){ name=it.first; } } } cout<<name<<endl; } return 0; } 0 msaravanansara4746 months ago for _ in range(int(input())): input() v=input().split() dictorial={} for x in v: if x in dictorial: dictorial[x]+=1 else: dictorial[x]=1 b=max(dictorial.values()) for x in sorted(dictorial.keys()): if dictorial[x]==b: print(x) break -1 aradhyakanthofficial6 months ago Solution in Python: #function define def task(l): l2=list(set(l)) dict1=dict() for i in l2: dict1[i]=l.count(i) c=dict1.items() d=sorted(c,key=lambda x:x[1],reverse=True) e=[d[i][0] for i in range(len(d)) if d[i][1]==d[0][1]] e.sort() print(e[0]) #Driver code t=int(input())while(t>0): n=int(input()) l=input().split() l=l[:n] task(l) t-=1 -2 imranwahid7 months ago Easy C++ solution https://ide.geeksforgeeks.org/exe78nbVCO 0 Mohit Kesharwani7 months ago Mohit Kesharwani #include<iostream>#include <bits stdc++.h="">using namespace std;int main() {//code//mohit.ke000int t;cin>>t;while(t--){ int n; cin>>n; string s[n]; for(int i=0; i<n; i++)="" {="" cin="">>s[i]; } map<string,int>mp; for(int i=0;i<n; i++)="" {="" mp.insert({s[i],i});="" mp[s[i]]++;="" }="" map<string,int="">::iterator it; int max=0; for(it=mp.begin(); it!=mp.end(); it++) { // cout<<it->first<<" "<<it->second<<endl; if(max="" <="" it-="">second) { max=it->second; } } for(it=mp.begin(); it!=mp.end(); it++) { if(max==it->second) { cout<<it->first; break; } } cout<<endl; }="" return="" 0;="" }=""> 0 MD DANISH_IT_2nd_A_249 months ago MD DANISH_IT_2nd_A_24 #include <bits stdc++.h="">using namespace std; int main() { int t; cin>>t; while(t--){ int n; cin>>n; string s; map<string, int="">m; for(int i=0;i<n;i++){ cin="">>s; m[s]++; s.clear(); } int p=INT_MIN; string ans; for(auto it:m){ if(it.second > p){ p = it.second; ans = it.first; } } cout<<ans<<endl; }=""> 0 Laxman Kumar vashist9 months ago Laxman Kumar vashist JAVA Solution ... https://uploads.disquscdn.c... 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": 483, "s": 238, "text": "Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. The task is to print the name of candidates received maximum vote. If there is tie, print lexicographically smaller name." }, { "code": null, "e": 769, "s": 483, "text": "Input:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains an Integer N denoting number of votes and the second line contains N space separated strings. " }, { "code": null, "e": 839, "s": 769, "text": "Output:\nFor each test case, print the winner of election in new line." }, { "code": null, "e": 895, "s": 839, "text": "Constraints:\n1<=T<=100\n2<=N<=105\n1<=|String length|<=20" }, { "code": null, "e": 976, "s": 895, "text": "Example:\nInput:\n2\n6\naaa bbb ccc bbb aaa aaa\n7\ngeeks for geeks for geeks aaa aaa" }, { "code": null, "e": 994, "s": 976, "text": "Output:\naaa\ngeeks" }, { "code": null, "e": 996, "s": 994, "text": "0" }, { "code": null, "e": 1024, "s": 996, "text": "rathoredivya1502 months ago" }, { "code": null, "e": 1069, "s": 1024, "text": "#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 1487, "s": 1069, "text": "int main() { int t; cin>>t; while(t--) {string st; map<string,int>mp; int n; cin>>n; string s[n]; for(int i=0;i<n;i++) {string str; cin>>str; mp[str]++; }int mx=INT_MIN; for(auto a:mp) { if(mx<a.second) { mx=a.second; st=a.first; } } cout<<st<<\"\\n\"; }//codereturn 0;}" }, { "code": null, "e": 1489, "s": 1487, "text": "0" }, { "code": null, "e": 1513, "s": 1489, "text": "snipperwolf3 months ago" }, { "code": null, "e": 1830, "s": 1513, "text": "for _ in range(int(input())): n=int(input()) n1=input() mp={} for i in n1.split(' '): if i not in mp: mp[i]=1 else: mp[i]+=1 n=max(mp.values()) l=[] for i,v in mp.items(): if v==n: l.append(i) if len(l)==1: print(l[0]) else: print(min(l))" }, { "code": null, "e": 1832, "s": 1830, "text": "0" }, { "code": null, "e": 1856, "s": 1832, "text": "kashyapjhon3 months ago" }, { "code": null, "e": 1870, "s": 1856, "text": "C++ Solution:" }, { "code": null, "e": 2407, "s": 1870, "text": "#include <bits/stdc++.h>using namespace std;int main() {//codeint t;cin>>t;// cin.ignore();while(t--){ map<string,int> s; int n; cin>>n; for(int i=0;i<n;i++){ string str; cin>>str; s[str]++; } int t=INT_MIN; for(auto it=s.begin();it!=s.end();it++){ if(t<it->second){ t=it->second; } } auto ans=s.begin(); for(auto it=s.begin();it!=s.end();it++){ if(it->second==t){ ans=it; break; } } cout<<ans->first<<endl;}return 0;}" }, { "code": null, "e": 2410, "s": 2407, "text": "+1" }, { "code": null, "e": 2439, "s": 2410, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 3006, "s": 2439, "text": "#include<iostream>\n#include<map>\nusing namespace std;\nint main()\n {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t int n;\n\t cin>>n;\n\t string arr[100000];\n\t for(int i=0;i<n;i++){\n\t cin>>arr[i];\n\t }\n\t map<string,int> mp;\n\t int maxi=0;\n\t string name;\n for(int i=0;i<n;i++){\n mp[arr[i]]++;\n maxi=max(maxi,mp[arr[i]]);\n }\n\t for(auto it:mp){\n\t if(it.second==maxi ){\n\t if(name.empty()||it.first<name){\n\t name=it.first;\n\t }\n\t }\n\t }\n\t cout<<name<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 3008, "s": 3006, "text": "0" }, { "code": null, "e": 3038, "s": 3008, "text": "msaravanansara4746 months ago" }, { "code": null, "e": 3367, "s": 3038, "text": "for _ in range(int(input())):\n input()\n v=input().split()\n dictorial={}\n for x in v:\n if x in dictorial:\n dictorial[x]+=1\n else:\n dictorial[x]=1\n b=max(dictorial.values())\n for x in sorted(dictorial.keys()):\n if dictorial[x]==b:\n print(x)\n break" }, { "code": null, "e": 3370, "s": 3367, "text": "-1" }, { "code": null, "e": 3403, "s": 3370, "text": "aradhyakanthofficial6 months ago" }, { "code": null, "e": 3423, "s": 3403, "text": "Solution in Python:" }, { "code": null, "e": 3440, "s": 3423, "text": "#function define" }, { "code": null, "e": 3672, "s": 3440, "text": "def task(l): l2=list(set(l)) dict1=dict() for i in l2: dict1[i]=l.count(i) c=dict1.items() d=sorted(c,key=lambda x:x[1],reverse=True) e=[d[i][0] for i in range(len(d)) if d[i][1]==d[0][1]] e.sort() print(e[0])" }, { "code": null, "e": 3697, "s": 3674, "text": "#Driver code " }, { "code": null, "e": 3787, "s": 3697, "text": "t=int(input())while(t>0): n=int(input()) l=input().split() l=l[:n] task(l) t-=1" }, { "code": null, "e": 3790, "s": 3787, "text": "-2" }, { "code": null, "e": 3813, "s": 3790, "text": "imranwahid7 months ago" }, { "code": null, "e": 3831, "s": 3813, "text": "Easy C++ solution" }, { "code": null, "e": 3872, "s": 3831, "text": "https://ide.geeksforgeeks.org/exe78nbVCO" }, { "code": null, "e": 3874, "s": 3872, "text": "0" }, { "code": null, "e": 3903, "s": 3874, "text": "Mohit Kesharwani7 months ago" }, { "code": null, "e": 3920, "s": 3903, "text": "Mohit Kesharwani" }, { "code": null, "e": 4131, "s": 3920, "text": "#include<iostream>#include <bits stdc++.h=\"\">using namespace std;int main() {//code//mohit.ke000int t;cin>>t;while(t--){ int n; cin>>n; string s[n]; for(int i=0; i<n; i++)=\"\" {=\"\" cin=\"\">>s[i]; }" }, { "code": null, "e": 4674, "s": 4131, "text": " map<string,int>mp; for(int i=0;i<n; i++)=\"\" {=\"\" mp.insert({s[i],i});=\"\" mp[s[i]]++;=\"\" }=\"\" map<string,int=\"\">::iterator it; int max=0; for(it=mp.begin(); it!=mp.end(); it++) { // cout<<it->first<<\" \"<<it->second<<endl; if(max=\"\" <=\"\" it-=\"\">second) { max=it->second; } } for(it=mp.begin(); it!=mp.end(); it++) { if(max==it->second) { cout<<it->first; break; } }" }, { "code": null, "e": 4722, "s": 4674, "text": " cout<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 4724, "s": 4722, "text": "0" }, { "code": null, "e": 4758, "s": 4724, "text": "MD DANISH_IT_2nd_A_249 months ago" }, { "code": null, "e": 4780, "s": 4758, "text": "MD DANISH_IT_2nd_A_24" }, { "code": null, "e": 4828, "s": 4780, "text": "#include <bits stdc++.h=\"\">using namespace std;" }, { "code": null, "e": 5249, "s": 4828, "text": "int main() { int t; cin>>t; while(t--){ int n; cin>>n; string s; map<string, int=\"\">m; for(int i=0;i<n;i++){ cin=\"\">>s; m[s]++; s.clear(); } int p=INT_MIN; string ans; for(auto it:m){ if(it.second > p){ p = it.second; ans = it.first; } } cout<<ans<<endl; }=\"\">" }, { "code": null, "e": 5251, "s": 5249, "text": "0" }, { "code": null, "e": 5284, "s": 5251, "text": "Laxman Kumar vashist9 months ago" }, { "code": null, "e": 5305, "s": 5284, "text": "Laxman Kumar vashist" }, { "code": null, "e": 5354, "s": 5305, "text": "JAVA Solution ... https://uploads.disquscdn.c..." }, { "code": null, "e": 5500, "s": 5354, "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": 5536, "s": 5500, "text": " Login to access your submissions. " }, { "code": null, "e": 5546, "s": 5536, "text": "\nProblem\n" }, { "code": null, "e": 5556, "s": 5546, "text": "\nContest\n" }, { "code": null, "e": 5619, "s": 5556, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5767, "s": 5619, "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": 5975, "s": 5767, "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": 6081, "s": 5975, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Counting Chars in EditText Changed Listener in Android?
Some situations, we have to restrict an edit text for some characters. To solve this situation, in this example demonstrate how to Counting Chars in Edit Text Changed Listener. 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:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:background = "#33FFFF00" android:orientation = "vertical"> <EditText android:id = "@+id/text" android:textSize = "18sp" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken one edit text. It going to check the length of the entered characters, if it exceeds 5 then it shows an error message. Step 3 - Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.VibrationEffect; import android.os.Vibrator; import android.support.annotation.RequiresApi; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; EditText text; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); text = findViewById(R.id.text); text.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if(s.toString().length()>5) { text.setError("It allows only 5 character"); }else{ text.setError(null); } } }); } } In the above code, we have used text changed listener, after changed text we are validating text as shown below - text.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if(s.toString().length()>5) { text.setError("It allows only 5 character"); }else{ text.setError(null); } } }); Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen - When you enter 5 characters, it does not show any error. if you enter more than 5 characters. it will show an error as shown below - Click here to download the project code
[ { "code": null, "e": 1239, "s": 1062, "text": "Some situations, we have to restrict an edit text for some characters. To solve this situation, in this example demonstrate how to Counting Chars in Edit Text Changed Listener." }, { "code": null, "e": 1368, "s": 1239, "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": 1433, "s": 1368, "text": "Step 2 - Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2038, "s": 1433, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:background = \"#33FFFF00\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/text\"\n android:textSize = \"18sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2190, "s": 2038, "text": "In the above code, we have taken one edit text. It going to check the length of the entered characters, if it exceeds 5 then it shows an error message." }, { "code": null, "e": 2247, "s": 2190, "text": "Step 3 - Add the following code to src/MainActivity.java" }, { "code": null, "e": 3833, "s": 2247, "text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.VibrationEffect;\nimport android.os.Vibrator;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.util.Log;\nimport android.view.KeyEvent;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n EditText text;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n text = findViewById(R.id.text);\n text.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n @Override\n public void afterTextChanged(Editable s) {\n if(s.toString().length()>5) {\n text.setError(\"It allows only 5 character\");\n }else{\n text.setError(null);\n }\n }\n });\n }\n}" }, { "code": null, "e": 3947, "s": 3833, "text": "In the above code, we have used text changed listener, after changed text we are validating text as shown below -" }, { "code": null, "e": 4396, "s": 3947, "text": "text.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n @Override\n public void afterTextChanged(Editable s) {\n if(s.toString().length()>5) {\n text.setError(\"It allows only 5 character\");\n }else{\n text.setError(null);\n }\n}\n});" }, { "code": null, "e": 4743, "s": 4396, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click 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": 4876, "s": 4743, "text": "When you enter 5 characters, it does not show any error. if you enter more than 5 characters. it will show an error as shown below -" }, { "code": null, "e": 4916, "s": 4876, "text": "Click here to download the project code" } ]