title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Ext.js - Ext.panel.Panel Container
Ext.panel.Panel: It is the basic container which allows to add items in a normal panel. Following is the simple syntax to create Ext.panel.Panel container. Ext.create('Ext.panel.Panel', { items: [child1, child2] // this way we can add different child elements to the container as container items. }); Following is a simple example showing Ext.panel.Panel Container. <!DOCTYPE html> <html> <head> <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" rel = "stylesheet" /> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> <script type = "text/javascript"> Ext.onReady(function () { var childPanel1 = Ext.create('Ext.Panel', { html: 'First Panel' }); var childPanel2 = Ext.create('Ext.Panel', { html: 'Another Panel' }); Ext.create('Ext.panel.Panel', { renderTo: Ext.getBody(), width: 100, height : 100, border : true, frame : true, items: [ childPanel1, childPanel2 ] }); }); </script> </head> <body> </body> </html> The above program will produce the following result βˆ’ Print Add Notes Bookmark this page
[ { "code": null, "e": 2111, "s": 2023, "text": "Ext.panel.Panel: It is the basic container which allows to add items in a normal panel." }, { "code": null, "e": 2179, "s": 2111, "text": "Following is the simple syntax to create Ext.panel.Panel container." }, { "code": null, "e": 2334, "s": 2179, "text": "Ext.create('Ext.panel.Panel', {\n items: [child1, child2] \n // this way we can add different child elements to the container as container items.\n});\n" }, { "code": null, "e": 2399, "s": 2334, "text": "Following is a simple example showing Ext.panel.Panel Container." }, { "code": null, "e": 3356, "s": 2399, "text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function () {\n var childPanel1 = Ext.create('Ext.Panel', {\n html: 'First Panel'\n });\n var childPanel2 = Ext.create('Ext.Panel', {\n html: 'Another Panel'\n });\n Ext.create('Ext.panel.Panel', {\n renderTo: Ext.getBody(),\n width: 100,\n height : 100,\n border : true,\n frame : true,\n items: [ childPanel1, childPanel2 ]\n });\n });\n </script>\n </head>\n \n <body>\n </body>\n</html>" }, { "code": null, "e": 3410, "s": 3356, "text": "The above program will produce the following result βˆ’" }, { "code": null, "e": 3417, "s": 3410, "text": " Print" }, { "code": null, "e": 3428, "s": 3417, "text": " Add Notes" } ]
Get a substring of specified length from a string in Julia - SubString() Method - GeeksforGeeks
26 Mar, 2020 The SubString() is an inbuilt function in julia which is used to return a part of the specified parent string s within range i:j or r, where i, j and r is given as the parameter. Syntax:SubString(string::AbstractString, i::Integer, j::Integer)orSubString(string::AbstractString, r::UnitRange) Parameters: string: Specified parent string i: Specified starting index j: Specified last index r: Specified unit range Returns: It returns a part of the specified parent string s within range i:j or r, where i, j and r is given as the parameter. Example 1: # Julia program to illustrate # the use of String SubString() method # Finding a part of the parent string# "Geeks" from starting index 1# to ending index 3println(SubString("Geeks", 1, 3)) # Finding a part of the parent string# "GeeksforGeeks" from starting index 5# to ending index 10println(SubString("GeeksforGeeks", 5, 10)) # Finding a part of the parent string# "Geeks" with unitrange 2println(SubString("Geeks", 2)) # Finding a part of the parent string# "GeeksforGeeks" with unit range 6println(SubString("GeeksforGeeks", 6)) Output: Gee sforGe eeks forGeeks Example 2: # Julia program to illustrate # the use of String SubString() method # Finding a part of the parent string# "12345" from starting index 1# to ending index 3println(SubString("12345", 1, 3)) # Finding a part of the parent string# "123456789" from starting index 5# to ending index 8println(SubString("123456789", 5, 8)) # Finding a part of the parent string# "2468" with unitrange 2println(SubString("2468", 2)) Output: 123 5678 468 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vectors in Julia Storing Output on a File in Julia Formatting of Strings in Julia Getting rounded value of a number in Julia - round() Method Creating array with repeated elements in Julia - repeat() Method Reshaping array dimensions in Julia | Array reshape() Method Get array dimensions and size of a dimension in Julia - size() Method Comments in Julia Taking Input from Users in Julia while loop in Julia
[ { "code": null, "e": 24278, "s": 24250, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24457, "s": 24278, "text": "The SubString() is an inbuilt function in julia which is used to return a part of the specified parent string s within range i:j or r, where i, j and r is given as the parameter." }, { "code": null, "e": 24571, "s": 24457, "text": "Syntax:SubString(string::AbstractString, i::Integer, j::Integer)orSubString(string::AbstractString, r::UnitRange)" }, { "code": null, "e": 24583, "s": 24571, "text": "Parameters:" }, { "code": null, "e": 24615, "s": 24583, "text": "string: Specified parent string" }, { "code": null, "e": 24643, "s": 24615, "text": "i: Specified starting index" }, { "code": null, "e": 24667, "s": 24643, "text": "j: Specified last index" }, { "code": null, "e": 24691, "s": 24667, "text": "r: Specified unit range" }, { "code": null, "e": 24818, "s": 24691, "text": "Returns: It returns a part of the specified parent string s within range i:j or r, where i, j and r is given as the parameter." }, { "code": null, "e": 24829, "s": 24818, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of String SubString() method # Finding a part of the parent string# \"Geeks\" from starting index 1# to ending index 3println(SubString(\"Geeks\", 1, 3)) # Finding a part of the parent string# \"GeeksforGeeks\" from starting index 5# to ending index 10println(SubString(\"GeeksforGeeks\", 5, 10)) # Finding a part of the parent string# \"Geeks\" with unitrange 2println(SubString(\"Geeks\", 2)) # Finding a part of the parent string# \"GeeksforGeeks\" with unit range 6println(SubString(\"GeeksforGeeks\", 6))", "e": 25367, "s": 24829, "text": null }, { "code": null, "e": 25375, "s": 25367, "text": "Output:" }, { "code": null, "e": 25401, "s": 25375, "text": "Gee\nsforGe\neeks\nforGeeks\n" }, { "code": null, "e": 25412, "s": 25401, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of String SubString() method # Finding a part of the parent string# \"12345\" from starting index 1# to ending index 3println(SubString(\"12345\", 1, 3)) # Finding a part of the parent string# \"123456789\" from starting index 5# to ending index 8println(SubString(\"123456789\", 5, 8)) # Finding a part of the parent string# \"2468\" with unitrange 2println(SubString(\"2468\", 2))", "e": 25829, "s": 25412, "text": null }, { "code": null, "e": 25837, "s": 25829, "text": "Output:" }, { "code": null, "e": 25851, "s": 25837, "text": "123\n5678\n468\n" }, { "code": null, "e": 25857, "s": 25851, "text": "Julia" }, { "code": null, "e": 25955, "s": 25857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25964, "s": 25955, "text": "Comments" }, { "code": null, "e": 25977, "s": 25964, "text": "Old Comments" }, { "code": null, "e": 25994, "s": 25977, "text": "Vectors in Julia" }, { "code": null, "e": 26028, "s": 25994, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 26059, "s": 26028, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 26119, "s": 26059, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 26184, "s": 26119, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 26245, "s": 26184, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 26315, "s": 26245, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 26333, "s": 26315, "text": "Comments in Julia" }, { "code": null, "e": 26366, "s": 26333, "text": "Taking Input from Users in Julia" } ]
org.json - JSONArray
A JSONArray is an ordered sequence of values. It provides methods to access values by index and to put values. Following types are supported βˆ’ Boolean Boolean JSONArray JSONArray JSONObject JSONObject Number Number String String JSONObject.NULL object JSONObject.NULL object import org.json.JSONArray; import org.json.JSONObject; public class JSONDemo { public static void main(String[] args) { JSONArray list = new JSONArray(); list.put("foo"); list.put(new Integer(100)); list.put(new Double(1000.21)); list.put(new Boolean(true)); list.put(JSONObject.NULL); System.out.println("JSONArray: "); System.out.println(list); } } JSONArray: ["foo",100,1000.21,true,null] 18 Lectures 1.5 hours Dr. Saatya Prasad 107 Lectures 13.5 hours Arnab Chakraborty 75 Lectures 5 hours Revathi Ramachandran 14 Lectures 44 mins Zach Miller 12 Lectures 54 mins Prof. Paul Cline, Ed.D 54 Lectures 4 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 1975, "text": "A JSONArray is an ordered sequence of values. It provides methods to access values by index and to put values. Following types are supported βˆ’" }, { "code": null, "e": 2126, "s": 2118, "text": "Boolean" }, { "code": null, "e": 2134, "s": 2126, "text": "Boolean" }, { "code": null, "e": 2144, "s": 2134, "text": "JSONArray" }, { "code": null, "e": 2154, "s": 2144, "text": "JSONArray" }, { "code": null, "e": 2165, "s": 2154, "text": "JSONObject" }, { "code": null, "e": 2176, "s": 2165, "text": "JSONObject" }, { "code": null, "e": 2183, "s": 2176, "text": "Number" }, { "code": null, "e": 2190, "s": 2183, "text": "Number" }, { "code": null, "e": 2197, "s": 2190, "text": "String" }, { "code": null, "e": 2204, "s": 2197, "text": "String" }, { "code": null, "e": 2227, "s": 2204, "text": "JSONObject.NULL object" }, { "code": null, "e": 2250, "s": 2227, "text": "JSONObject.NULL object" }, { "code": null, "e": 2659, "s": 2250, "text": "import org.json.JSONArray;\nimport org.json.JSONObject;\n\npublic class JSONDemo {\n public static void main(String[] args) { \n JSONArray list = new JSONArray();\n\n list.put(\"foo\");\n list.put(new Integer(100));\n list.put(new Double(1000.21));\n list.put(new Boolean(true));\n list.put(JSONObject.NULL);\n\n System.out.println(\"JSONArray: \");\n System.out.println(list);\n }\n}" }, { "code": null, "e": 2702, "s": 2659, "text": "JSONArray: \n[\"foo\",100,1000.21,true,null]\n" }, { "code": null, "e": 2737, "s": 2702, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2756, "s": 2737, "text": " Dr. Saatya Prasad" }, { "code": null, "e": 2793, "s": 2756, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 2812, "s": 2793, "text": " Arnab Chakraborty" }, { "code": null, "e": 2845, "s": 2812, "text": "\n 75 Lectures \n 5 hours \n" }, { "code": null, "e": 2867, "s": 2845, "text": " Revathi Ramachandran" }, { "code": null, "e": 2899, "s": 2867, "text": "\n 14 Lectures \n 44 mins\n" }, { "code": null, "e": 2912, "s": 2899, "text": " Zach Miller" }, { "code": null, "e": 2944, "s": 2912, "text": "\n 12 Lectures \n 54 mins\n" }, { "code": null, "e": 2968, "s": 2944, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 3001, "s": 2968, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 3019, "s": 3001, "text": " Gilad James, PhD" }, { "code": null, "e": 3026, "s": 3019, "text": " Print" }, { "code": null, "e": 3037, "s": 3026, "text": " Add Notes" } ]
MySQL Select Rows where two columns do not have the same value?
You can use != operator from MySQL for this. The syntax is as follows: SELECT *FROM yourTableName WHERE yourColumnName1 !=yourColumnName2 OR (yourColumnName1 IS NULL AND yourColumnName2IS NOT NULL) OR (yourColumnName2 IS NULL AND yourColumnName1 IS NOT NULL); To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table selectTwoColumns -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstNumber int, -> SecondNumber int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.87 sec) Insert some records in the table using insert command. The query is as follows: mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(10,20); Query OK, 1 row affected (0.29 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(30,40); Query OK, 1 row affected (0.16 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(20,20); Query OK, 1 row affected (0.15 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,60); Query OK, 1 row affected (0.18 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,50); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(70,NULL); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from selectTwoColumns; The following is the output: +----+-------------+--------------+ | Id | FirstNumber | SecondNumber | +----+-------------+--------------+ | 1 | 10 | 20 | | 2 | 30 | 40 | | 3 | 20 | 20 | | 4 | 50 | 60 | | 5 | 50 | 50 | | 6 | 70 | NULL | +----+-------------+--------------+ 6 rows in set (0.00 sec) Here is the query to select rows where two columns do not have same value: mysql> select *from selectTwoColumns -> where FirstNumber!=SecondNumber -> OR (FirstNumber IS NULL AND SecondNumber IS NOT NULL) -> OR (SecondNumber IS NULL AND FirstNumber IS NOT NULL); The following is the output: +----+-------------+--------------+ | Id | FirstNumber | SecondNumber | +----+-------------+--------------+ | 1 | 10 | 20 | | 2 | 30 | 40 | | 4 | 50 | 60 | | 6 | 70 | NULL | +----+-------------+--------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1133, "s": 1062, "text": "You can use != operator from MySQL for this. The syntax is as follows:" }, { "code": null, "e": 1322, "s": 1133, "text": "SELECT *FROM yourTableName\nWHERE yourColumnName1 !=yourColumnName2\nOR (yourColumnName1 IS NULL AND yourColumnName2IS NOT NULL)\nOR (yourColumnName2 IS NULL AND yourColumnName1 IS NOT NULL);" }, { "code": null, "e": 1420, "s": 1322, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1618, "s": 1420, "text": "mysql> create table selectTwoColumns\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> FirstNumber int,\n -> SecondNumber int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.87 sec)" }, { "code": null, "e": 1698, "s": 1618, "text": "Insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2378, "s": 1698, "text": "mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(10,20);\nQuery OK, 1 row affected (0.29 sec)\nmysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(30,40);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(20,20);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,60);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,50);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(70,NULL);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2462, "s": 2378, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2500, "s": 2462, "text": "mysql> select *from selectTwoColumns;" }, { "code": null, "e": 2529, "s": 2500, "text": "The following is the output:" }, { "code": null, "e": 2914, "s": 2529, "text": "+----+-------------+--------------+\n| Id | FirstNumber | SecondNumber |\n+----+-------------+--------------+\n| 1 | 10 | 20 |\n| 2 | 30 | 40 |\n| 3 | 20 | 20 |\n| 4 | 50 | 60 |\n| 5 | 50 | 50 |\n| 6 | 70 | NULL |\n+----+-------------+--------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2989, "s": 2914, "text": "Here is the query to select rows where two columns do not have same value:" }, { "code": null, "e": 3185, "s": 2989, "text": "mysql> select *from selectTwoColumns\n -> where FirstNumber!=SecondNumber\n -> OR (FirstNumber IS NULL AND SecondNumber IS NOT NULL)\n -> OR (SecondNumber IS NULL AND FirstNumber IS NOT NULL);" }, { "code": null, "e": 3214, "s": 3185, "text": "The following is the output:" }, { "code": null, "e": 3527, "s": 3214, "text": "+----+-------------+--------------+\n| Id | FirstNumber | SecondNumber |\n+----+-------------+--------------+\n| 1 | 10 | 20 |\n| 2 | 30 | 40 |\n| 4 | 50 | 60 |\n| 6 | 70 | NULL |\n+----+-------------+--------------+\n4 rows in set (0.00 sec)" } ]
How to get the value of id attribute in jQuery?
Use jQuery attr() method to get the value of id attribute. You can try to run the following code to learn how to get the value in jQuery βˆ’ Live Demo <html> <head> <title>jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { alert($('#div1').attr('id')); }); </script> </head> <body> <div id = "div1"> <p>This is demo text.</p> </div> </body> </html>
[ { "code": null, "e": 1201, "s": 1062, "text": "Use jQuery attr() method to get the value of id attribute. You can try to run the following code to learn how to get the value in jQuery βˆ’" }, { "code": null, "e": 1211, "s": 1201, "text": "Live Demo" }, { "code": null, "e": 1618, "s": 1211, "text": "<html>\n\n <head>\n <title>jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n alert($('#div1').attr('id'));\n });\n </script>\n \n </head>\n \n <body>\n\n <div id = \"div1\">\n <p>This is demo text.</p>\n </div>\n\n </body>\n</html>" } ]
Minimum element in a sorted and rotated array | Practice | GeeksforGeeks
A sorted array A[ ] with distinct elements is rotated at some unknown point, the task is to find the minimum element in it. Example 1 Input: N = 5 arr[] = {4 ,5 ,1 ,2 ,3} Output: 1 Explanation: 1 is the minimum element inthe array. Example 2 Input: N = 7 arr[] = {10, 20, 30, 40, 50, 5, 7} Output: 5 Explanation: Here 5 is the minimum element. Your Task: Complete the function findMin() which takes an array arr[] and n, size of the array as input parameters, and returns the minimum element of the array. Expected Time Complexity: O(log N). Expected Auxiliary Space: O(log N). Constraints: 1 ≀ N ≀ 100000 1 ≀ A[i] ≀ 1000000 0 edavellycharanya7 hours ago C++ int findMin(int arr[], int n){ sort(arr,arr+n); return arr[0]; } 0 edavellycharanya This comment was deleted. 0 chessnoobdj8 hours ago C++ int findMin(int arr[], int n){ int l = 0, r = n-1, mid; while(l < r){ mid = (l+r)/2; if(arr[mid] < arr[r]) r = mid; else l = mid+1; } return arr[l]; } 0 chessnoobdj8 hours ago C++ log(n) int findMin(int arr[], int n){ int l = 0, r = n-1, mid, ans = arr[0]; while(l < r){ mid = l + (r-l)/2; if(arr[0] < arr[mid]) l = mid+1; else r = mid; } ans = min(ans, arr[mid]); if(mid-1 >= 0) ans = min(ans, arr[mid-1]); if(mid+1 < n) ans = min(ans, arr[mid+1]); return ans; } 0 awrijeetsingh12025 days ago //USING ARRAY REPRESENTATION OF A BINARY TREE int findMin(int arr[], int n) { int i, min = 263526; for (i = 0; i < n / 2; i++) { if (arr[i] < min) { min = arr[i]; } if (2 * i + 1 < n && arr[2 * i + 1] < min) { min = arr[2 * i + 1]; } if (2 * i + 2 < n && arr[2 * i + 2] < min) { min = arr[2 * i + 2]; } } return min; } 0 meghapucsd5 days ago int findMin(int arr[], int n){ //complete the function here int i = 0; int j =n-1; int min = arr[0]; while (i<j-1 && j>0) { if (arr[i] < arr[i +1]) { i++; } if (arr[j] > arr[j-1]) { j--; } if (arr[i] <= arr[j] && min>arr[i]) { min = arr[i]; } else if (min>arr[j]) { min = arr[j]; } } return min; } 0 harshilrpanchal19986 days ago java solution class Solution{ int findMin(int arr[], int n) { //complete the function here int ans = arr[0]; for (int i=1;i < n ; i++){ if (arr[i] < ans){ ans = arr[i]; } } return ans; }} 0 amarrajsmart1972 weeks ago int findMin(int arr[], int n){ //complete the function here // int min=INT_MAX; // for(int i=0;i<n;i++) // { // if(arr[i]<min) // min=arr[i]; // } // return min; for(int i=0;i<n-1;i++){ if(arr[i]>arr[i+1]) { return arr[i+1]; } } return arr[0]; } +1 sarthakgupta102 weeks ago int findMin(int arr[], int n){ //complete the function here int min=INT_MAX; for(int i=0;i<n;i++) { if(arr[i]<min) { min=arr[i]; } } return min; } 0 hemachoudary1232 weeks ago class Solution{ int findMin(int arr[], int n) { Arrays.sort(arr); return arr[0]; }} 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": 362, "s": 238, "text": "A sorted array A[ ] with distinct elements is rotated at some unknown point, the task is to find the minimum element in it." }, { "code": null, "e": 372, "s": 362, "text": "Example 1" }, { "code": null, "e": 470, "s": 372, "text": "Input:\nN = 5\narr[] = {4 ,5 ,1 ,2 ,3}\nOutput: 1\nExplanation: 1 is the minimum element inthe array." }, { "code": null, "e": 480, "s": 470, "text": "Example 2" }, { "code": null, "e": 582, "s": 480, "text": "Input:\nN = 7\narr[] = {10, 20, 30, 40, 50, 5, 7}\nOutput: 5\nExplanation: Here 5 is the minimum element." }, { "code": null, "e": 746, "s": 584, "text": "Your Task:\nComplete the function findMin() which takes an array arr[] and n, size of the array as input parameters, and returns the minimum element of the array." }, { "code": null, "e": 818, "s": 746, "text": "Expected Time Complexity: O(log N).\nExpected Auxiliary Space: O(log N)." }, { "code": null, "e": 865, "s": 818, "text": "Constraints:\n1 ≀ N ≀ 100000\n1 ≀ A[i] ≀ 1000000" }, { "code": null, "e": 867, "s": 865, "text": "0" }, { "code": null, "e": 895, "s": 867, "text": "edavellycharanya7 hours ago" }, { "code": null, "e": 899, "s": 895, "text": "C++" }, { "code": null, "e": 984, "s": 899, "text": "int findMin(int arr[], int n){\n sort(arr,arr+n);\n return arr[0];\n }" }, { "code": null, "e": 986, "s": 984, "text": "0" }, { "code": null, "e": 1003, "s": 986, "text": "edavellycharanya" }, { "code": null, "e": 1029, "s": 1003, "text": "This comment was deleted." }, { "code": null, "e": 1031, "s": 1029, "text": "0" }, { "code": null, "e": 1054, "s": 1031, "text": "chessnoobdj8 hours ago" }, { "code": null, "e": 1058, "s": 1054, "text": "C++" }, { "code": null, "e": 1313, "s": 1058, "text": "int findMin(int arr[], int n){\n int l = 0, r = n-1, mid;\n while(l < r){\n mid = (l+r)/2;\n if(arr[mid] < arr[r])\n r = mid;\n else\n l = mid+1;\n }\n return arr[l];\n }" }, { "code": null, "e": 1315, "s": 1313, "text": "0" }, { "code": null, "e": 1338, "s": 1315, "text": "chessnoobdj8 hours ago" }, { "code": null, "e": 1349, "s": 1338, "text": "C++ log(n)" }, { "code": null, "e": 1778, "s": 1349, "text": "int findMin(int arr[], int n){\n int l = 0, r = n-1, mid, ans = arr[0];\n while(l < r){\n mid = l + (r-l)/2;\n if(arr[0] < arr[mid])\n l = mid+1;\n else\n r = mid;\n }\n ans = min(ans, arr[mid]);\n if(mid-1 >= 0)\n ans = min(ans, arr[mid-1]);\n if(mid+1 < n)\n ans = min(ans, arr[mid+1]);\n return ans;\n }" }, { "code": null, "e": 1780, "s": 1778, "text": "0" }, { "code": null, "e": 1808, "s": 1780, "text": "awrijeetsingh12025 days ago" }, { "code": null, "e": 2160, "s": 1808, "text": "//USING ARRAY REPRESENTATION OF A BINARY TREE\n\nint findMin(int arr[], int n)\n{\n\tint i, min = 263526;\n\tfor (i = 0; i < n / 2; i++)\n\t{\n\t\tif (arr[i] < min)\n\t\t{\n\t\t\tmin = arr[i];\n\t\t}\n\t\tif (2 * i + 1 < n && arr[2 * i + 1] < min)\n\t\t{\n\t\t\tmin = arr[2 * i + 1];\n\t\t}\n\t\tif (2 * i + 2 < n && arr[2 * i + 2] < min)\n\t\t{\n\t\t\tmin = arr[2 * i + 2];\n\t\t}\n\t}\n\treturn min;\n}" }, { "code": null, "e": 2162, "s": 2160, "text": "0" }, { "code": null, "e": 2183, "s": 2162, "text": "meghapucsd5 days ago" }, { "code": null, "e": 2786, "s": 2183, "text": "int findMin(int arr[], int n){ //complete the function here int i = 0; int j =n-1; int min = arr[0]; while (i<j-1 && j>0) { if (arr[i] < arr[i +1]) { i++; } if (arr[j] > arr[j-1]) { j--; } if (arr[i] <= arr[j] && min>arr[i]) { min = arr[i]; } else if (min>arr[j]) { min = arr[j]; } } return min; }" }, { "code": null, "e": 2788, "s": 2786, "text": "0" }, { "code": null, "e": 2818, "s": 2788, "text": "harshilrpanchal19986 days ago" }, { "code": null, "e": 2832, "s": 2818, "text": "java solution" }, { "code": null, "e": 3080, "s": 2834, "text": "class Solution{ int findMin(int arr[], int n) { //complete the function here int ans = arr[0]; for (int i=1;i < n ; i++){ if (arr[i] < ans){ ans = arr[i]; } } return ans; }} " }, { "code": null, "e": 3082, "s": 3080, "text": "0" }, { "code": null, "e": 3109, "s": 3082, "text": "amarrajsmart1972 weeks ago" }, { "code": null, "e": 3459, "s": 3109, "text": "int findMin(int arr[], int n){ //complete the function here // int min=INT_MAX; // for(int i=0;i<n;i++) // { // if(arr[i]<min) // min=arr[i]; // } // return min; for(int i=0;i<n-1;i++){ if(arr[i]>arr[i+1]) { return arr[i+1]; } } return arr[0]; }" }, { "code": null, "e": 3462, "s": 3459, "text": "+1" }, { "code": null, "e": 3488, "s": 3462, "text": "sarthakgupta102 weeks ago" }, { "code": null, "e": 3748, "s": 3488, "text": "int findMin(int arr[], int n){\n //complete the function here\n int min=INT_MAX;\n for(int i=0;i<n;i++)\n {\n if(arr[i]<min)\n {\n min=arr[i];\n }\n }\n return min;\n \n }" }, { "code": null, "e": 3750, "s": 3748, "text": "0" }, { "code": null, "e": 3777, "s": 3750, "text": "hemachoudary1232 weeks ago" }, { "code": null, "e": 3880, "s": 3777, "text": "class Solution{ int findMin(int arr[], int n) { Arrays.sort(arr); return arr[0]; }} " }, { "code": null, "e": 4026, "s": 3880, "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": 4062, "s": 4026, "text": " Login to access your submissions. " }, { "code": null, "e": 4072, "s": 4062, "text": "\nProblem\n" }, { "code": null, "e": 4082, "s": 4072, "text": "\nContest\n" }, { "code": null, "e": 4145, "s": 4082, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4293, "s": 4145, "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": 4501, "s": 4293, "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": 4607, "s": 4501, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
SQL - UNIONS CLAUSE
The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. To use this UNION clause, each SELECT statement must have The same number of columns selected The same number of column expressions The same data type and Have them in the same order But they need not have to be in the same length. The basic syntax of a UNION clause is as follows βˆ’ SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Consider the following two tables. Table 1 βˆ’ CUSTOMERS Table is as follows. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 βˆ’ ORDERS Table is as follows. +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as follows βˆ’ SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID UNION SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result βˆ’ +------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Muffy | NULL | NULL | +------+----------+--------+---------------------+ The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to the UNION clause will apply to the UNION ALL operator. The basic syntax of the UNION ALL is as follows. SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALL SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Consider the following two tables, Table 1 βˆ’ CUSTOMERS Table is as follows. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 βˆ’ ORDERS table is as follows. +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as follows βˆ’ SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID UNION ALL SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result βˆ’ +------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Muffy | NULL | NULL | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +------+----------+--------+---------------------+ There are two other clauses (i.e., operators), which are like the UNION clause. SQL INTERSECT Clause βˆ’ This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. SQL INTERSECT Clause βˆ’ This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. SQL EXCEPT Clause βˆ’ This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. SQL EXCEPT Clause βˆ’ This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2585, "s": 2453, "text": "The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows." }, { "code": null, "e": 2643, "s": 2585, "text": "To use this UNION clause, each SELECT statement must have" }, { "code": null, "e": 2679, "s": 2643, "text": "The same number of columns selected" }, { "code": null, "e": 2717, "s": 2679, "text": "The same number of column expressions" }, { "code": null, "e": 2740, "s": 2717, "text": "The same data type and" }, { "code": null, "e": 2768, "s": 2740, "text": "Have them in the same order" }, { "code": null, "e": 2817, "s": 2768, "text": "But they need not have to be in the same length." }, { "code": null, "e": 2868, "s": 2817, "text": "The basic syntax of a UNION clause is as follows βˆ’" }, { "code": null, "e": 3017, "s": 2868, "text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n" }, { "code": null, "e": 3100, "s": 3017, "text": "Here, the given condition could be any given expression based on your requirement." }, { "code": null, "e": 3135, "s": 3100, "text": "Consider the following two tables." }, { "code": null, "e": 3176, "s": 3135, "text": "Table 1 βˆ’ CUSTOMERS Table is as follows." }, { "code": null, "e": 3693, "s": 3176, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 3731, "s": 3693, "text": "Table 2 βˆ’ ORDERS Table is as follows." }, { "code": null, "e": 4155, "s": 3731, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 4226, "s": 4155, "text": "Now, let us join these two tables in our SELECT statement as follows βˆ’" }, { "code": null, "e": 4460, "s": 4226, "text": "SQL> SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n LEFT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID\nUNION\n SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n RIGHT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 4502, "s": 4460, "text": "This would produce the following result βˆ’" }, { "code": null, "e": 5115, "s": 4502, "text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n+------+----------+--------+---------------------+\n" }, { "code": null, "e": 5220, "s": 5115, "text": "The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows." }, { "code": null, "e": 5304, "s": 5220, "text": "The same rules that apply to the UNION clause will apply to the UNION ALL operator." }, { "code": null, "e": 5353, "s": 5304, "text": "The basic syntax of the UNION ALL is as follows." }, { "code": null, "e": 5506, "s": 5353, "text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION ALL\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n" }, { "code": null, "e": 5589, "s": 5506, "text": "Here, the given condition could be any given expression based on your requirement." }, { "code": null, "e": 5624, "s": 5589, "text": "Consider the following two tables," }, { "code": null, "e": 5665, "s": 5624, "text": "Table 1 βˆ’ CUSTOMERS Table is as follows." }, { "code": null, "e": 6182, "s": 5665, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 6220, "s": 6182, "text": "Table 2 βˆ’ ORDERS table is as follows." }, { "code": null, "e": 6644, "s": 6220, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 6715, "s": 6644, "text": "Now, let us join these two tables in our SELECT statement as follows βˆ’" }, { "code": null, "e": 6953, "s": 6715, "text": "SQL> SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n LEFT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID\nUNION ALL\n SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n RIGHT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 6995, "s": 6953, "text": "This would produce the following result βˆ’" }, { "code": null, "e": 7812, "s": 6995, "text": "+------+----------+--------+---------------------+\n| ID | NAME | AMOUNT | DATE |\n+------+----------+--------+---------------------+\n| 1 | Ramesh | NULL | NULL |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n| 5 | Hardik | NULL | NULL |\n| 6 | Komal | NULL | NULL |\n| 7 | Muffy | NULL | NULL |\n| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |\n| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |\n| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |\n| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |\n+------+----------+--------+---------------------+\n" }, { "code": null, "e": 7892, "s": 7812, "text": "There are two other clauses (i.e., operators), which are like the UNION clause." }, { "code": null, "e": 8076, "s": 7892, "text": "SQL INTERSECT Clause βˆ’ This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement." }, { "code": null, "e": 8260, "s": 8076, "text": "SQL INTERSECT Clause βˆ’ This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement." }, { "code": null, "e": 8419, "s": 8260, "text": "SQL EXCEPT Clause βˆ’ This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement." }, { "code": null, "e": 8578, "s": 8419, "text": "SQL EXCEPT Clause βˆ’ This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement." }, { "code": null, "e": 8611, "s": 8578, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 8625, "s": 8611, "text": " Anadi Sharma" }, { "code": null, "e": 8658, "s": 8625, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 8672, "s": 8658, "text": " Anadi Sharma" }, { "code": null, "e": 8707, "s": 8672, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8721, "s": 8707, "text": " Anadi Sharma" }, { "code": null, "e": 8754, "s": 8721, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 8776, "s": 8754, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8811, "s": 8776, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8865, "s": 8811, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 8898, "s": 8865, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 8926, "s": 8898, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8933, "s": 8926, "text": " Print" }, { "code": null, "e": 8944, "s": 8933, "text": " Add Notes" } ]
Overflow Handling in Data Structure
An overflow occurs at the time of the home bucket for a new pair (key, element) is full. We may tackle overflows by Search the hash table in some systematic manner for a bucket that is not full. Linear probing (linear open addressing). Quadratic probing. Random probing. Eliminate overflows by allowing each bucket to keep a list of all pairs for which it is the home bucket. Array linear list. Chain. Open addressing is performed to ensure that all elements are stored directly into the hash table, thus it attempts to resolve collisions implementing various methods. Linear Probing is performed to resolve collisions by placing the data into the next open slot in the table. Worst-case find/insert/erase time is ΞΈ(m), where m is treated as the number of pairs in the table. This occurs when all pairs are in the same cluster. Identifiers are tending to cluster together Adjacent clusters are tending to coalesce Increase or enhance the search time Linear probing searches buckets (H(x)+i2)%b; H(x) indicates Hash function of x Quadratic probing implements a quadratic function of i as the increment Examine buckets H(x), (H(x)+i2)%b, (H(x)-i2)%b, for 1<=i<=(b-1)/2 b is indicated as a prime number of the form 4j+3, j is an integer Random Probing performs incorporating with random numbers. H(x):= (H’(x) + S[i]) % b S[i] is a table along with size b-1 S[i] is indicated as a random permutation of integers [1, b-1].
[ { "code": null, "e": 1151, "s": 1062, "text": "An overflow occurs at the time of the home bucket for a new pair (key, element) is full." }, { "code": null, "e": 1178, "s": 1151, "text": "We may tackle overflows by" }, { "code": null, "e": 1257, "s": 1178, "text": "Search the hash table in some systematic manner for a bucket that is not full." }, { "code": null, "e": 1298, "s": 1257, "text": "Linear probing (linear open addressing)." }, { "code": null, "e": 1317, "s": 1298, "text": "Quadratic probing." }, { "code": null, "e": 1333, "s": 1317, "text": "Random probing." }, { "code": null, "e": 1438, "s": 1333, "text": "Eliminate overflows by allowing each bucket to keep a list of all pairs for which it is the home bucket." }, { "code": null, "e": 1457, "s": 1438, "text": "Array linear list." }, { "code": null, "e": 1464, "s": 1457, "text": "Chain." }, { "code": null, "e": 1631, "s": 1464, "text": "Open addressing is performed to ensure that all elements are stored directly into the hash table, thus it attempts to resolve collisions implementing various methods." }, { "code": null, "e": 1739, "s": 1631, "text": "Linear Probing is performed to resolve collisions by placing the data into the next open slot in the table." }, { "code": null, "e": 1838, "s": 1739, "text": "Worst-case find/insert/erase time is ΞΈ(m), where m is treated as the number of pairs in the table." }, { "code": null, "e": 1890, "s": 1838, "text": "This occurs when all pairs are in the same cluster." }, { "code": null, "e": 1934, "s": 1890, "text": "Identifiers are tending to cluster together" }, { "code": null, "e": 1976, "s": 1934, "text": "Adjacent clusters are tending to coalesce" }, { "code": null, "e": 2012, "s": 1976, "text": "Increase or enhance the search time" }, { "code": null, "e": 2091, "s": 2012, "text": "Linear probing searches buckets (H(x)+i2)%b; H(x) indicates Hash function of x" }, { "code": null, "e": 2163, "s": 2091, "text": "Quadratic probing implements a quadratic function of i as the increment" }, { "code": null, "e": 2229, "s": 2163, "text": "Examine buckets H(x), (H(x)+i2)%b, (H(x)-i2)%b, for 1<=i<=(b-1)/2" }, { "code": null, "e": 2296, "s": 2229, "text": "b is indicated as a prime number of the form 4j+3, j is an integer" }, { "code": null, "e": 2355, "s": 2296, "text": "Random Probing performs incorporating with random numbers." }, { "code": null, "e": 2481, "s": 2355, "text": "H(x):= (H’(x) + S[i]) % b\nS[i] is a table along with size b-1\nS[i] is indicated as a random permutation of integers [1, b-1]." } ]
RxJS - Working with Subjects
A subject is an observable that can multicast i.e. talk to many observers. Consider a button with an event listener, the function attached to the event using add listener is called every time the user clicks on the button similar functionality goes for subject too. We are going to discuss the following topics in this chapter βˆ’ Create a subject What is the Difference between Observable and Subject? Behaviour Subject Replay Subject AsyncSubject To work with subject, we need to import Subject as shown below βˆ’ import { Subject } from 'rxjs'; You can create a subject object as follows βˆ’ const subject_test = new Subject(); The object is an observer that has three methods βˆ’ next(v) error(e) complete() You can create multiple subscription on the subject as shown below βˆ’ subject_test.subscribe({ next: (v) => console.log(`From Subject : ${v}`) }); subject_test.subscribe({ next: (v) => console.log(`From Subject: ${v}`) }); The subscription is registered to the subject object just like addlistener we discussed earlier. You can pass data to the subject created using the next() method. subject_test.next("A"); The data will be passed to all the subscription added on the subject. Here, is a working example of the subject βˆ’ import { Subject } from 'rxjs'; const subject_test = new Subject(); subject_test.subscribe({ next: (v) => console.log(`From Subject : ${v}`) }); subject_test.subscribe({ next: (v) => console.log(`From Subject: ${v}`) }); subject_test.next("A"); subject_test.next("B"); The subject_test object is created by calling a new Subject(). The subject_test object has reference to next(), error() and complete() methods. The output of the above example is shown below βˆ’ We can use complete() method to stop the subject execution as shown below. import { Subject } from 'rxjs'; const subject_test = new Subject(); subject_test.subscribe({ next: (v) => console.log(`From Subject : ${v}`) }); subject_test.subscribe({ next: (v) => console.log(`From Subject: ${v}`) }); subject_test.next("A"); subject_test.complete(); subject_test.next("B"); Once we call complete the next method called later is not invoked. Let us now see how to call error () method. Below is a working example βˆ’ import { Subject } from 'rxjs'; const subject_test = new Subject(); subject_test.subscribe({ error: (e) => console.log(`From Subject : ${e}`) }); subject_test.subscribe({ error: (e) => console.log(`From Subject : ${e}`) }); subject_test.error(new Error("There is an error")); An observable will talk one to one, to the subscriber. Anytime you subscribe to the observable the execution will start from scratch. Take an Http call made using ajax, and 2 subscribers calling the observable. You will see 2 HttpHttp requests in the browser network tab. Here is a working example of same βˆ’ import { ajax } from 'rxjs/ajax'; import { map } from 'rxjs/operators'; let final_val = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response)); let subscriber1 = final_val.subscribe(a => console.log(a)); let subscriber2 = final_val.subscribe(a => console.log(a)); Now, here the problem is, we want the same data to be shared, but not, at the cost of 2 Http calls. We want to make one Http call and share the data between subscribers. This will be possible using Subjects. It is an observable that can multicast i.e. talk to many observers. It can share the value between subscribers. Here is a working example using Subjects βˆ’ import { Subject } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { map } from 'rxjs/operators'; const subject_test = new Subject(); subject_test.subscribe({ next: (v) => console.log(v) }); subject_test.subscribe({ next: (v) => console.log(v) }); let final_val = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response)); let subscriber = final_val.subscribe(subject_test); Now you can see only one Http call and the same data is shared between the subscribers called. Behaviour subject will give you the latest value when called. You can create behaviour subject as shown below βˆ’ import { BehaviorSubject } from 'rxjs'; const subject = new BehaviorSubject("Testing Behaviour Subject"); // initialized the behaviour subject with value:Testing Behaviour Subject Here is a working example to use Behaviour Subject βˆ’ import { BehaviorSubject } from 'rxjs'; const behavior_subject = new BehaviorSubject("Testing Behaviour Subject"); // 0 is the initial value behavior_subject.subscribe({ next: (v) => console.log(`observerA: ${v}`) }); behavior_subject.next("Hello"); behavior_subject.subscribe({ next: (v) => console.log(`observerB: ${v}`) }); behavior_subject.next("Last call to Behaviour Subject"); A replaysubject is similar to behaviour subject, wherein, it can buffer the values and replay the same to the new subscribers. Here is a working example of replay subject βˆ’ import { ReplaySubject } from 'rxjs'; const replay_subject = new ReplaySubject(2); // buffer 2 values but new subscribers replay_subject.subscribe({ next: (v) => console.log(`Testing Replay Subject A: ${v}`) }); replay_subject.next(1); replay_subject.next(2); replay_subject.next(3); replay_subject.subscribe({ next: (v) => console.log(`Testing Replay Subject B: ${v}`) }); replay_subject.next(5); The buffer value used is 2 on the replay subject. So the last two values will be buffered and used for the new subscribers called. In the case of AsyncSubject the last value called is passed to the subscriber and it will be done only after complete() method is called. Here is a working example of the same βˆ’ import { AsyncSubject } from 'rxjs'; const async_subject = new AsyncSubject(); async_subject.subscribe({ next: (v) => console.log(`Testing Async Subject A: ${v}`) }); async_subject.next(1); async_subject.next(2); async_subject.complete(); async_subject.subscribe({ next: (v) => console.log(`Testing Async Subject B: ${v}`) }); Here, before complete is called the last value passed to the subject is 2 and the same it given to the subscribers. 51 Lectures 4 hours Daniel Stern Print Add Notes Bookmark this page
[ { "code": null, "e": 2090, "s": 1824, "text": "A subject is an observable that can multicast i.e. talk to many observers. Consider a button with an event listener, the function attached to the event using add listener is called every time the user clicks on the button similar functionality goes for subject too." }, { "code": null, "e": 2153, "s": 2090, "text": "We are going to discuss the following topics in this chapter βˆ’" }, { "code": null, "e": 2170, "s": 2153, "text": "Create a subject" }, { "code": null, "e": 2225, "s": 2170, "text": "What is the Difference between Observable and Subject?" }, { "code": null, "e": 2243, "s": 2225, "text": "Behaviour Subject" }, { "code": null, "e": 2258, "s": 2243, "text": "Replay Subject" }, { "code": null, "e": 2271, "s": 2258, "text": "AsyncSubject" }, { "code": null, "e": 2336, "s": 2271, "text": "To work with subject, we need to import Subject as shown below βˆ’" }, { "code": null, "e": 2369, "s": 2336, "text": "import { Subject } from 'rxjs';\n" }, { "code": null, "e": 2414, "s": 2369, "text": "You can create a subject object as follows βˆ’" }, { "code": null, "e": 2451, "s": 2414, "text": "const subject_test = new Subject();\n" }, { "code": null, "e": 2502, "s": 2451, "text": "The object is an observer that has three methods βˆ’" }, { "code": null, "e": 2510, "s": 2502, "text": "next(v)" }, { "code": null, "e": 2519, "s": 2510, "text": "error(e)" }, { "code": null, "e": 2530, "s": 2519, "text": "complete()" }, { "code": null, "e": 2599, "s": 2530, "text": "You can create multiple subscription on the subject as shown below βˆ’" }, { "code": null, "e": 2758, "s": 2599, "text": "subject_test.subscribe({\n next: (v) => console.log(`From Subject : ${v}`)\n});\nsubject_test.subscribe({\n next: (v) => console.log(`From Subject: ${v}`)\n});" }, { "code": null, "e": 2855, "s": 2758, "text": "The subscription is registered to the subject object just like addlistener we discussed earlier." }, { "code": null, "e": 2921, "s": 2855, "text": "You can pass data to the subject created using the next() method." }, { "code": null, "e": 2946, "s": 2921, "text": "subject_test.next(\"A\");\n" }, { "code": null, "e": 3016, "s": 2946, "text": "The data will be passed to all the subscription added on the subject." }, { "code": null, "e": 3060, "s": 3016, "text": "Here, is a working example of the subject βˆ’" }, { "code": null, "e": 3337, "s": 3060, "text": "import { Subject } from 'rxjs';\n\nconst subject_test = new Subject();\n\nsubject_test.subscribe({\n next: (v) => console.log(`From Subject : ${v}`)\n});\nsubject_test.subscribe({\n next: (v) => console.log(`From Subject: ${v}`)\n});\nsubject_test.next(\"A\");\nsubject_test.next(\"B\");" }, { "code": null, "e": 3530, "s": 3337, "text": "The subject_test object is created by calling a new Subject(). The subject_test object has reference to next(), error() and complete() methods. The output of the above example is shown below βˆ’" }, { "code": null, "e": 3605, "s": 3530, "text": "We can use complete() method to stop the subject execution as shown below." }, { "code": null, "e": 3907, "s": 3605, "text": "import { Subject } from 'rxjs';\n\nconst subject_test = new Subject();\n\nsubject_test.subscribe({\n next: (v) => console.log(`From Subject : ${v}`)\n});\nsubject_test.subscribe({\n next: (v) => console.log(`From Subject: ${v}`)\n});\nsubject_test.next(\"A\");\nsubject_test.complete();\nsubject_test.next(\"B\");" }, { "code": null, "e": 3974, "s": 3907, "text": "Once we call complete the next method called later is not invoked." }, { "code": null, "e": 4018, "s": 3974, "text": "Let us now see how to call error () method." }, { "code": null, "e": 4047, "s": 4018, "text": "Below is a working example βˆ’" }, { "code": null, "e": 4331, "s": 4047, "text": "import { Subject } from 'rxjs';\n\nconst subject_test = new Subject();\n\nsubject_test.subscribe({\n error: (e) => console.log(`From Subject : ${e}`)\n});\nsubject_test.subscribe({\n error: (e) => console.log(`From Subject : ${e}`)\n});\nsubject_test.error(new Error(\"There is an error\"));" }, { "code": null, "e": 4603, "s": 4331, "text": "An observable will talk one to one, to the subscriber. Anytime you subscribe to the observable the execution will start from scratch. Take an Http call made using ajax, and 2 subscribers calling the observable. You will see 2 HttpHttp requests in the browser network tab." }, { "code": null, "e": 4639, "s": 4603, "text": "Here is a working example of same βˆ’" }, { "code": null, "e": 4927, "s": 4639, "text": "import { ajax } from 'rxjs/ajax';\nimport { map } from 'rxjs/operators';\n\nlet final_val = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));\nlet subscriber1 = final_val.subscribe(a => console.log(a));\nlet subscriber2 = final_val.subscribe(a => console.log(a));" }, { "code": null, "e": 5097, "s": 4927, "text": "Now, here the problem is, we want the same data to be shared, but not, at the cost of 2 Http calls. We want to make one Http call and share the data between subscribers." }, { "code": null, "e": 5247, "s": 5097, "text": "This will be possible using Subjects. It is an observable that can multicast i.e. talk to many observers. It can share the value between subscribers." }, { "code": null, "e": 5290, "s": 5247, "text": "Here is a working example using Subjects βˆ’" }, { "code": null, "e": 5700, "s": 5290, "text": "import { Subject } from 'rxjs';\nimport { ajax } from 'rxjs/ajax';\nimport { map } from 'rxjs/operators';\n\nconst subject_test = new Subject();\n\nsubject_test.subscribe({\n next: (v) => console.log(v)\n});\nsubject_test.subscribe({\n next: (v) => console.log(v)\n});\n\nlet final_val = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));\nlet subscriber = final_val.subscribe(subject_test);" }, { "code": null, "e": 5795, "s": 5700, "text": "Now you can see only one Http call and the same data is shared between the subscribers called." }, { "code": null, "e": 5857, "s": 5795, "text": "Behaviour subject will give you the latest value when called." }, { "code": null, "e": 5907, "s": 5857, "text": "You can create behaviour subject as shown below βˆ’" }, { "code": null, "e": 6089, "s": 5907, "text": "import { BehaviorSubject } from 'rxjs';\nconst subject = new BehaviorSubject(\"Testing Behaviour Subject\"); \n// initialized the behaviour subject with value:Testing Behaviour Subject\n" }, { "code": null, "e": 6142, "s": 6089, "text": "Here is a working example to use Behaviour Subject βˆ’" }, { "code": null, "e": 6535, "s": 6142, "text": "import { BehaviorSubject } from 'rxjs';\nconst behavior_subject = new BehaviorSubject(\"Testing Behaviour Subject\"); \n// 0 is the initial value\n\nbehavior_subject.subscribe({\n next: (v) => console.log(`observerA: ${v}`)\n});\n\nbehavior_subject.next(\"Hello\");\nbehavior_subject.subscribe({\n next: (v) => console.log(`observerB: ${v}`)\n});\nbehavior_subject.next(\"Last call to Behaviour Subject\");" }, { "code": null, "e": 6662, "s": 6535, "text": "A replaysubject is similar to behaviour subject, wherein, it can buffer the values and replay the same to the new subscribers." }, { "code": null, "e": 6708, "s": 6662, "text": "Here is a working example of replay subject βˆ’" }, { "code": null, "e": 7116, "s": 6708, "text": "import { ReplaySubject } from 'rxjs';\nconst replay_subject = new ReplaySubject(2); \n// buffer 2 values but new subscribers\n\nreplay_subject.subscribe({\n next: (v) => console.log(`Testing Replay Subject A: ${v}`)\n});\n\nreplay_subject.next(1);\nreplay_subject.next(2);\nreplay_subject.next(3);\nreplay_subject.subscribe({\n next: (v) => console.log(`Testing Replay Subject B: ${v}`)\n});\n\nreplay_subject.next(5);" }, { "code": null, "e": 7247, "s": 7116, "text": "The buffer value used is 2 on the replay subject. So the last two values will be buffered and used for the new subscribers called." }, { "code": null, "e": 7385, "s": 7247, "text": "In the case of AsyncSubject the last value called is passed to the subscriber and it will be done only after complete() method is called." }, { "code": null, "e": 7425, "s": 7385, "text": "Here is a working example of the same βˆ’" }, { "code": null, "e": 7761, "s": 7425, "text": "import { AsyncSubject } from 'rxjs';\n\nconst async_subject = new AsyncSubject();\n\nasync_subject.subscribe({\n next: (v) => console.log(`Testing Async Subject A: ${v}`)\n});\n\nasync_subject.next(1);\nasync_subject.next(2);\nasync_subject.complete();\nasync_subject.subscribe({\n next: (v) => console.log(`Testing Async Subject B: ${v}`)\n});" }, { "code": null, "e": 7877, "s": 7761, "text": "Here, before complete is called the last value passed to the subject is 2 and the same it given to the subscribers." }, { "code": null, "e": 7910, "s": 7877, "text": "\n 51 Lectures \n 4 hours \n" }, { "code": null, "e": 7924, "s": 7910, "text": " Daniel Stern" }, { "code": null, "e": 7931, "s": 7924, "text": " Print" }, { "code": null, "e": 7942, "s": 7931, "text": " Add Notes" } ]
How to deal with error β€œundefined columns selected when subsetting data frame” in R?
The error β€œundefined columns selected when subsetting data frame” means that R does not understand the column that you want to use while subsetting the data frame. Generally, this happens when we forget to use comma while subsetting with single square brackets. Consider the below data frame βˆ’ > set.seed(99) > x1<-rnorm(20,0.5) > x2<-rpois(20,2) > x3<-runif(20,2,10) > x4<-rnorm(20,0.2) > x5<-rpois(20,5) > df<-data.frame(x1,x2,x3,x4,x5) > df x1 x2 x3 x4 x5 1 0.7139625 4 9.321058 0.33297863 4 2 0.9796581 2 4.298837 -1.47926432 11 3 0.5878287 3 7.389898 -0.07847958 5 4 0.9438585 4 7.873764 -1.35241100 6 5 0.1371621 2 5.534758 -1.17969925 4 6 0.6226740 4 8.786676 -1.15705659 5 7 -0.3638452 1 6.407712 -0.72113718 5 8 0.9896243 2 9.374095 -0.66681774 9 9 0.1358831 2 2.086996 1.85664439 3 10 -0.7942420 0 8.730721 0.04492028 3 11 -0.2457690 3 2.687042 -1.37655243 2 12 1.4215504 3 7.075115 0.82408260 4 13 1.2500544 3 5.373809 0.53022068 5 14 -2.0085540 5 5.287499 -0.19812226 12 15 -2.5409341 1 6.217131 -0.88139693 5 16 0.5002658 3 2.723290 0.12307794 6 17 0.1059810 0 6.288451 -0.32553662 4 18 -1.2450277 2 2.942365 0.59128965 5 19 0.9986315 4 7.012492 -0.48045326 6 20 0.7709538 1 7.801093 -0.54869693 5 Now suppose, you want to select rows where x2 is greater than 2 and you type of the following code βˆ’ > df[df$x2>2] Error in `[.data.frame`(df, df$x2 > 2) : undefined columns selected It is throwing an error of undefined columns because you forgot the comma after defining your objective. The appropriate way to select the rows where x2 is greater than 2 is as shown below βˆ’ > df[df$x2>2,] x1 x2 x3 x4 x5 1 0.7139625 4 9.321058 0.33297863 4 3 0.5878287 3 7.389898 -0.07847958 5 4 0.9438585 4 7.873764 -1.35241100 6 6 0.6226740 4 8.786676 -1.15705659 5 11 -0.2457690 3 2.687042 -1.37655243 2 12 1.4215504 3 7.075115 0.82408260 4 13 1.2500544 3 5.373809 0.53022068 5 14 -2.0085540 5 5.287499 -0.19812226 12 16 0.5002658 3 2.723290 0.12307794 6 19 0.9986315 4 7.012492 -0.48045326 6 Similarly, to select the rows where x2 is less than 2 is as follows βˆ’ > df[df$x2<2,] x1 x2 x3 x4 x5 7 -0.3638452 1 6.407712 -0.72113718 5 10 -0.7942420 0 8.730721 0.04492028 3 15 -2.5409341 1 6.217131 -0.88139693 5 17 0.1059810 0 6.288451 -0.32553662 4 20 0.7709538 1 7.801093 -0.54869693 5 In the same way, the selection of rows where x2 is greater than 1 is as follows βˆ’ > df[df$x2>1,] x1 x2 x3 x4 x5 1 0.7139625 4 9.321058 0.33297863 4 2 0.9796581 2 4.298837 -1.47926432 11 3 0.5878287 3 7.389898 -0.07847958 5 4 0.9438585 4 7.873764 -1.35241100 6 5 0.1371621 2 5.534758 -1.17969925 4 6 0.6226740 4 8.786676 -1.15705659 5 8 0.9896243 2 9.374095 -0.66681774 9 9 0.1358831 2 2.086996 1.85664439 3 11 -0.2457690 3 2.687042 -1.37655243 2 12 1.4215504 3 7.075115 0.82408260 4 13 1.2500544 3 5.373809 0.53022068 5 14 -2.0085540 5 5.287499 -0.19812226 12 16 0.5002658 3 2.723290 0.12307794 6 18 -1.2450277 2 2.942365 0.59128965 5 19 0.9986315 4 7.012492 -0.48045326 6
[ { "code": null, "e": 1324, "s": 1062, "text": "The error β€œundefined columns selected when subsetting data frame” means that R does not understand the column that you want to use while subsetting the data frame. Generally, this happens when we forget to use comma while subsetting with single square brackets." }, { "code": null, "e": 1356, "s": 1324, "text": "Consider the below data frame βˆ’" }, { "code": null, "e": 2273, "s": 1356, "text": "> set.seed(99)\n> x1<-rnorm(20,0.5)\n> x2<-rpois(20,2)\n> x3<-runif(20,2,10)\n> x4<-rnorm(20,0.2)\n> x5<-rpois(20,5)\n> df<-data.frame(x1,x2,x3,x4,x5)\n> df\nx1 x2 x3 x4 x5\n1 0.7139625 4 9.321058 0.33297863 4\n2 0.9796581 2 4.298837 -1.47926432 11\n3 0.5878287 3 7.389898 -0.07847958 5\n4 0.9438585 4 7.873764 -1.35241100 6\n5 0.1371621 2 5.534758 -1.17969925 4\n6 0.6226740 4 8.786676 -1.15705659 5\n7 -0.3638452 1 6.407712 -0.72113718 5\n8 0.9896243 2 9.374095 -0.66681774 9\n9 0.1358831 2 2.086996 1.85664439 3\n10 -0.7942420 0 8.730721 0.04492028 3\n11 -0.2457690 3 2.687042 -1.37655243 2\n12 1.4215504 3 7.075115 0.82408260 4\n13 1.2500544 3 5.373809 0.53022068 5\n14 -2.0085540 5 5.287499 -0.19812226 12\n15 -2.5409341 1 6.217131 -0.88139693 5\n16 0.5002658 3 2.723290 0.12307794 6\n17 0.1059810 0 6.288451 -0.32553662 4\n18 -1.2450277 2 2.942365 0.59128965 5\n19 0.9986315 4 7.012492 -0.48045326 6\n20 0.7709538 1 7.801093 -0.54869693 5" }, { "code": null, "e": 2374, "s": 2273, "text": "Now suppose, you want to select rows where x2 is greater than 2 and you type of the following code βˆ’" }, { "code": null, "e": 2456, "s": 2374, "text": "> df[df$x2>2]\nError in `[.data.frame`(df, df$x2 > 2) : undefined columns selected" }, { "code": null, "e": 2647, "s": 2456, "text": "It is throwing an error of undefined columns because you forgot the comma after defining your objective. The appropriate way to select the rows where x2 is greater than 2 is as shown below βˆ’" }, { "code": null, "e": 3052, "s": 2647, "text": "> df[df$x2>2,]\nx1 x2 x3 x4 x5\n1 0.7139625 4 9.321058 0.33297863 4\n3 0.5878287 3 7.389898 -0.07847958 5\n4 0.9438585 4 7.873764 -1.35241100 6\n6 0.6226740 4 8.786676 -1.15705659 5\n11 -0.2457690 3 2.687042 -1.37655243 2\n12 1.4215504 3 7.075115 0.82408260 4\n13 1.2500544 3 5.373809 0.53022068 5\n14 -2.0085540 5 5.287499 -0.19812226 12\n16 0.5002658 3 2.723290 0.12307794 6\n19 0.9986315 4 7.012492 -0.48045326 6" }, { "code": null, "e": 3122, "s": 3052, "text": "Similarly, to select the rows where x2 is less than 2 is as follows βˆ’" }, { "code": null, "e": 3343, "s": 3122, "text": "> df[df$x2<2,]\nx1 x2 x3 x4 x5\n7 -0.3638452 1 6.407712 -0.72113718 5\n10 -0.7942420 0 8.730721 0.04492028 3\n15 -2.5409341 1 6.217131 -0.88139693 5\n17 0.1059810 0 6.288451 -0.32553662 4\n20 0.7709538 1 7.801093 -0.54869693 5" }, { "code": null, "e": 3425, "s": 3343, "text": "In the same way, the selection of rows where x2 is greater than 1 is as follows βˆ’" }, { "code": null, "e": 4016, "s": 3425, "text": "> df[df$x2>1,]\nx1 x2 x3 x4 x5\n1 0.7139625 4 9.321058 0.33297863 4\n2 0.9796581 2 4.298837 -1.47926432 11\n3 0.5878287 3 7.389898 -0.07847958 5\n4 0.9438585 4 7.873764 -1.35241100 6\n5 0.1371621 2 5.534758 -1.17969925 4\n6 0.6226740 4 8.786676 -1.15705659 5\n8 0.9896243 2 9.374095 -0.66681774 9\n9 0.1358831 2 2.086996 1.85664439 3\n11 -0.2457690 3 2.687042 -1.37655243 2\n12 1.4215504 3 7.075115 0.82408260 4\n13 1.2500544 3 5.373809 0.53022068 5\n14 -2.0085540 5 5.287499 -0.19812226 12\n16 0.5002658 3 2.723290 0.12307794 6\n18 -1.2450277 2 2.942365 0.59128965 5\n19 0.9986315 4 7.012492 -0.48045326 6" } ]
How can I show a hidden div when a select option is selected in JavaScript?
To show a hidden div when a select option is selected, you can set the value β€œstyle.display” to block. Following is the code βˆ’ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <style> #hideValuesOnSelect { display: none; } </style> <body> <select onchange="displayDivDemo('hideValuesOnSelect', this)"> <option value="0">Java</option> <option value="1">Javascript</option> </select> <div id="hideValuesOnSelect">This is the Javascript</div> </body> <script> function displayDivDemo(id, elementValue) { document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none'; } </script> </html> To run the above program, save the file name anyName.html(index.html) and right click on the file. Select the option β€œOpen with live server” in VS Code editor. This will produce the following output βˆ’ Whenever you select the second option value (JavaScript), the hidden div will show. This will produce the following output βˆ’
[ { "code": null, "e": 1165, "s": 1062, "text": "To show a hidden div when a select option is selected, you can set the value β€œstyle.display” to block." }, { "code": null, "e": 1189, "s": 1165, "text": "Following is the code βˆ’" }, { "code": null, "e": 2033, "s": 1189, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n</head>\n<link rel=\"stylesheet\"\nhref=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<style>\n #hideValuesOnSelect {\n display: none;\n }\n</style>\n<body>\n<select onchange=\"displayDivDemo('hideValuesOnSelect', this)\">\n<option value=\"0\">Java</option>\n<option value=\"1\">Javascript</option>\n</select>\n<div id=\"hideValuesOnSelect\">This is the Javascript</div>\n</body>\n<script>\n function displayDivDemo(id, elementValue) {\n document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none';\n }\n</script>\n</html>" }, { "code": null, "e": 2193, "s": 2033, "text": "To run the above program, save the file name anyName.html(index.html) and right click on the\nfile. Select the option β€œOpen with live server” in VS Code editor." }, { "code": null, "e": 2234, "s": 2193, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2318, "s": 2234, "text": "Whenever you select the second option value (JavaScript), the hidden div will show." }, { "code": null, "e": 2359, "s": 2318, "text": "This will produce the following output βˆ’" } ]
Good String | Practice | GeeksforGeeks
Given a string s of length N, you have to tell whether it is good or not. A good string is one where the distance between every two adjacent character is exactly 1. Here distance is defined by minimum distance between two character when alphabets from 'a' to 'z' are put in cyclic manner. For example distance between 'a' to 'c' is 2 and distance between 'a' to 'y' is also 2. The task is to print "YES" or "NO" (without quotes) depending on whether the given string is Good or not. Example 1: Input: s = "aaa" Output: NO Explanation: distance between 'a' and 'a' is not 1. Example 2: Input: s = "cbc" Output: YES Explanation: distance between 'b' and 'c' is 1. Your Task: You don't need to read input or print anything. Your task is to complete the function isGoodString() which accepts a string as input parameter and returns "YES" or "NO" (without quotes) accordingly. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: String contains only lower case english alphabets. 1 <= N <= 105 0 gurankitbehal781141 week ago string isGoodString(string s){string a="YES";string b="NO";int j=0; for(int i=0;i<s.length();i++){ if(s[i+1]-s[i]==1 || s[i+1]-s[i]==25 ||s[i+1]-s[i]==-25){ j++; } } if(j==s.length()-1){ cout<<a; } else cout<<b;} 0 saikirannagarjuna0072 months ago class Solution { String isGoodString(String s) { // code here for(int i=1;i<s.length();i++){ if(s.charAt(i)==s.charAt(i-1)){ return "NO"; } } return "YES"; }} 0 rayalravi20013 months ago c++ solution int n = s.length(); for(int i=1; i<n; i++){ if((s[i]=='a' && s[i-1]=='z') ||(s[i]=='z' && s[i-1]=='a')){ continue; } if(abs(s[i]-s[i-1]) != 1){ return "NO"; } } return "YES"; 0 jacksparrowxsr3 months ago string isGoodString(string s) { int n = s.size(); for(int i=0;i<n-1;i++) if(abs(s[i]-s[i+1])%24 != 1) return "NO"; return "YES"; } 0 jacksparrowxsr This comment was deleted. +1 ashumishra8425 months ago for i in range(len(s)-1): if abs(ord(s[i])-ord(s[i+1]))!=1 and abs(ord(s[i])-ord(s[i+1]))!=25: return "NO" return "YES" +1 badgujarsachin835 months ago string isGoodString(string s) { //code here. for(int i=0;i<s.size()-1;i++){ if(s[i]==s[i+1]){ return "NO"; } if(s[i]!='a' && s[i+1]!='z'&&s[i]!='a'&& s[s.size()-1]!='z'&&s[i]!='z' && s[i+1]!='a'&&s[i]!='z'&& s[s.size()-1]!='a'){ if(abs((s[i]-'0')-(s[i+1]-'0'))!=1){ return "NO"; } } } return "YES"; } 0 Sai Manaswini Reddy P3 years ago Sai Manaswini Reddy P https://uploads.disquscdn.c... 0 Dheeraj Varshney5 years ago Dheeraj Varshney not able to understand what is wrong with this code http://code.geeksforgeeks.o...gives error - output producing less number of line 0 ayush2277365 years ago ayush227736 Wrong !! The first test case where your code failed: Input:dcbabcbcdcdcbabcdcbcdcbazyzyxwxw Its Correct output is:YES And Your Output is:NO how can this be possible! 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": 721, "s": 238, "text": "Given a string s of length N, you have to tell whether it is good or not. A good string is one where the distance between every two adjacent character is exactly 1. Here distance is defined by minimum distance between two character when alphabets from 'a' to 'z' are put in cyclic manner. For example distance between 'a' to 'c' is 2 and distance between 'a' to 'y' is also 2. The task is to print \"YES\" or \"NO\" (without quotes) depending on whether the given string is Good or not." }, { "code": null, "e": 734, "s": 723, "text": "Example 1:" }, { "code": null, "e": 814, "s": 734, "text": "Input: s = \"aaa\"\nOutput: NO\nExplanation: distance between 'a' and 'a' is not 1." }, { "code": null, "e": 827, "s": 816, "text": "Example 2:" }, { "code": null, "e": 904, "s": 827, "text": "Input: s = \"cbc\"\nOutput: YES\nExplanation: distance between 'b' and 'c' is 1." }, { "code": null, "e": 1120, "s": 906, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function isGoodString() which accepts a string as input parameter and returns \"YES\" or \"NO\" (without quotes) accordingly.\n " }, { "code": null, "e": 1184, "s": 1120, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n " }, { "code": null, "e": 1248, "s": 1184, "text": "Constraints:\nString contains only lower case english alphabets." }, { "code": null, "e": 1262, "s": 1248, "text": "1 <= N <= 105" }, { "code": null, "e": 1264, "s": 1262, "text": "0" }, { "code": null, "e": 1293, "s": 1264, "text": "gurankitbehal781141 week ago" }, { "code": null, "e": 1554, "s": 1293, "text": "string isGoodString(string s){string a=\"YES\";string b=\"NO\";int j=0; for(int i=0;i<s.length();i++){ if(s[i+1]-s[i]==1 || s[i+1]-s[i]==25 ||s[i+1]-s[i]==-25){ j++; } } if(j==s.length()-1){ cout<<a; } else cout<<b;}" }, { "code": null, "e": 1556, "s": 1554, "text": "0" }, { "code": null, "e": 1589, "s": 1556, "text": "saikirannagarjuna0072 months ago" }, { "code": null, "e": 1816, "s": 1589, "text": "class Solution { String isGoodString(String s) { // code here for(int i=1;i<s.length();i++){ if(s.charAt(i)==s.charAt(i-1)){ return \"NO\"; } } return \"YES\"; }} " }, { "code": null, "e": 1818, "s": 1816, "text": "0" }, { "code": null, "e": 1844, "s": 1818, "text": "rayalravi20013 months ago" }, { "code": null, "e": 1857, "s": 1844, "text": "c++ solution" }, { "code": null, "e": 2084, "s": 1857, "text": " int n = s.length(); for(int i=1; i<n; i++){ if((s[i]=='a' && s[i-1]=='z') ||(s[i]=='z' && s[i-1]=='a')){ continue; } if(abs(s[i]-s[i-1]) != 1){ return \"NO\"; } } return \"YES\";" }, { "code": null, "e": 2086, "s": 2084, "text": "0" }, { "code": null, "e": 2113, "s": 2086, "text": "jacksparrowxsr3 months ago" }, { "code": null, "e": 2253, "s": 2113, "text": "string isGoodString(string s)\n{\n int n = s.size();\n for(int i=0;i<n-1;i++) if(abs(s[i]-s[i+1])%24 != 1) return \"NO\";\n return \"YES\";\n}" }, { "code": null, "e": 2255, "s": 2253, "text": "0" }, { "code": null, "e": 2270, "s": 2255, "text": "jacksparrowxsr" }, { "code": null, "e": 2296, "s": 2270, "text": "This comment was deleted." }, { "code": null, "e": 2299, "s": 2296, "text": "+1" }, { "code": null, "e": 2325, "s": 2299, "text": "ashumishra8425 months ago" }, { "code": null, "e": 2475, "s": 2325, "text": "for i in range(len(s)-1): if abs(ord(s[i])-ord(s[i+1]))!=1 and abs(ord(s[i])-ord(s[i+1]))!=25: return \"NO\" return \"YES\"" }, { "code": null, "e": 2478, "s": 2475, "text": "+1" }, { "code": null, "e": 2507, "s": 2478, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 2913, "s": 2507, "text": "string isGoodString(string s)\n{\n //code here.\n for(int i=0;i<s.size()-1;i++){\n if(s[i]==s[i+1]){\n return \"NO\";\n }\n if(s[i]!='a' && s[i+1]!='z'&&s[i]!='a'&& s[s.size()-1]!='z'&&s[i]!='z' && s[i+1]!='a'&&s[i]!='z'&& s[s.size()-1]!='a'){\n \n if(abs((s[i]-'0')-(s[i+1]-'0'))!=1){\n return \"NO\";\n }\n }\n \n }\n return \"YES\";\n}" }, { "code": null, "e": 2915, "s": 2913, "text": "0" }, { "code": null, "e": 2948, "s": 2915, "text": "Sai Manaswini Reddy P3 years ago" }, { "code": null, "e": 2970, "s": 2948, "text": "Sai Manaswini Reddy P" }, { "code": null, "e": 3001, "s": 2970, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 3003, "s": 3001, "text": "0" }, { "code": null, "e": 3031, "s": 3003, "text": "Dheeraj Varshney5 years ago" }, { "code": null, "e": 3048, "s": 3031, "text": "Dheeraj Varshney" }, { "code": null, "e": 3181, "s": 3048, "text": "not able to understand what is wrong with this code http://code.geeksforgeeks.o...gives error - output producing less number of line" }, { "code": null, "e": 3183, "s": 3181, "text": "0" }, { "code": null, "e": 3206, "s": 3183, "text": "ayush2277365 years ago" }, { "code": null, "e": 3218, "s": 3206, "text": "ayush227736" }, { "code": null, "e": 3271, "s": 3218, "text": "Wrong !! The first test case where your code failed:" }, { "code": null, "e": 3310, "s": 3271, "text": "Input:dcbabcbcdcdcbabcdcbcdcbazyzyxwxw" }, { "code": null, "e": 3336, "s": 3310, "text": "Its Correct output is:YES" }, { "code": null, "e": 3358, "s": 3336, "text": "And Your Output is:NO" }, { "code": null, "e": 3384, "s": 3358, "text": "how can this be possible!" }, { "code": null, "e": 3530, "s": 3384, "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": 3566, "s": 3530, "text": " Login to access your submissions. " }, { "code": null, "e": 3576, "s": 3566, "text": "\nProblem\n" }, { "code": null, "e": 3586, "s": 3576, "text": "\nContest\n" }, { "code": null, "e": 3649, "s": 3586, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3797, "s": 3649, "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": 4005, "s": 3797, "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": 4111, "s": 4005, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Maximum and minimum of an array using minimum number of comparisons - GeeksforGeeks
03 Jan, 2022 Write a C function to return minimum and maximum in an array. Your program should make the minimum number of comparisons. First of all, how do we return multiple values from a C function? We can do it either using structures or pointers. We have created a structure named pair (which contains min and max) to return multiple values. c struct pair{ int min; int max;}; And the function declaration becomes: struct pair getMinMax(int arr[], int n) where arr[] is the array of size n whose minimum and maximum are needed. METHOD 1 (Simple Linear Search) Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly (i.e., if the element is smaller than min then change min, else if the element is greater than max then change max, else ignore the element) C++ C Java Python3 C# Javascript // C++ program of above implementation#include<iostream>using namespace std; // Pair struct is used to return// two values from getMinMax()struct Pair{ int min; int max;}; Pair getMinMax(int arr[], int n){ struct Pair minmax; int i; // If there is only one element // then return it as min and max both if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } // If there are more than one elements, // then initialize min and max if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for(i = 2; i < n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, arr_size); cout << "Minimum element is " << minmax.min << endl; cout << "Maximum element is " << minmax.max; return 0;} // This code is contributed by nik_3112 /* structure is used to return two values from minMax() */#include<stdio.h>struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int n){ struct pair minmax; int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i<n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar();} // Java program of above implementationpublic class GFG {/* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); } } # Python program of above implementation # structure is used to return two values from minMax() class pair: def __init__(self): self.min = 0 self.max = 0 def getMinMax(arr: list, n: int) -> pair: minmax = pair() # If there is only one element then return it as min and max both if n == 1: minmax.max = arr[0] minmax.min = arr[0] return minmax # If there are more than one elements, then initialize min # and max if arr[0] > arr[1]: minmax.max = arr[0] minmax.min = arr[1] else: minmax.max = arr[1] minmax.min = arr[0] for i in range(2, n): if arr[i] > minmax.max: minmax.max = arr[i] elif arr[i] < minmax.min: minmax.min = arr[i] return minmax # Driver Codeif __name__ == "__main__": arr = [1000, 11, 445, 1, 330, 3000] arr_size = 6 minmax = getMinMax(arr, arr_size) print("Minimum element is", minmax.min) print("Maximum element is", minmax.max) # This code is contributed by# sanjeev2552 // C# program of above implementationusing System; class GFG{ /* Class Pair is used to return two values from getMinMax() */ class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write("Minimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); }} // This code is contributed by PrinciRaj1992 <script>// JavaScript program of above implementation /* Class Pair is used to return two values from getMinMax() */ function getMinMax(arr, n) { minmax = new Array(); var i; var min; var max; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ var arr = [1000, 11, 445, 1, 330, 3000]; var arr_size = 6; minmax = getMinMax(arr, arr_size); document.write("\nMinimum element is " ,minmax.min +"<br>"); document.write("\nMaximum element is " , minmax.max); // This code is contributed by shivanisinghss2110</script> Output: Minimum element is 1 Maximum element is 3000 Time Complexity: O(n) In this method, the total number of comparisons is 1 + 2(n-2) in the worst case and 1 + n – 2 in the best case. In the above implementation, the worst case occurs when elements are sorted in descending order and the best case occurs when elements are sorted in ascending order. METHOD 2 (Tournament Method) Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array. Pair MaxMin(array, array_size) if array_size = 1 return element as both max and min else if arry_size = 2 one comparison to determine max and min return that pair else /* array_size > 2 */ recur for max and min of left half recur for max and min of right half one comparison determines true max of the two candidates one comparison determines true min of the two candidates return the pair of max and min Implementation C++ C Java Python3 C# Javascript // C++ program of above implementation#include<iostream>using namespace std; // structure is used to return// two values from minMax()struct Pair{ int min; int max;}; struct Pair getMinMax(int arr[], int low, int high){ struct Pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } // If there are two elements if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } // If there are more than 2 elements mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); // Compare minimums of two parts if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; // Compare maximums of two parts if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, 0, arr_size - 1); cout << "Minimum element is " << minmax.min << endl; cout << "Maximum element is " << minmax.max; return 0;} // This code is contributed by nik_3112 /* structure is used to return two values from minMax() */#include<stdio.h>struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int low, int high){ struct pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high)/2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid+1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; /* compare maximums of two parts*/ if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax(arr, 0, arr_size-1); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar();} // Java program of above implementationpublic class GFG {/* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); }} # Python program of above implementationdef getMinMax(low, high, arr): arr_max = arr[low] arr_min = arr[low] # If there is only one element if low == high: arr_max = arr[low] arr_min = arr[low] return (arr_max, arr_min) # If there is only two element elif high == low + 1: if arr[low] > arr[high]: arr_max = arr[low] arr_min = arr[high] else: arr_max = arr[high] arr_min = arr[low] return (arr_max, arr_min) else: # If there are more than 2 elements mid = int((low + high) / 2) arr_max1, arr_min1 = getMinMax(low, mid, arr) arr_max2, arr_min2 = getMinMax(mid + 1, high, arr) return (max(arr_max1, arr_max2), min(arr_min1, arr_min2)) # Driver codearr = [1000, 11, 445, 1, 330, 3000]high = len(arr) - 1low = 0arr_max, arr_min = getMinMax(low, high, arr)print('Minimum element is ', arr_min)print('nMaximum element is ', arr_max) # This code is contributed by DeepakChhitarka // C# implementation of the approachusing System; public class GFG {/* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); Console.Write("\nMinimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); }} // This code contributed by Rajput-Ji <script>// Javascript program of above implementation /* Class Pair is used to return two values from getMinMax() */ class Pair { constructor(){ this.min = -1; this.max = 10000000; } } function getMinMax(arr , low , high) { var minmax = new Pair(); var mml = new Pair(); var mmr = new Pair(); var mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = parseInt((low + high) / 2); mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts */ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts */ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ var arr = [ 1000, 11, 445, 1, 330, 3000 ]; var arr_size = 6; var minmax = getMinMax(arr, 0, arr_size - 1); document.write("\nMinimum element is ", minmax.min); document.write("<br/>Maximum element is ", minmax.max); // This code is contributed by Rajput-Ji</script> Output: Minimum element is 1 Maximum element is 3000 Time Complexity: O(n) Total number of comparisons: let the number of comparisons be T(n). T(n) can be written as follows: Algorithmic Paradigm: Divide and Conquer T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2 T(2) = 1 T(1) = 0 If n is a power of 2, then we can write T(n) as: T(n) = 2T(n/2) + 2 After solving the above recursion, we get T(n) = 3n/2 -2 Thus, the approach does 3n/2 -2 comparisons if n is a power of 2. And it does more than 3n/2 -2 comparisons if n is not a power of 2. METHOD 3 (Compare in Pairs) If n is odd then initialize min and max as first element. If n is even then initialize min and max as minimum and maximum of the first two elements respectively. For rest of the elements, pick them in pairs and compare their maximum and minimum with max and min respectively. C++ C Java Python3 C# // C++ program of above implementation#include<iostream>using namespace std; // Structure is used to return// two values from minMax()struct Pair{ int min; int max;}; struct Pair getMinMax(int arr[], int n){ struct Pair minmax; int i; // If array has even number of elements // then initialize the first two elements // as minimum and maximum if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } // Set the starting index for loop i = 2; } // If array has odd number of elements // then initialize the first element as // minimum and maximum else { minmax.min = arr[0]; minmax.max = arr[0]; // Set the starting index for loop i = 1; } // In the while loop, pick elements in // pair and compare the pair with max // and min so far while (i < n - 1) { if (arr[i] > arr[i + 1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i + 1] < minmax.min) minmax.min = arr[i + 1]; } else { if (arr[i + 1] > minmax.max) minmax.max = arr[i + 1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } // Increment the index by 2 as // two elements are processed in loop i += 2; } return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); cout << "nMinimum element is " << minmax.min << endl; cout << "nMaximum element is " << minmax.max; return 0;} // This code is contributed by nik_3112 #include<stdio.h> /* structure is used to return two values from minMax() */struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int n){ struct pair minmax; int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n%2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n-1) { if (arr[i] > arr[i+1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i+1] < minmax.min) minmax.min = arr[i+1]; } else { if (arr[i+1] > minmax.max) minmax.max = arr[i+1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar();} // Java program of above implementationpublic class GFG { /* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); }} # Python3 program of above implementationdef getMinMax(arr): n = len(arr) # If array has even number of elements then # initialize the first two elements as minimum # and maximum if(n % 2 == 0): mx = max(arr[0], arr[1]) mn = min(arr[0], arr[1]) # set the starting index for loop i = 2 # If array has odd number of elements then # initialize the first element as minimum # and maximum else: mx = mn = arr[0] # set the starting index for loop i = 1 # In the while loop, pick elements in pair and # compare the pair with max and min so far while(i < n - 1): if arr[i] < arr[i + 1]: mx = max(mx, arr[i + 1]) mn = min(mn, arr[i]) else: mx = max(mx, arr[i]) mn = min(mn, arr[i + 1]) # Increment the index by 2 as two # elements are processed in loop i += 2 return (mx, mn) # Driver Codeif __name__ =='__main__': arr = [1000, 11, 445, 1, 330, 3000] mx, mn = getMinMax(arr) print("Minimum element is", mn) print("Maximum element is", mx) # This code is contributed by Kaustav // C# program of above implementationusing System; class GFG{ /* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; } /* set the starting index for loop */ /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write("Minimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); }} // This code is contributed by 29AjayKumar Output: Minimum element is 1 Maximum element is 3000 Time Complexity: O(n) Total number of comparisons: Different for even and odd n, see below: If n is odd: 3*(n-1)/2 If n is even: 1 Initial comparison for initializing min and max, and 3(n-2)/2 comparisons for rest of the elements = 1 + 3*(n-2)/2 = 3n/2 -2 Second and third approaches make the equal number of comparisons when n is a power of 2. In general, method 3 seems to be the best.Please write comments if you find any bug in the above programs/algorithms or a better way to solve the same problem. kamleshbhalui Rajput-Ji Kaustav kumar Chanda Akanksha_Rai princiraj1992 29AjayKumar sanjeev2552 DeepakChhitarka nik_3112 maafkaroplz anjalitejasvi501 anshulpurohit11 dhairyabahl5 shivanisinghss2110 abhishekolympics Numbers Arrays Divide and Conquer Searching Arrays Searching Divide and Conquer Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Merge Sort QuickSort Binary Search Program for Tower of Hanoi Count Inversions in an array | Set 1 (Using Merge Sort)
[ { "code": null, "e": 21473, "s": 21445, "text": "\n03 Jan, 2022" }, { "code": null, "e": 21596, "s": 21473, "text": "Write a C function to return minimum and maximum in an array. Your program should make the minimum number of comparisons. " }, { "code": null, "e": 21808, "s": 21596, "text": "First of all, how do we return multiple values from a C function? We can do it either using structures or pointers. We have created a structure named pair (which contains min and max) to return multiple values. " }, { "code": null, "e": 21810, "s": 21808, "text": "c" }, { "code": "struct pair{ int min; int max;}; ", "e": 21846, "s": 21810, "text": null }, { "code": null, "e": 21998, "s": 21846, "text": "And the function declaration becomes: struct pair getMinMax(int arr[], int n) where arr[] is the array of size n whose minimum and maximum are needed. " }, { "code": null, "e": 22361, "s": 21998, "text": "METHOD 1 (Simple Linear Search) Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly (i.e., if the element is smaller than min then change min, else if the element is greater than max then change max, else ignore the element) " }, { "code": null, "e": 22365, "s": 22361, "text": "C++" }, { "code": null, "e": 22367, "s": 22365, "text": "C" }, { "code": null, "e": 22372, "s": 22367, "text": "Java" }, { "code": null, "e": 22380, "s": 22372, "text": "Python3" }, { "code": null, "e": 22383, "s": 22380, "text": "C#" }, { "code": null, "e": 22394, "s": 22383, "text": "Javascript" }, { "code": "// C++ program of above implementation#include<iostream>using namespace std; // Pair struct is used to return// two values from getMinMax()struct Pair{ int min; int max;}; Pair getMinMax(int arr[], int n){ struct Pair minmax; int i; // If there is only one element // then return it as min and max both if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } // If there are more than one elements, // then initialize min and max if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for(i = 2; i < n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, arr_size); cout << \"Minimum element is \" << minmax.min << endl; cout << \"Maximum element is \" << minmax.max; return 0;} // This code is contributed by nik_3112", "e": 23647, "s": 22394, "text": null }, { "code": "/* structure is used to return two values from minMax() */#include<stdio.h>struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int n){ struct pair minmax; int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i<n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf(\"nMinimum element is %d\", minmax.min); printf(\"nMaximum element is %d\", minmax.max); getchar();} ", "e": 24678, "s": 23647, "text": null }, { "code": "// Java program of above implementationpublic class GFG {/* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf(\"\\nMinimum element is %d\", minmax.min); System.out.printf(\"\\nMaximum element is %d\", minmax.max); } }", "e": 26004, "s": 24678, "text": null }, { "code": "# Python program of above implementation # structure is used to return two values from minMax() class pair: def __init__(self): self.min = 0 self.max = 0 def getMinMax(arr: list, n: int) -> pair: minmax = pair() # If there is only one element then return it as min and max both if n == 1: minmax.max = arr[0] minmax.min = arr[0] return minmax # If there are more than one elements, then initialize min # and max if arr[0] > arr[1]: minmax.max = arr[0] minmax.min = arr[1] else: minmax.max = arr[1] minmax.min = arr[0] for i in range(2, n): if arr[i] > minmax.max: minmax.max = arr[i] elif arr[i] < minmax.min: minmax.min = arr[i] return minmax # Driver Codeif __name__ == \"__main__\": arr = [1000, 11, 445, 1, 330, 3000] arr_size = 6 minmax = getMinMax(arr, arr_size) print(\"Minimum element is\", minmax.min) print(\"Maximum element is\", minmax.max) # This code is contributed by# sanjeev2552", "e": 27042, "s": 26004, "text": null }, { "code": "// C# program of above implementationusing System; class GFG{ /* Class Pair is used to return two values from getMinMax() */ class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write(\"Minimum element is {0}\", minmax.min); Console.Write(\"\\nMaximum element is {0}\", minmax.max); }} // This code is contributed by PrinciRaj1992", "e": 28548, "s": 27042, "text": null }, { "code": "<script>// JavaScript program of above implementation /* Class Pair is used to return two values from getMinMax() */ function getMinMax(arr, n) { minmax = new Array(); var i; var min; var max; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ var arr = [1000, 11, 445, 1, 330, 3000]; var arr_size = 6; minmax = getMinMax(arr, arr_size); document.write(\"\\nMinimum element is \" ,minmax.min +\"<br>\"); document.write(\"\\nMaximum element is \" , minmax.max); // This code is contributed by shivanisinghss2110</script>", "e": 29831, "s": 28548, "text": null }, { "code": null, "e": 29840, "s": 29831, "text": "Output: " }, { "code": null, "e": 29885, "s": 29840, "text": "Minimum element is 1\nMaximum element is 3000" }, { "code": null, "e": 29907, "s": 29885, "text": "Time Complexity: O(n)" }, { "code": null, "e": 30185, "s": 29907, "text": "In this method, the total number of comparisons is 1 + 2(n-2) in the worst case and 1 + n – 2 in the best case. In the above implementation, the worst case occurs when elements are sorted in descending order and the best case occurs when elements are sorted in ascending order." }, { "code": null, "e": 30356, "s": 30185, "text": "METHOD 2 (Tournament Method) Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array." }, { "code": null, "e": 30822, "s": 30356, "text": "Pair MaxMin(array, array_size)\n if array_size = 1\n return element as both max and min\n else if arry_size = 2\n one comparison to determine max and min\n return that pair\n else /* array_size > 2 */\n recur for max and min of left half\n recur for max and min of right half\n one comparison determines true max of the two candidates\n one comparison determines true min of the two candidates\n return the pair of max and min" }, { "code": null, "e": 30838, "s": 30822, "text": "Implementation " }, { "code": null, "e": 30842, "s": 30838, "text": "C++" }, { "code": null, "e": 30844, "s": 30842, "text": "C" }, { "code": null, "e": 30849, "s": 30844, "text": "Java" }, { "code": null, "e": 30857, "s": 30849, "text": "Python3" }, { "code": null, "e": 30860, "s": 30857, "text": "C#" }, { "code": null, "e": 30871, "s": 30860, "text": "Javascript" }, { "code": "// C++ program of above implementation#include<iostream>using namespace std; // structure is used to return// two values from minMax()struct Pair{ int min; int max;}; struct Pair getMinMax(int arr[], int low, int high){ struct Pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } // If there are two elements if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } // If there are more than 2 elements mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); // Compare minimums of two parts if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; // Compare maximums of two parts if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, 0, arr_size - 1); cout << \"Minimum element is \" << minmax.min << endl; cout << \"Maximum element is \" << minmax.max; return 0;} // This code is contributed by nik_3112", "e": 32507, "s": 30871, "text": null }, { "code": "/* structure is used to return two values from minMax() */#include<stdio.h>struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int low, int high){ struct pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high)/2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid+1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; /* compare maximums of two parts*/ if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax(arr, 0, arr_size-1); printf(\"nMinimum element is %d\", minmax.min); printf(\"nMaximum element is %d\", minmax.max); getchar();}", "e": 33809, "s": 32507, "text": null }, { "code": "// Java program of above implementationpublic class GFG {/* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); System.out.printf(\"\\nMinimum element is %d\", minmax.min); System.out.printf(\"\\nMaximum element is %d\", minmax.max); }}", "e": 35537, "s": 33809, "text": null }, { "code": "# Python program of above implementationdef getMinMax(low, high, arr): arr_max = arr[low] arr_min = arr[low] # If there is only one element if low == high: arr_max = arr[low] arr_min = arr[low] return (arr_max, arr_min) # If there is only two element elif high == low + 1: if arr[low] > arr[high]: arr_max = arr[low] arr_min = arr[high] else: arr_max = arr[high] arr_min = arr[low] return (arr_max, arr_min) else: # If there are more than 2 elements mid = int((low + high) / 2) arr_max1, arr_min1 = getMinMax(low, mid, arr) arr_max2, arr_min2 = getMinMax(mid + 1, high, arr) return (max(arr_max1, arr_max2), min(arr_min1, arr_min2)) # Driver codearr = [1000, 11, 445, 1, 330, 3000]high = len(arr) - 1low = 0arr_max, arr_min = getMinMax(low, high, arr)print('Minimum element is ', arr_min)print('nMaximum element is ', arr_max) # This code is contributed by DeepakChhitarka", "e": 36572, "s": 35537, "text": null }, { "code": "// C# implementation of the approachusing System; public class GFG {/* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); Console.Write(\"\\nMinimum element is {0}\", minmax.min); Console.Write(\"\\nMaximum element is {0}\", minmax.max); }} // This code contributed by Rajput-Ji", "e": 38387, "s": 36572, "text": null }, { "code": "<script>// Javascript program of above implementation /* Class Pair is used to return two values from getMinMax() */ class Pair { constructor(){ this.min = -1; this.max = 10000000; } } function getMinMax(arr , low , high) { var minmax = new Pair(); var mml = new Pair(); var mmr = new Pair(); var mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = parseInt((low + high) / 2); mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts */ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts */ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ var arr = [ 1000, 11, 445, 1, 330, 3000 ]; var arr_size = 6; var minmax = getMinMax(arr, 0, arr_size - 1); document.write(\"\\nMinimum element is \", minmax.min); document.write(\"<br/>Maximum element is \", minmax.max); // This code is contributed by Rajput-Ji</script>", "e": 40147, "s": 38387, "text": null }, { "code": null, "e": 40156, "s": 40147, "text": "Output: " }, { "code": null, "e": 40201, "s": 40156, "text": "Minimum element is 1\nMaximum element is 3000" }, { "code": null, "e": 40224, "s": 40201, "text": "Time Complexity: O(n) " }, { "code": null, "e": 40366, "s": 40224, "text": "Total number of comparisons: let the number of comparisons be T(n). T(n) can be written as follows: Algorithmic Paradigm: Divide and Conquer " }, { "code": null, "e": 40446, "s": 40366, "text": " \n T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2 \n T(2) = 1\n T(1) = 0" }, { "code": null, "e": 40496, "s": 40446, "text": "If n is a power of 2, then we can write T(n) as: " }, { "code": null, "e": 40518, "s": 40496, "text": " T(n) = 2T(n/2) + 2" }, { "code": null, "e": 40561, "s": 40518, "text": "After solving the above recursion, we get " }, { "code": null, "e": 40579, "s": 40561, "text": " T(n) = 3n/2 -2" }, { "code": null, "e": 40713, "s": 40579, "text": "Thus, the approach does 3n/2 -2 comparisons if n is a power of 2. And it does more than 3n/2 -2 comparisons if n is not a power of 2." }, { "code": null, "e": 41018, "s": 40713, "text": "METHOD 3 (Compare in Pairs) If n is odd then initialize min and max as first element. If n is even then initialize min and max as minimum and maximum of the first two elements respectively. For rest of the elements, pick them in pairs and compare their maximum and minimum with max and min respectively. " }, { "code": null, "e": 41022, "s": 41018, "text": "C++" }, { "code": null, "e": 41024, "s": 41022, "text": "C" }, { "code": null, "e": 41029, "s": 41024, "text": "Java" }, { "code": null, "e": 41037, "s": 41029, "text": "Python3" }, { "code": null, "e": 41040, "s": 41037, "text": "C#" }, { "code": "// C++ program of above implementation#include<iostream>using namespace std; // Structure is used to return// two values from minMax()struct Pair{ int min; int max;}; struct Pair getMinMax(int arr[], int n){ struct Pair minmax; int i; // If array has even number of elements // then initialize the first two elements // as minimum and maximum if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } // Set the starting index for loop i = 2; } // If array has odd number of elements // then initialize the first element as // minimum and maximum else { minmax.min = arr[0]; minmax.max = arr[0]; // Set the starting index for loop i = 1; } // In the while loop, pick elements in // pair and compare the pair with max // and min so far while (i < n - 1) { if (arr[i] > arr[i + 1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i + 1] < minmax.min) minmax.min = arr[i + 1]; } else { if (arr[i + 1] > minmax.max) minmax.max = arr[i + 1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } // Increment the index by 2 as // two elements are processed in loop i += 2; } return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); cout << \"nMinimum element is \" << minmax.min << endl; cout << \"nMaximum element is \" << minmax.max; return 0;} // This code is contributed by nik_3112", "e": 43061, "s": 41040, "text": null }, { "code": "#include<stdio.h> /* structure is used to return two values from minMax() */struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int n){ struct pair minmax; int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n%2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n-1) { if (arr[i] > arr[i+1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i+1] < minmax.min) minmax.min = arr[i+1]; } else { if (arr[i+1] > minmax.max) minmax.max = arr[i+1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf(\"nMinimum element is %d\", minmax.min); printf(\"nMaximum element is %d\", minmax.max); getchar();}", "e": 44716, "s": 43061, "text": null }, { "code": "// Java program of above implementationpublic class GFG { /* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf(\"\\nMinimum element is %d\", minmax.min); System.out.printf(\"\\nMaximum element is %d\", minmax.max); }}", "e": 46794, "s": 44716, "text": null }, { "code": "# Python3 program of above implementationdef getMinMax(arr): n = len(arr) # If array has even number of elements then # initialize the first two elements as minimum # and maximum if(n % 2 == 0): mx = max(arr[0], arr[1]) mn = min(arr[0], arr[1]) # set the starting index for loop i = 2 # If array has odd number of elements then # initialize the first element as minimum # and maximum else: mx = mn = arr[0] # set the starting index for loop i = 1 # In the while loop, pick elements in pair and # compare the pair with max and min so far while(i < n - 1): if arr[i] < arr[i + 1]: mx = max(mx, arr[i + 1]) mn = min(mn, arr[i]) else: mx = max(mx, arr[i]) mn = min(mn, arr[i + 1]) # Increment the index by 2 as two # elements are processed in loop i += 2 return (mx, mn) # Driver Codeif __name__ =='__main__': arr = [1000, 11, 445, 1, 330, 3000] mx, mn = getMinMax(arr) print(\"Minimum element is\", mn) print(\"Maximum element is\", mx) # This code is contributed by Kaustav", "e": 48018, "s": 46794, "text": null }, { "code": "// C# program of above implementationusing System; class GFG{ /* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; } /* set the starting index for loop */ /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write(\"Minimum element is {0}\", minmax.min); Console.Write(\"\\nMaximum element is {0}\", minmax.max); }} // This code is contributed by 29AjayKumar", "e": 50408, "s": 48018, "text": null }, { "code": null, "e": 50417, "s": 50408, "text": "Output: " }, { "code": null, "e": 50462, "s": 50417, "text": "Minimum element is 1\nMaximum element is 3000" }, { "code": null, "e": 50484, "s": 50462, "text": "Time Complexity: O(n)" }, { "code": null, "e": 50555, "s": 50484, "text": "Total number of comparisons: Different for even and odd n, see below: " }, { "code": null, "e": 50793, "s": 50555, "text": " If n is odd: 3*(n-1)/2 \n If n is even: 1 Initial comparison for initializing min and max, \n and 3(n-2)/2 comparisons for rest of the elements \n = 1 + 3*(n-2)/2 = 3n/2 -2" }, { "code": null, "e": 51043, "s": 50793, "text": "Second and third approaches make the equal number of comparisons when n is a power of 2. In general, method 3 seems to be the best.Please write comments if you find any bug in the above programs/algorithms or a better way to solve the same problem. " }, { "code": null, "e": 51057, "s": 51043, "text": "kamleshbhalui" }, { "code": null, "e": 51067, "s": 51057, "text": "Rajput-Ji" }, { "code": null, "e": 51088, "s": 51067, "text": "Kaustav kumar Chanda" }, { "code": null, "e": 51101, "s": 51088, "text": "Akanksha_Rai" }, { "code": null, "e": 51115, "s": 51101, "text": "princiraj1992" }, { "code": null, "e": 51127, "s": 51115, "text": "29AjayKumar" }, { "code": null, "e": 51139, "s": 51127, "text": "sanjeev2552" }, { "code": null, "e": 51155, "s": 51139, "text": "DeepakChhitarka" }, { "code": null, "e": 51164, "s": 51155, "text": "nik_3112" }, { "code": null, "e": 51176, "s": 51164, "text": "maafkaroplz" }, { "code": null, "e": 51193, "s": 51176, "text": "anjalitejasvi501" }, { "code": null, "e": 51209, "s": 51193, "text": "anshulpurohit11" }, { "code": null, "e": 51222, "s": 51209, "text": "dhairyabahl5" }, { "code": null, "e": 51241, "s": 51222, "text": "shivanisinghss2110" }, { "code": null, "e": 51258, "s": 51241, "text": "abhishekolympics" }, { "code": null, "e": 51266, "s": 51258, "text": "Numbers" }, { "code": null, "e": 51273, "s": 51266, "text": "Arrays" }, { "code": null, "e": 51292, "s": 51273, "text": "Divide and Conquer" }, { "code": null, "e": 51302, "s": 51292, "text": "Searching" }, { "code": null, "e": 51309, "s": 51302, "text": "Arrays" }, { "code": null, "e": 51319, "s": 51309, "text": "Searching" }, { "code": null, "e": 51338, "s": 51319, "text": "Divide and Conquer" }, { "code": null, "e": 51346, "s": 51338, "text": "Numbers" }, { "code": null, "e": 51444, "s": 51346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51492, "s": 51444, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 51524, "s": 51492, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 51538, "s": 51524, "text": "Linear Search" }, { "code": null, "e": 51623, "s": 51538, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 51668, "s": 51623, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 51679, "s": 51668, "text": "Merge Sort" }, { "code": null, "e": 51689, "s": 51679, "text": "QuickSort" }, { "code": null, "e": 51703, "s": 51689, "text": "Binary Search" }, { "code": null, "e": 51730, "s": 51703, "text": "Program for Tower of Hanoi" } ]
Can I overload static methods in Java?
Overloading is a one of the mechanisms to achieve polymorphism where, a class contains two methods with same name and different parameters. Whenever you call this method the method body will be bound with the method call based on the parameters. Live Demo public class Calculator { public int addition(int a , int b){ int result = a+b; return result; } public int addition(int a , int b, int c){ int result = a+b+c; return result; } public static void main(String args[]){ Calculator cal = new Calculator(); System.out.println(cal.addition(12, 13, 15)); } } 40 Yes, we can overload static methods in Java. Live Demo public class Calculator { public static int addition(int a , int b){ int result = a+b; return result; } public static int addition(int a , int b, int c){ int result = a+b+c; return result; } public static void main(String args[]){ System.out.println(Calculator.addition(12, 13)); System.out.println(Calculator.addition(12, 13, 15)); } } 25 40
[ { "code": null, "e": 1202, "s": 1062, "text": "Overloading is a one of the mechanisms to achieve polymorphism where, a class contains two methods with same name and different parameters." }, { "code": null, "e": 1308, "s": 1202, "text": "Whenever you call this method the method body will be bound with the method call based on the parameters." }, { "code": null, "e": 1319, "s": 1308, "text": " Live Demo" }, { "code": null, "e": 1675, "s": 1319, "text": "public class Calculator {\n public int addition(int a , int b){\n int result = a+b;\n return result;\n }\n public int addition(int a , int b, int c){\n int result = a+b+c;\n return result;\n }\n public static void main(String args[]){\n Calculator cal = new Calculator();\n System.out.println(cal.addition(12, 13, 15));\n }\n}" }, { "code": null, "e": 1678, "s": 1675, "text": "40" }, { "code": null, "e": 1723, "s": 1678, "text": "Yes, we can overload static methods in Java." }, { "code": null, "e": 1734, "s": 1723, "text": " Live Demo" }, { "code": null, "e": 2125, "s": 1734, "text": "public class Calculator {\n public static int addition(int a , int b){\n int result = a+b;\n return result;\n }\n public static int addition(int a , int b, int c){\n int result = a+b+c;\n return result;\n }\n public static void main(String args[]){\n System.out.println(Calculator.addition(12, 13));\n System.out.println(Calculator.addition(12, 13, 15));\n }\n}" }, { "code": null, "e": 2131, "s": 2125, "text": "25\n40" } ]
Toggle bits of a number except first and last bits - GeeksforGeeks
22 Mar, 2021 Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite : Find most significant set bit of a number1) Generate a number which contains middle bit as set. We need to change all middle bits to 1 and keep corner bits as 0.2) Answer is XOR of generated number and original number. Note that XOR of 1 with a number toggles the number. C++ Java Python3 C# PHP Javascript // C++ Program to toggle bits// except first and last bit#include<iostream>using namespace std; // return set middle bitsint setmiddlebits(int n){ // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1;} int togglemiddlebits(int n){ // if number is 1 then // simply return if (n == 1) return 1; // xor with // middle bits return n ^ setmiddlebits(n);} // Driver Codeint main(){ // Given number int n = 9; // print toggle bits cout<<togglemiddlebits(n); return 0;} // Java program for toggle bits// expect first and last bitimport java.io.*; class GFG { // return set middle bits static int setmiddlebits(int n) { // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1; } static int togglemiddlebits(int n) { // if number is 1 then // simply return if (n == 1) return 1; // XOR with middle bits return n ^ setmiddlebits(n); } // Driver Code public static void main (String[] args) { // Given number int n = 9; // print toggle bits System.out.println(togglemiddlebits(n)); }} // This code is contributed by vt_m # Python3 program for toggle bits# expect first and last bit # return set middle bitsdef setmiddlebits(n): # set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; # return middle set bits # shift by 1 and xor with 1 return (n >> 1) ^ 1 def togglemiddlebits(n): # if number is 1 then simply return if (n == 1): return 1 # xor with middle bits return n ^ setmiddlebits(n) # Driver coden = 9print(togglemiddlebits(n)) # This code is contributed by Anant Agarwal. // C# program for toggle bits// expect first and last bitusing System; class GFG { // return set middle bits static int setmiddlebits(int n) { // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1; } static int togglemiddlebits(int n) { // if number is 1 then // simply return if (n == 1) return 1; // XOR with middle bits return n ^ setmiddlebits(n); } // Driver Code public static void Main () { // Given number int n = 9; // print toggle bits Console.WriteLine(togglemiddlebits(n)); }} // This code is contributed by Anant Agarwal. <?php// Php Program to toggle bits// except first and last bit // return set middle bitsfunction setmiddlebits($n){ // set all bit $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // return middle set bits // shift by 1 and xor with 1 return ($n >> 1) ^ 1;} function togglemiddlebits($n){ // if number is 1 then // simply return if ($n == 1) return 1; // xor with // middle bits return $n ^ setmiddlebits($n);} // Driver Code $n = 9; // print toggle bits echo togglemiddlebits($n); // This code is contributed by ajit?> <script> // Javascript Program to toggle bits// except first and last bit // return set middle bitsfunction setmiddlebits(n){ // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1;} function togglemiddlebits(n){ // if number is 1 then // simply return if (n == 1) return 1; // xor with // middle bits return n ^ setmiddlebits(n);} // Driver Code // Given numbervar n = 9;// print toggle bitsdocument.write(togglemiddlebits(n)); </script> Time Complexity:- O(1) Output: 15 raghavbansal011 jit_t noob2000 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Binary representation of a given number Program to find whether a given number is power of 2 Bit Fields in C 1's and 2's complement of a Binary Number Bits manipulation (Important tactics) Josephus problem | Set 1 (A O(n) Solution) Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C
[ { "code": null, "e": 24606, "s": 24578, "text": "\n22 Mar, 2021" }, { "code": null, "e": 24709, "s": 24606, "text": "Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: " }, { "code": null, "e": 24899, "s": 24709, "text": "Input : 10\nOutput : 12\nBinary representation:- 1 0 1 0\nAfter toggling first and last : 1 1 0 0\n\nInput : 9\nOutput : 15\nBinary representation : 1 0 0 1\nAfter toggling first and last : 1 1 1 1" }, { "code": null, "e": 25189, "s": 24901, "text": "Prerequisite : Find most significant set bit of a number1) Generate a number which contains middle bit as set. We need to change all middle bits to 1 and keep corner bits as 0.2) Answer is XOR of generated number and original number. Note that XOR of 1 with a number toggles the number. " }, { "code": null, "e": 25193, "s": 25189, "text": "C++" }, { "code": null, "e": 25198, "s": 25193, "text": "Java" }, { "code": null, "e": 25206, "s": 25198, "text": "Python3" }, { "code": null, "e": 25209, "s": 25206, "text": "C#" }, { "code": null, "e": 25213, "s": 25209, "text": "PHP" }, { "code": null, "e": 25224, "s": 25213, "text": "Javascript" }, { "code": "// C++ Program to toggle bits// except first and last bit#include<iostream>using namespace std; // return set middle bitsint setmiddlebits(int n){ // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1;} int togglemiddlebits(int n){ // if number is 1 then // simply return if (n == 1) return 1; // xor with // middle bits return n ^ setmiddlebits(n);} // Driver Codeint main(){ // Given number int n = 9; // print toggle bits cout<<togglemiddlebits(n); return 0;}", "e": 25871, "s": 25224, "text": null }, { "code": "// Java program for toggle bits// expect first and last bitimport java.io.*; class GFG { // return set middle bits static int setmiddlebits(int n) { // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1; } static int togglemiddlebits(int n) { // if number is 1 then // simply return if (n == 1) return 1; // XOR with middle bits return n ^ setmiddlebits(n); } // Driver Code public static void main (String[] args) { // Given number int n = 9; // print toggle bits System.out.println(togglemiddlebits(n)); }} // This code is contributed by vt_m", "e": 26720, "s": 25871, "text": null }, { "code": "# Python3 program for toggle bits# expect first and last bit # return set middle bitsdef setmiddlebits(n): # set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; # return middle set bits # shift by 1 and xor with 1 return (n >> 1) ^ 1 def togglemiddlebits(n): # if number is 1 then simply return if (n == 1): return 1 # xor with middle bits return n ^ setmiddlebits(n) # Driver coden = 9print(togglemiddlebits(n)) # This code is contributed by Anant Agarwal.", "e": 27254, "s": 26720, "text": null }, { "code": "// C# program for toggle bits// expect first and last bitusing System; class GFG { // return set middle bits static int setmiddlebits(int n) { // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1; } static int togglemiddlebits(int n) { // if number is 1 then // simply return if (n == 1) return 1; // XOR with middle bits return n ^ setmiddlebits(n); } // Driver Code public static void Main () { // Given number int n = 9; // print toggle bits Console.WriteLine(togglemiddlebits(n)); }} // This code is contributed by Anant Agarwal.", "e": 28106, "s": 27254, "text": null }, { "code": "<?php// Php Program to toggle bits// except first and last bit // return set middle bitsfunction setmiddlebits($n){ // set all bit $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // return middle set bits // shift by 1 and xor with 1 return ($n >> 1) ^ 1;} function togglemiddlebits($n){ // if number is 1 then // simply return if ($n == 1) return 1; // xor with // middle bits return $n ^ setmiddlebits($n);} // Driver Code $n = 9; // print toggle bits echo togglemiddlebits($n); // This code is contributed by ajit?>", "e": 28727, "s": 28106, "text": null }, { "code": "<script> // Javascript Program to toggle bits// except first and last bit // return set middle bitsfunction setmiddlebits(n){ // set all bit n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return middle set bits // shift by 1 and xor with 1 return (n >> 1) ^ 1;} function togglemiddlebits(n){ // if number is 1 then // simply return if (n == 1) return 1; // xor with // middle bits return n ^ setmiddlebits(n);} // Driver Code // Given numbervar n = 9;// print toggle bitsdocument.write(togglemiddlebits(n)); </script>", "e": 29331, "s": 28727, "text": null }, { "code": null, "e": 29363, "s": 29331, "text": "Time Complexity:- O(1) Output: " }, { "code": null, "e": 29366, "s": 29363, "text": "15" }, { "code": null, "e": 29384, "s": 29368, "text": "raghavbansal011" }, { "code": null, "e": 29390, "s": 29384, "text": "jit_t" }, { "code": null, "e": 29399, "s": 29390, "text": "noob2000" }, { "code": null, "e": 29409, "s": 29399, "text": "Bit Magic" }, { "code": null, "e": 29419, "s": 29409, "text": "Bit Magic" }, { "code": null, "e": 29517, "s": 29419, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29526, "s": 29517, "text": "Comments" }, { "code": null, "e": 29539, "s": 29526, "text": "Old Comments" }, { "code": null, "e": 29585, "s": 29539, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 29615, "s": 29585, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 29655, "s": 29615, "text": "Binary representation of a given number" }, { "code": null, "e": 29708, "s": 29655, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 29724, "s": 29708, "text": "Bit Fields in C" }, { "code": null, "e": 29766, "s": 29724, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 29804, "s": 29766, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 29847, "s": 29804, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 29898, "s": 29847, "text": "Add two numbers without using arithmetic operators" } ]
Rust - Input Output
This chapter discusses how to accept values from the standard input (keyboard) and display values to the standard output (console). In this chapter, we will also discuss passing command line arguments. Rust’s standard library features for input and output are organized around two traits βˆ’ Read Write Read Types that implement Read have methods for byte-oriented input. They’re called readers Write Types that implement Write support both byte-oriented and UTF-8 text output. They’re called writers. Readers are components that your program can read bytes from. Examples include reading input from the keyboard, files, etc. The read_line() method of this trait can be used to read data, one line at a time, from a file or standard input stream. read_line(&mut line)->Result Reads a line of text and appends it to line, which is a String. The return value is an io::Result, the number of bytes read. Rust programs might have to accept values from the user at runtime. The following example reads values from the standard input (Keyboard) and prints it to the console. fn main(){ let mut line = String::new(); println!("Enter your name :"); let b1 = std::io::stdin().read_line(&mut line).unwrap(); println!("Hello , {}", line); println!("no of bytes read , {}", b1); } The stdin() function returns a handle to the standard input stream of the current process, to which the read_line function can be applied. This function tries to read all the characters present in the input buffer when it encounters an end-of-line character. Enter your name : Mohtashim Hello , Mohtashim no of bytes read , 10 Writers are components that your program can write bytes to. Examples include printing values to the console, writing to files, etc. The write() method of this trait can be used to write data to a file or standard output stream. write(&buf)->Result Writes some of the bytes in the slice buf to the underlying stream. It returns an io::Result, the number of bytes written. The print! or println! macros can be used to display text on the console. However, you can also use the write() standard library function to display some text to the standard output. Let us consider an example to understand this. use std::io::Write; fn main() { let b1 = std::io::stdout().write("Tutorials ".as_bytes()).unwrap(); let b2 = std::io::stdout().write(String::from("Point").as_bytes()).unwrap(); std::io::stdout().write(format!("\nbytes written {}",(b1+b2)).as_bytes()).unwrap(); } Tutorials Point bytes written 15 The stdout() standard library function returns a handle to the standard output stream of the current process, to which the write function can be applied. The write() method returns an enum, Result. The unwrap() is a helper method to extract the actual result from the enumeration. The unwrap method will send panic if an error occurs. NOTE βˆ’ File IO is discussed in the next chapter. CommandLine arguments are passed to a program before executing it. They are like parameters passed to functions. CommandLine parameters can be used to pass values to the main() function. The std::env::args() returns the commandline arguments. The following example passes values as commandLine arguments to the main() function. The program is created in a file name main.rs. //main.rs fn main(){ let cmd_line = std::env::args(); println!("No of elements in arguments is :{}",cmd_line.len()); //print total number of values passed for arg in cmd_line { println!("[{}]",arg); //print all values passed as commandline arguments } } The program will generate a file main.exe once compiled. Multiple command line parameters should be separated by space. Execute main.exe from the terminal as main.exe hello tutorialspoint. NOTE βˆ’ hello and tutorialspoint are commandline arguments. No of elements in arguments is :3 [main.exe] [hello] [tutorialspoint] The output shows 3 arguments as the main.exe is the first argument. The following program calculates the sum of values passed as commandline arguments. A list integer values separated by space is passed to program. fn main(){ let cmd_line = std::env::args(); println!("No of elements in arguments is :{}",cmd_line.len()); // total number of elements passed let mut sum = 0; let mut has_read_first_arg = false; //iterate through all the arguments and calculate their sum for arg in cmd_line { if has_read_first_arg { //skip the first argument since it is the exe file name sum += arg.parse::<i32>().unwrap(); } has_read_first_arg = true; // set the flag to true to calculate sum for the subsequent arguments. } println!("sum is {}",sum); } On executing the program as main.exe 1 2 3 4, the output will be βˆ’ No of elements in arguments is :5 sum is 10 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2289, "s": 2087, "text": "This chapter discusses how to accept values from the standard input (keyboard) and display values to the standard output (console). In this chapter, we will also discuss passing command line arguments." }, { "code": null, "e": 2377, "s": 2289, "text": "Rust’s standard library features for input and output are organized around two traits βˆ’" }, { "code": null, "e": 2382, "s": 2377, "text": "Read" }, { "code": null, "e": 2388, "s": 2382, "text": "Write" }, { "code": null, "e": 2393, "s": 2388, "text": "Read" }, { "code": null, "e": 2480, "s": 2393, "text": "Types that implement Read have methods for byte-oriented input. They’re called readers" }, { "code": null, "e": 2486, "s": 2480, "text": "Write" }, { "code": null, "e": 2587, "s": 2486, "text": "Types that implement Write support both byte-oriented and UTF-8 text output. They’re called writers." }, { "code": null, "e": 2832, "s": 2587, "text": "Readers are components that your program can read bytes from. Examples include reading input from the keyboard, files, etc. The read_line() method of this trait can be used to read data, one line at a time, from a file or standard input stream." }, { "code": null, "e": 2861, "s": 2832, "text": "read_line(&mut line)->Result" }, { "code": null, "e": 2986, "s": 2861, "text": "Reads a line of text and appends it to line, which is a String. The return value is an io::Result, the number of bytes read." }, { "code": null, "e": 3154, "s": 2986, "text": "Rust programs might have to accept values from the user at runtime. The following example reads values from the standard input (Keyboard) and prints it to the console." }, { "code": null, "e": 3369, "s": 3154, "text": "fn main(){\n let mut line = String::new();\n println!(\"Enter your name :\");\n let b1 = std::io::stdin().read_line(&mut line).unwrap();\n println!(\"Hello , {}\", line);\n println!(\"no of bytes read , {}\", b1);\n}" }, { "code": null, "e": 3628, "s": 3369, "text": "The stdin() function returns a handle to the standard input stream of the current process, to which the read_line function can be applied. This function tries to read all the characters present in the input buffer when it encounters an end-of-line character." }, { "code": null, "e": 3697, "s": 3628, "text": "Enter your name :\nMohtashim\nHello , Mohtashim\nno of bytes read , 10\n" }, { "code": null, "e": 3926, "s": 3697, "text": "Writers are components that your program can write bytes to. Examples include printing values to the console, writing to files, etc. The write() method of this trait can be used to write data to a file or standard output stream." }, { "code": null, "e": 3946, "s": 3926, "text": "write(&buf)->Result" }, { "code": null, "e": 4069, "s": 3946, "text": "Writes some of the bytes in the slice buf to the underlying stream. It returns an io::Result, the number of bytes written." }, { "code": null, "e": 4252, "s": 4069, "text": "The print! or println! macros can be used to display text on the console. However, you can also use the write() standard library function to display some text to the standard output." }, { "code": null, "e": 4299, "s": 4252, "text": "Let us consider an example to understand this." }, { "code": null, "e": 4571, "s": 4299, "text": "use std::io::Write;\nfn main() {\n let b1 = std::io::stdout().write(\"Tutorials \".as_bytes()).unwrap();\n let b2 = std::io::stdout().write(String::from(\"Point\").as_bytes()).unwrap();\n std::io::stdout().write(format!(\"\\nbytes written {}\",(b1+b2)).as_bytes()).unwrap();\n}" }, { "code": null, "e": 4605, "s": 4571, "text": "Tutorials Point\nbytes written 15\n" }, { "code": null, "e": 4940, "s": 4605, "text": "The stdout() standard library function returns a handle to the standard output stream of the current process, to which the write function can be applied. The write() method returns an enum, Result. The unwrap() is a helper method to extract the actual result from the enumeration. The unwrap method will send panic if an error occurs." }, { "code": null, "e": 4989, "s": 4940, "text": "NOTE βˆ’ File IO is discussed in the next chapter." }, { "code": null, "e": 5232, "s": 4989, "text": "CommandLine arguments are passed to a program before executing it. They are like parameters passed to functions. CommandLine parameters can be used to pass values to the main() function. The std::env::args() returns the commandline arguments." }, { "code": null, "e": 5364, "s": 5232, "text": "The following example passes values as commandLine arguments to the main() function. The program is created in a file name main.rs." }, { "code": null, "e": 5647, "s": 5364, "text": "//main.rs\nfn main(){\n let cmd_line = std::env::args();\n println!(\"No of elements in arguments is :{}\",cmd_line.len()); \n //print total number of values passed\n for arg in cmd_line {\n println!(\"[{}]\",arg); //print all values passed \n as commandline arguments\n }\n}" }, { "code": null, "e": 5836, "s": 5647, "text": "The program will generate a file main.exe once compiled. Multiple command line parameters should be separated by space. Execute main.exe from the terminal as main.exe hello tutorialspoint." }, { "code": null, "e": 5895, "s": 5836, "text": "NOTE βˆ’ hello and tutorialspoint are commandline arguments." }, { "code": null, "e": 5966, "s": 5895, "text": "No of elements in arguments is :3\n[main.exe]\n[hello]\n[tutorialspoint]\n" }, { "code": null, "e": 6034, "s": 5966, "text": "The output shows 3 arguments as the main.exe is the first argument." }, { "code": null, "e": 6181, "s": 6034, "text": "The following program calculates the sum of values passed as commandline arguments. A list integer values separated by space is passed to program." }, { "code": null, "e": 6774, "s": 6181, "text": "fn main(){\n let cmd_line = std::env::args();\n println!(\"No of elements in arguments is \n :{}\",cmd_line.len()); \n // total number of elements passed\n\n let mut sum = 0;\n let mut has_read_first_arg = false;\n\n //iterate through all the arguments and calculate their sum\n\n for arg in cmd_line {\n if has_read_first_arg { //skip the first argument since it is the exe file name\n sum += arg.parse::<i32>().unwrap();\n }\n has_read_first_arg = true; \n // set the flag to true to calculate sum for the subsequent arguments.\n }\n println!(\"sum is {}\",sum);\n}" }, { "code": null, "e": 6841, "s": 6774, "text": "On executing the program as main.exe 1 2 3 4, the output will be βˆ’" }, { "code": null, "e": 6886, "s": 6841, "text": "No of elements in arguments is :5\nsum is 10\n" }, { "code": null, "e": 6921, "s": 6886, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6944, "s": 6921, "text": " Stone River ELearning" }, { "code": null, "e": 6976, "s": 6944, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 6987, "s": 6976, "text": " Ken Burke" }, { "code": null, "e": 6994, "s": 6987, "text": " Print" }, { "code": null, "e": 7005, "s": 6994, "text": " Add Notes" } ]
Add error bars to a Matplotlib bar plot - GeeksforGeeks
17 Dec, 2020 Prerequisites: Matplotlib In this article, we will create a bar plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data. Import required python library. Making simple data. Plot using plt.errorbar() function Display graph The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars. Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \*, data=None, \*\*kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameters are the horizontal and vertical coordinates of the data points. ecolor: This parameter is an optional parameter. And it is the color of the errorbar lines with default value NONE. elinewidth: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE. capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE. barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False. Implementation using the approach above is given below: Example 1: Adding Some errors in a β€˜y’ value. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plota = [1, 3, 5, 7]b = [11, 2, 4, 19] # Plot scatter hereplt.bar(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, yerr=c, fmt="o", color="r") plt.show() Output: Example 2: Adding Some errors in the β€˜x’ value. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plota = [1, 3, 5, 7]b = [11, 2, 4, 19] # Plot scatter hereplt.bar(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, xerr=c, fmt="o", color="r") plt.show() Output: Example 3: Adding error in x and y Python3 import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, 2, 4, 19] plt.bar(a, b) c = [1, 3, 2, 1]d = [1, 3, 2, 1] plt.errorbar(a, b, xerr=c, yerr=d, fmt="o", color="r")plt.show() Output: Example 4: Adding variable error in x and y. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx = [1, 2, 3, 4, 5]y = [1, 2, 1, 2, 1] # creating errory_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]y_errormax = [0.2, 0.4, 0.6, 0.4, 0.2] x_error = 0.5 y_error = [y_errormin, y_errormax] # ploting graphplt.bar(x, y) plt.errorbar(x, y, yerr=y_error, xerr=x_error, fmt='o', color="r") # you can use color ="r" for red or skip to default as blue plt.show() Output: Picked Python-matplotlib 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 | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n17 Dec, 2020" }, { "code": null, "e": 25673, "s": 25647, "text": "Prerequisites: Matplotlib" }, { "code": null, "e": 25933, "s": 25673, "text": "In this article, we will create a bar plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data. " }, { "code": null, "e": 25965, "s": 25933, "text": "Import required python library." }, { "code": null, "e": 25985, "s": 25965, "text": "Making simple data." }, { "code": null, "e": 26020, "s": 25985, "text": "Plot using plt.errorbar() function" }, { "code": null, "e": 26034, "s": 26020, "text": "Display graph" }, { "code": null, "e": 26173, "s": 26034, "text": "The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars." }, { "code": null, "e": 26418, "s": 26173, "text": "Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \\*, data=None, \\*\\*kwargs)" }, { "code": null, "e": 26500, "s": 26418, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26587, "s": 26500, "text": "x, y: These parameters are the horizontal and vertical coordinates of the data points." }, { "code": null, "e": 26703, "s": 26587, "text": "ecolor: This parameter is an optional parameter. And it is the color of the errorbar lines with default value NONE." }, { "code": null, "e": 26832, "s": 26703, "text": "elinewidth: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE." }, { "code": null, "e": 26965, "s": 26832, "text": "capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE." }, { "code": null, "e": 27128, "s": 26965, "text": "barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False." }, { "code": null, "e": 27184, "s": 27128, "text": "Implementation using the approach above is given below:" }, { "code": null, "e": 27231, "s": 27184, "text": "Example 1: Adding Some errors in a β€˜y’ value." }, { "code": null, "e": 27239, "s": 27231, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plota = [1, 3, 5, 7]b = [11, 2, 4, 19] # Plot scatter hereplt.bar(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, yerr=c, fmt=\"o\", color=\"r\") plt.show()", "e": 27463, "s": 27239, "text": null }, { "code": null, "e": 27471, "s": 27463, "text": "Output:" }, { "code": null, "e": 27520, "s": 27471, "text": "Example 2: Adding Some errors in the β€˜x’ value." }, { "code": null, "e": 27528, "s": 27520, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plota = [1, 3, 5, 7]b = [11, 2, 4, 19] # Plot scatter hereplt.bar(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, xerr=c, fmt=\"o\", color=\"r\") plt.show()", "e": 27752, "s": 27528, "text": null }, { "code": null, "e": 27760, "s": 27752, "text": "Output:" }, { "code": null, "e": 27795, "s": 27760, "text": "Example 3: Adding error in x and y" }, { "code": null, "e": 27803, "s": 27795, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, 2, 4, 19] plt.bar(a, b) c = [1, 3, 2, 1]d = [1, 3, 2, 1] plt.errorbar(a, b, xerr=c, yerr=d, fmt=\"o\", color=\"r\")plt.show()", "e": 27986, "s": 27803, "text": null }, { "code": null, "e": 27994, "s": 27986, "text": "Output:" }, { "code": null, "e": 28039, "s": 27994, "text": "Example 4: Adding variable error in x and y." }, { "code": null, "e": 28047, "s": 28039, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx = [1, 2, 3, 4, 5]y = [1, 2, 1, 2, 1] # creating errory_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]y_errormax = [0.2, 0.4, 0.6, 0.4, 0.2] x_error = 0.5 y_error = [y_errormin, y_errormax] # ploting graphplt.bar(x, y) plt.errorbar(x, y, yerr=y_error, xerr=x_error, fmt='o', color=\"r\") # you can use color =\"r\" for red or skip to default as blue plt.show()", "e": 28522, "s": 28047, "text": null }, { "code": null, "e": 28530, "s": 28522, "text": "Output:" }, { "code": null, "e": 28537, "s": 28530, "text": "Picked" }, { "code": null, "e": 28555, "s": 28537, "text": "Python-matplotlib" }, { "code": null, "e": 28562, "s": 28555, "text": "Python" }, { "code": null, "e": 28660, "s": 28562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28692, "s": 28660, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28734, "s": 28692, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28776, "s": 28734, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28832, "s": 28776, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28859, "s": 28832, "text": "Python Classes and Objects" }, { "code": null, "e": 28890, "s": 28859, "text": "Python | os.path.join() method" }, { "code": null, "e": 28926, "s": 28890, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28955, "s": 28926, "text": "Create a directory in Python" }, { "code": null, "e": 28977, "s": 28955, "text": "Defaultdict in Python" } ]
Permutations to arrange N persons around a circular table - GeeksforGeeks
18 Jan, 2022 Given N, the number of persons. The task is to arrange N person around a circular table.Examples: Input: N = 4 Output: 6 Input: N = 5 Output: 24 Approach: It is the concept of Circular permutation i.e. there is no specific starting point in the arrangement, any element can be considered as the start of the arrangement. For N = 4, Arrangements will be: Below is the formula to find Circular permutations: Circular Permutations = (N - 1)! Below is the implementation of above idea: C++ Java Python 3 C# PHP Javascript // C++ code to demonstrate Circular Permutation#include <bits/stdc++.h>using namespace std; // Function to find no. of permutationsint Circular(int n){ int Result = 1; while (n > 0) { Result = Result * n; n--; } return Result;} // Driver Codeint main(){ int n = 4; cout << Circular(n - 1);} // Java code to demonstrate// Circular Permutationimport java.io.*; class GFG{// Function to find no.// of permutationsstatic int Circular(int n){ int Result = 1; while (n > 0) { Result = Result * n; n--; } return Result;} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.println(Circular(n - 1));}} // This code is contributed// by Naman_Garg # Python 3 Program to demonstrate Circular Permutation # Function to find no. of permutationsdef Circular(n) : Result = 1 while n > 0 : Result = Result * n n -= 1 return Result # Driver Codeif __name__ == "__main__" : n = 4 # function calling print(Circular(n-1)) # This code is contributed by ANKITRAI1 // C# code to demonstrate// Circular Permutationusing System; public class GFG { // Function to find no.// of permutationsstatic int Circular(int n){ int Result = 1; while (n > 0) { Result = Result * n; n--; } return Result;} // Driver Codepublic static void Main(){ int n = 4; Console.Write(Circular(n - 1));}} /* This Java code is contributed by 29AjayKumar*/ <?php// PHP code to demonstrate Circular Permutation // Function to find no. of permutationsfunction Circular($n){ $Result = 1; while ($n > 0) { $Result = $Result * $n; $n--; } return $Result;} // Driver Code$n = 4; echo Circular($n - 1); // This code is contributed by mits?> <script>// javascript code to demonstrate// Circular Permutation // Function to find no. // of permutations function Circular(n) { var Result = 1; while (n > 0) { Result = Result * n; n--; } return Result; } // Driver Code var n = 4; document.write(Circular(n - 1)); // This code is contributed by Rajput-Ji</script> 6 ankthon Naman_Garg 29AjayKumar Mithun Kumar Rajput-Ji varshagumber28 math permutation Permutation and Combination C++ Programs Mathematical Mathematical permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Handling the Divide by Zero Exception in C++ Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24552, "s": 24524, "text": "\n18 Jan, 2022" }, { "code": null, "e": 24652, "s": 24552, "text": "Given N, the number of persons. The task is to arrange N person around a circular table.Examples: " }, { "code": null, "e": 24700, "s": 24652, "text": "Input: N = 4\nOutput: 6\n\nInput: N = 5\nOutput: 24" }, { "code": null, "e": 24912, "s": 24702, "text": "Approach: It is the concept of Circular permutation i.e. there is no specific starting point in the arrangement, any element can be considered as the start of the arrangement. For N = 4, Arrangements will be: " }, { "code": null, "e": 24966, "s": 24912, "text": "Below is the formula to find Circular permutations: " }, { "code": null, "e": 24999, "s": 24966, "text": "Circular Permutations = (N - 1)!" }, { "code": null, "e": 25044, "s": 24999, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 25048, "s": 25044, "text": "C++" }, { "code": null, "e": 25053, "s": 25048, "text": "Java" }, { "code": null, "e": 25062, "s": 25053, "text": "Python 3" }, { "code": null, "e": 25065, "s": 25062, "text": "C#" }, { "code": null, "e": 25069, "s": 25065, "text": "PHP" }, { "code": null, "e": 25080, "s": 25069, "text": "Javascript" }, { "code": "// C++ code to demonstrate Circular Permutation#include <bits/stdc++.h>using namespace std; // Function to find no. of permutationsint Circular(int n){ int Result = 1; while (n > 0) { Result = Result * n; n--; } return Result;} // Driver Codeint main(){ int n = 4; cout << Circular(n - 1);}", "e": 25407, "s": 25080, "text": null }, { "code": "// Java code to demonstrate// Circular Permutationimport java.io.*; class GFG{// Function to find no.// of permutationsstatic int Circular(int n){ int Result = 1; while (n > 0) { Result = Result * n; n--; } return Result;} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.println(Circular(n - 1));}} // This code is contributed// by Naman_Garg", "e": 25821, "s": 25407, "text": null }, { "code": "# Python 3 Program to demonstrate Circular Permutation # Function to find no. of permutationsdef Circular(n) : Result = 1 while n > 0 : Result = Result * n n -= 1 return Result # Driver Codeif __name__ == \"__main__\" : n = 4 # function calling print(Circular(n-1)) # This code is contributed by ANKITRAI1", "e": 26165, "s": 25821, "text": null }, { "code": "// C# code to demonstrate// Circular Permutationusing System; public class GFG { // Function to find no.// of permutationsstatic int Circular(int n){ int Result = 1; while (n > 0) { Result = Result * n; n--; } return Result;} // Driver Codepublic static void Main(){ int n = 4; Console.Write(Circular(n - 1));}} /* This Java code is contributed by 29AjayKumar*/", "e": 26597, "s": 26165, "text": null }, { "code": "<?php// PHP code to demonstrate Circular Permutation // Function to find no. of permutationsfunction Circular($n){ $Result = 1; while ($n > 0) { $Result = $Result * $n; $n--; } return $Result;} // Driver Code$n = 4; echo Circular($n - 1); // This code is contributed by mits?>", "e": 26905, "s": 26597, "text": null }, { "code": "<script>// javascript code to demonstrate// Circular Permutation // Function to find no. // of permutations function Circular(n) { var Result = 1; while (n > 0) { Result = Result * n; n--; } return Result; } // Driver Code var n = 4; document.write(Circular(n - 1)); // This code is contributed by Rajput-Ji</script>", "e": 27306, "s": 26905, "text": null }, { "code": null, "e": 27308, "s": 27306, "text": "6" }, { "code": null, "e": 27318, "s": 27310, "text": "ankthon" }, { "code": null, "e": 27329, "s": 27318, "text": "Naman_Garg" }, { "code": null, "e": 27341, "s": 27329, "text": "29AjayKumar" }, { "code": null, "e": 27354, "s": 27341, "text": "Mithun Kumar" }, { "code": null, "e": 27364, "s": 27354, "text": "Rajput-Ji" }, { "code": null, "e": 27379, "s": 27364, "text": "varshagumber28" }, { "code": null, "e": 27384, "s": 27379, "text": "math" }, { "code": null, "e": 27396, "s": 27384, "text": "permutation" }, { "code": null, "e": 27424, "s": 27396, "text": "Permutation and Combination" }, { "code": null, "e": 27437, "s": 27424, "text": "C++ Programs" }, { "code": null, "e": 27450, "s": 27437, "text": "Mathematical" }, { "code": null, "e": 27463, "s": 27450, "text": "Mathematical" }, { "code": null, "e": 27475, "s": 27463, "text": "permutation" }, { "code": null, "e": 27573, "s": 27475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27582, "s": 27573, "text": "Comments" }, { "code": null, "e": 27595, "s": 27582, "text": "Old Comments" }, { "code": null, "e": 27636, "s": 27595, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27657, "s": 27636, "text": "Const keyword in C++" }, { "code": null, "e": 27716, "s": 27657, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 27728, "s": 27716, "text": "cout in C++" }, { "code": null, "e": 27773, "s": 27728, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 27803, "s": 27773, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 27818, "s": 27803, "text": "C++ Data Types" }, { "code": null, "e": 27878, "s": 27818, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27921, "s": 27878, "text": "Set in C++ Standard Template Library (STL)" } ]
ArrayAdapter in Android with Example - GeeksforGeeks
23 Oct, 2020 The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When you have a list of single type items which are stored in an array you can use ArrayAdapter. Likewise, if you have a list of phone numbers, names, or cities. ArrayAdapter has a layout with a single TextView. If you want to have a more complex layout instead of ArrayAdapter use CustomArrayAdapter. The basic syntax for ArrayAdapter is given as: public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) Parameters Description context: It is used to pass the reference of the current class. Here β€˜this’ keyword is used to pass the current class reference. Instead of β€˜this’ we could also use the getApplicationContext() method which is used for the Activity and the getApplication() method which is used for Fragments. public ArrayAdapter(this, int resource, int textViewResourceId, T[] objects) resource: It is used to set the layout file(.xml files) for the list items. public ArrayAdapter(this, R.layout.itemListView, int textViewResourceId, T[] objects) textViewResourceId: It is used to set the TextView where you want to display the text data. public ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, T[] objects) objects: These are the array object which is used to set the array element into the TextView. String courseList[] = {β€œC-Programming”, β€œData Structure”, β€œDatabase”, β€œPython”, β€œJava”, β€œOperating System”,”Compiler Design”, β€œAndroid Development”}; ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, courseList[]); In this example, the list of courses is displayed using a simple array adapter. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Go to the layout folder and in activity_main.xml file change the ConstraintLayout to RelativeLayout and insert a ListView with id simpleListView. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/simpleListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> Step 3: Create a new layout file Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view.xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/itemTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout> Step 4: Working with the MainActivity.java file Now go to the java folder and in MainActivity.java and provide the implementation to the ArrayAdapter. Below is the code for the MainActivity.java file. Java import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ListView simpleListView; // array objects String courseList[] = {"C-Programming", "Data Structure", "Database", "Python", "Java", "Operating System", "Compiler Design", "Android Development"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); simpleListView = (ListView) findViewById(R.id.simpleListView); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.item_view, R.id.itemTextView, courseList); simpleListView.setAdapter(arrayAdapter); }} android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Content Providers in Android with Example Android RecyclerView in Kotlin How to View and Locate SQLite Database in Android Studio? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25076, "s": 25048, "text": "\n23 Oct, 2020" }, { "code": null, "e": 25769, "s": 25076, "text": "The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When you have a list of single type items which are stored in an array you can use ArrayAdapter. Likewise, if you have a list of phone numbers, names, or cities. ArrayAdapter has a layout with a single TextView. If you want to have a more complex layout instead of ArrayAdapter use CustomArrayAdapter. The basic syntax for ArrayAdapter is given as:" }, { "code": null, "e": 25857, "s": 25769, "text": "public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)" }, { "code": null, "e": 25868, "s": 25857, "text": "Parameters" }, { "code": null, "e": 25880, "s": 25868, "text": "Description" }, { "code": null, "e": 26172, "s": 25880, "text": "context: It is used to pass the reference of the current class. Here β€˜this’ keyword is used to pass the current class reference. Instead of β€˜this’ we could also use the getApplicationContext() method which is used for the Activity and the getApplication() method which is used for Fragments." }, { "code": null, "e": 26249, "s": 26172, "text": "public ArrayAdapter(this, int resource, int textViewResourceId, T[] objects)" }, { "code": null, "e": 26325, "s": 26249, "text": "resource: It is used to set the layout file(.xml files) for the list items." }, { "code": null, "e": 26411, "s": 26325, "text": "public ArrayAdapter(this, R.layout.itemListView, int textViewResourceId, T[] objects)" }, { "code": null, "e": 26503, "s": 26411, "text": "textViewResourceId: It is used to set the TextView where you want to display the text data." }, { "code": null, "e": 26584, "s": 26503, "text": "public ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, T[] objects)" }, { "code": null, "e": 26678, "s": 26584, "text": "objects: These are the array object which is used to set the array element into the TextView." }, { "code": null, "e": 26758, "s": 26678, "text": "String courseList[] = {β€œC-Programming”, β€œData Structure”, β€œDatabase”, β€œPython”," }, { "code": null, "e": 26850, "s": 26758, "text": " β€œJava”, β€œOperating System”,”Compiler Design”, β€œAndroid Development”};" }, { "code": null, "e": 26958, "s": 26850, "text": "ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, courseList[]);" }, { "code": null, "e": 27112, "s": 26958, "text": "In this example, the list of courses is displayed using a simple array adapter. Note that we are going to implement this project using the Java language." }, { "code": null, "e": 27141, "s": 27112, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27303, "s": 27141, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 27351, "s": 27303, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 27547, "s": 27351, "text": "Go to the layout folder and in activity_main.xml file change the ConstraintLayout to RelativeLayout and insert a ListView with id simpleListView. Below is the code for the activity_main.xml file." }, { "code": null, "e": 27551, "s": 27547, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ListView android:id=\"@+id/simpleListView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </RelativeLayout>", "e": 27995, "s": 27551, "text": null }, { "code": null, "e": 28028, "s": 27995, "text": "Step 3: Create a new layout file" }, { "code": null, "e": 28288, "s": 28028, "text": "Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view.xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output." }, { "code": null, "e": 28292, "s": 28288, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/itemTextView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" /> </LinearLayout>", "e": 28720, "s": 28292, "text": null }, { "code": null, "e": 28768, "s": 28720, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 28922, "s": 28768, "text": "Now go to the java folder and in MainActivity.java and provide the implementation to the ArrayAdapter. Below is the code for the MainActivity.java file. " }, { "code": null, "e": 28927, "s": 28922, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ListView simpleListView; // array objects String courseList[] = {\"C-Programming\", \"Data Structure\", \"Database\", \"Python\", \"Java\", \"Operating System\", \"Compiler Design\", \"Android Development\"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); simpleListView = (ListView) findViewById(R.id.simpleListView); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.item_view, R.id.itemTextView, courseList); simpleListView.setAdapter(arrayAdapter); }}", "e": 29805, "s": 28927, "text": null }, { "code": null, "e": 29813, "s": 29805, "text": "android" }, { "code": null, "e": 29821, "s": 29813, "text": "Android" }, { "code": null, "e": 29826, "s": 29821, "text": "Java" }, { "code": null, "e": 29831, "s": 29826, "text": "Java" }, { "code": null, "e": 29839, "s": 29831, "text": "Android" }, { "code": null, "e": 29937, "s": 29839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29946, "s": 29937, "text": "Comments" }, { "code": null, "e": 29959, "s": 29946, "text": "Old Comments" }, { "code": null, "e": 30017, "s": 29959, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 30060, "s": 30017, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30102, "s": 30060, "text": "Content Providers in Android with Example" }, { "code": null, "e": 30133, "s": 30102, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 30191, "s": 30133, "text": "How to View and Locate SQLite Database in Android Studio?" }, { "code": null, "e": 30206, "s": 30191, "text": "Arrays in Java" }, { "code": null, "e": 30250, "s": 30206, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30272, "s": 30250, "text": "For-each loop in Java" }, { "code": null, "e": 30308, "s": 30272, "text": "Arrays.sort() in Java with examples" } ]
K Nearest Neighbor Algorithm In Python | by Cory Maklin | Towards Data Science
K-Nearest Neighbors, or KNN for short, is one of the simplest machine learning algorithms and is used in a wide array of institutions. KNN is a non-parametric, lazy learning algorithm. When we say a technique is non-parametric, it means that it does not make any assumptions about the underlying data. In other words, it makes its selection based off of the proximity to other data points regardless of what feature the numerical values represent. Being a lazy learning algorithm implies that there is little to no training phase. Therefore, we can immediately classify new data points as they present themselves. Pros: No assumptions about data Simple algorithm β€” easy to understand Can be used for classification and regression Cons: High memory requirement β€” All of the training data must be present in memory in order to calculate the closest K neighbors Sensitive to irrelevant features Sensitive to the scale of the data since we’re computing the distance to the closest K points Pick a value for K (i.e. 5). Pick a value for K (i.e. 5). 2. Take the K nearest neighbors of the new data point according to their Euclidean distance. 3. Among these neighbors, count the number of data points in each category and assign the new data point to the category where you counted the most neighbors. Let’s take a look at how we could go about classifying data using the K-Nearest Neighbors algorithm in Python. For this tutorial, we’ll be using the breast cancer dataset from the sklearn.datasets module. We need to start by importing the proceeding libraries. import numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.metrics import confusion_matrixfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitimport seaborn as snssns.set() The dataset classifies tumors into two categories (malignant and benign) and contains something like 30 features. In the real world, you’d look at the correlations and select a subset of features that plays the greatest role in determining whether a tumor is malignant or not. However, for the sake of simplicity, we’ll pick a couple at random. We must encode categorical data for it to be interpreted by the model (i.e. malignant = 0 and benign = 1). breast_cancer = load_breast_cancer()X = pd.DataFrame(breast_cancer.data, columns=breast_cancer.feature_names)X = X[['mean area', 'mean compactness']]y = pd.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names)y = pd.get_dummies(y, drop_first=True) As mentioned in another tutorial, the point of building a model, is to classify new data with undefined labels. Therefore, we need to put aside data to verify whether our model does a good job at classifying the data. By default, train_test_split sets aside 25% of the samples in the original dataset for testing. X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) The sklearn library has provided a layer of abstraction on top of Python. Therefore, in order to make use of the KNN algorithm, it’s sufficient to create an instance of KNeighborsClassifier. By default, the KNeighborsClassifier looks for the 5 nearest neighbors. We must explicitly tell the classifier to use Euclidean distance for determining the proximity between neighboring points. knn = KNeighborsClassifier(n_neighbors=5, metric='euclidean')knn.fit(X_train, y_train) Using our newly trained model, we predict whether a tumor is benign or not given its mean compactness and area. y_pred = knn.predict(X_test) We visually compare the predictions made by our model with the samples inside the testing set. sns.scatterplot( x='mean area', y='mean compactness', hue='benign', data=X_test.join(y_test, how='outer')) plt.scatter( X_test['mean area'], X_test['mean compactness'], c=y_pred, cmap='coolwarm', alpha=0.7) Another way of evaluating our model is to compute the confusion matrix. The numbers on the diagonal of the confusion matrix correspond to correct predictions whereas the others imply false positives and false negatives. confusion_matrix(y_test, y_pred) Given our confusion matrix, our model has an accuracy of 121/143 = 84.6%. The K Nearest Neighbors algorithm doesn’t require any additional training when new data becomes available. Rather it determines the K closest points according to some distance metric (the samples must reside in memory). Then, it looks at the target label for each of the neighbors and places the new found data point into the same category as the majority. Given that KNN computes distance, it’s imperative that we scale our data. In addition, since KNN disregards the underlying features, it’s our responsibility to filter out any features that are deemed irrelevant.
[ { "code": null, "e": 786, "s": 172, "text": "K-Nearest Neighbors, or KNN for short, is one of the simplest machine learning algorithms and is used in a wide array of institutions. KNN is a non-parametric, lazy learning algorithm. When we say a technique is non-parametric, it means that it does not make any assumptions about the underlying data. In other words, it makes its selection based off of the proximity to other data points regardless of what feature the numerical values represent. Being a lazy learning algorithm implies that there is little to no training phase. Therefore, we can immediately classify new data points as they present themselves." }, { "code": null, "e": 792, "s": 786, "text": "Pros:" }, { "code": null, "e": 818, "s": 792, "text": "No assumptions about data" }, { "code": null, "e": 856, "s": 818, "text": "Simple algorithm β€” easy to understand" }, { "code": null, "e": 902, "s": 856, "text": "Can be used for classification and regression" }, { "code": null, "e": 908, "s": 902, "text": "Cons:" }, { "code": null, "e": 1031, "s": 908, "text": "High memory requirement β€” All of the training data must be present in memory in order to calculate the closest K neighbors" }, { "code": null, "e": 1064, "s": 1031, "text": "Sensitive to irrelevant features" }, { "code": null, "e": 1158, "s": 1064, "text": "Sensitive to the scale of the data since we’re computing the distance to the closest K points" }, { "code": null, "e": 1187, "s": 1158, "text": "Pick a value for K (i.e. 5)." }, { "code": null, "e": 1216, "s": 1187, "text": "Pick a value for K (i.e. 5)." }, { "code": null, "e": 1309, "s": 1216, "text": "2. Take the K nearest neighbors of the new data point according to their Euclidean distance." }, { "code": null, "e": 1468, "s": 1309, "text": "3. Among these neighbors, count the number of data points in each category and assign the new data point to the category where you counted the most neighbors." }, { "code": null, "e": 1729, "s": 1468, "text": "Let’s take a look at how we could go about classifying data using the K-Nearest Neighbors algorithm in Python. For this tutorial, we’ll be using the breast cancer dataset from the sklearn.datasets module. We need to start by importing the proceeding libraries." }, { "code": null, "e": 2026, "s": 1729, "text": "import numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.metrics import confusion_matrixfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitimport seaborn as snssns.set()" }, { "code": null, "e": 2478, "s": 2026, "text": "The dataset classifies tumors into two categories (malignant and benign) and contains something like 30 features. In the real world, you’d look at the correlations and select a subset of features that plays the greatest role in determining whether a tumor is malignant or not. However, for the sake of simplicity, we’ll pick a couple at random. We must encode categorical data for it to be interpreted by the model (i.e. malignant = 0 and benign = 1)." }, { "code": null, "e": 2745, "s": 2478, "text": "breast_cancer = load_breast_cancer()X = pd.DataFrame(breast_cancer.data, columns=breast_cancer.feature_names)X = X[['mean area', 'mean compactness']]y = pd.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names)y = pd.get_dummies(y, drop_first=True)" }, { "code": null, "e": 3059, "s": 2745, "text": "As mentioned in another tutorial, the point of building a model, is to classify new data with undefined labels. Therefore, we need to put aside data to verify whether our model does a good job at classifying the data. By default, train_test_split sets aside 25% of the samples in the original dataset for testing." }, { "code": null, "e": 3133, "s": 3059, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)" }, { "code": null, "e": 3519, "s": 3133, "text": "The sklearn library has provided a layer of abstraction on top of Python. Therefore, in order to make use of the KNN algorithm, it’s sufficient to create an instance of KNeighborsClassifier. By default, the KNeighborsClassifier looks for the 5 nearest neighbors. We must explicitly tell the classifier to use Euclidean distance for determining the proximity between neighboring points." }, { "code": null, "e": 3606, "s": 3519, "text": "knn = KNeighborsClassifier(n_neighbors=5, metric='euclidean')knn.fit(X_train, y_train)" }, { "code": null, "e": 3718, "s": 3606, "text": "Using our newly trained model, we predict whether a tumor is benign or not given its mean compactness and area." }, { "code": null, "e": 3747, "s": 3718, "text": "y_pred = knn.predict(X_test)" }, { "code": null, "e": 3842, "s": 3747, "text": "We visually compare the predictions made by our model with the samples inside the testing set." }, { "code": null, "e": 3961, "s": 3842, "text": "sns.scatterplot( x='mean area', y='mean compactness', hue='benign', data=X_test.join(y_test, how='outer'))" }, { "code": null, "e": 4076, "s": 3961, "text": "plt.scatter( X_test['mean area'], X_test['mean compactness'], c=y_pred, cmap='coolwarm', alpha=0.7)" }, { "code": null, "e": 4296, "s": 4076, "text": "Another way of evaluating our model is to compute the confusion matrix. The numbers on the diagonal of the confusion matrix correspond to correct predictions whereas the others imply false positives and false negatives." }, { "code": null, "e": 4329, "s": 4296, "text": "confusion_matrix(y_test, y_pred)" }, { "code": null, "e": 4403, "s": 4329, "text": "Given our confusion matrix, our model has an accuracy of 121/143 = 84.6%." } ]
Drop Empty Columns in Pandas - GeeksforGeeks
23 Dec, 2020 In this article, we will try to see different ways of removing the Empty column, Null column, and zeros value column. First, We will create a sample data frame and then we will perform our operations in subsequent examples by the end you will get a strong hand knowledge on how to handle this situation with pandas. Approach: Import required python library. Create a sample Data Frame. Use the Pandas dropna() method, It allows the user to analyze and drop Rows/Columns with Null values in different ways. Display updated Data Frame. Syntax: DataFrameName.dropna(axis=0, how=’any’, inplace=False) Parameters: axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and β€˜index’ or β€˜columns’ for String. how: how takes string value of two kinds only (β€˜any’ or β€˜all’). β€˜any’ drops the row/column if ANY value is Null and β€˜all’ drops only if ALL values are null. inplace: It is a boolean which makes the changes in the data frame itself if True. Sample Data: This is the sample data frame on which we will perform different operations. Python3 # import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], "Gender": ["", "", ""], "Age": [0, 0, 0]})Mydataframe['Department'] = np.nan # show the dataframeprint(Mydataframe) Output: Example 1: Remove all null value column. Python3 # import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], "Gender": ["", "", ""], "Age": [0, 0, 0]}) Mydataframe['Department'] = np.nan display(Mydataframe) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe) Output: Example 2: Replace all Empty places with null and then Remove all null values column with dropna function. Python3 # import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], "Gender": ["", "", ""], "Age": [0, 0, 0]}) Mydataframe['Department'] = np.nandisplay(Mydataframe) nan_value = float("NaN")Mydataframe.replace("", nan_value, inplace=True) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe) Output: Example 3: Replace all zeros places with null and then Remove all null values column with dropna function. Python3 # import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], "Gender": ["", "", ""], "Age": [0, 0, 0]}) Mydataframe['Department'] = np.nandisplay(Mydataframe) nan_value = float("NaN")Mydataframe.replace(0, nan_value, inplace=True) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe) Output: Example 4: Replace all zeros and empty places with null and then Remove all null values column with dropna function. Python3 # import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], "Gender": ["", "", ""], "Age": [0, 0, 0]}) Mydataframe['Department'] = np.nandisplay(Mydataframe) nan_value = float("NaN")Mydataframe.replace(0, nan_value, inplace=True)Mydataframe.replace("", nan_value, inplace=True) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe) Output: Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Dec, 2020" }, { "code": null, "e": 24608, "s": 24292, "text": "In this article, we will try to see different ways of removing the Empty column, Null column, and zeros value column. First, We will create a sample data frame and then we will perform our operations in subsequent examples by the end you will get a strong hand knowledge on how to handle this situation with pandas." }, { "code": null, "e": 24618, "s": 24608, "text": "Approach:" }, { "code": null, "e": 24650, "s": 24618, "text": "Import required python library." }, { "code": null, "e": 24678, "s": 24650, "text": "Create a sample Data Frame." }, { "code": null, "e": 24798, "s": 24678, "text": "Use the Pandas dropna() method, It allows the user to analyze and drop Rows/Columns with Null values in different ways." }, { "code": null, "e": 24826, "s": 24798, "text": "Display updated Data Frame." }, { "code": null, "e": 24889, "s": 24826, "text": "Syntax: DataFrameName.dropna(axis=0, how=’any’, inplace=False)" }, { "code": null, "e": 24901, "s": 24889, "text": "Parameters:" }, { "code": null, "e": 25025, "s": 24901, "text": "axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and β€˜index’ or β€˜columns’ for String." }, { "code": null, "e": 25182, "s": 25025, "text": "how: how takes string value of two kinds only (β€˜any’ or β€˜all’). β€˜any’ drops the row/column if ANY value is Null and β€˜all’ drops only if ALL values are null." }, { "code": null, "e": 25265, "s": 25182, "text": "inplace: It is a boolean which makes the changes in the data frame itself if True." }, { "code": null, "e": 25278, "s": 25265, "text": "Sample Data:" }, { "code": null, "e": 25355, "s": 25278, "text": "This is the sample data frame on which we will perform different operations." }, { "code": null, "e": 25363, "s": 25355, "text": "Python3" }, { "code": "# import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], \"Gender\": [\"\", \"\", \"\"], \"Age\": [0, 0, 0]})Mydataframe['Department'] = np.nan # show the dataframeprint(Mydataframe)", "e": 25691, "s": 25363, "text": null }, { "code": null, "e": 25699, "s": 25691, "text": "Output:" }, { "code": null, "e": 25710, "s": 25699, "text": "Example 1:" }, { "code": null, "e": 25740, "s": 25710, "text": "Remove all null value column." }, { "code": null, "e": 25748, "s": 25740, "text": "Python3" }, { "code": "# import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], \"Gender\": [\"\", \"\", \"\"], \"Age\": [0, 0, 0]}) Mydataframe['Department'] = np.nan display(Mydataframe) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe)", "e": 26155, "s": 25748, "text": null }, { "code": null, "e": 26163, "s": 26155, "text": "Output:" }, { "code": null, "e": 26174, "s": 26163, "text": "Example 2:" }, { "code": null, "e": 26270, "s": 26174, "text": "Replace all Empty places with null and then Remove all null values column with dropna function." }, { "code": null, "e": 26278, "s": 26270, "text": "Python3" }, { "code": "# import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], \"Gender\": [\"\", \"\", \"\"], \"Age\": [0, 0, 0]}) Mydataframe['Department'] = np.nandisplay(Mydataframe) nan_value = float(\"NaN\")Mydataframe.replace(\"\", nan_value, inplace=True) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe)", "e": 26757, "s": 26278, "text": null }, { "code": null, "e": 26765, "s": 26757, "text": "Output:" }, { "code": null, "e": 26776, "s": 26765, "text": "Example 3:" }, { "code": null, "e": 26872, "s": 26776, "text": "Replace all zeros places with null and then Remove all null values column with dropna function." }, { "code": null, "e": 26880, "s": 26872, "text": "Python3" }, { "code": "# import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], \"Gender\": [\"\", \"\", \"\"], \"Age\": [0, 0, 0]}) Mydataframe['Department'] = np.nandisplay(Mydataframe) nan_value = float(\"NaN\")Mydataframe.replace(0, nan_value, inplace=True) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe)", "e": 27358, "s": 26880, "text": null }, { "code": null, "e": 27366, "s": 27358, "text": "Output:" }, { "code": null, "e": 27377, "s": 27366, "text": "Example 4:" }, { "code": null, "e": 27483, "s": 27377, "text": "Replace all zeros and empty places with null and then Remove all null values column with dropna function." }, { "code": null, "e": 27491, "s": 27483, "text": "Python3" }, { "code": "# import required librariesimport numpy as npimport pandas as pd # create a DataframeMydataframe = pd.DataFrame({'FirstName': ['Vipul', 'Ashish', 'Milan'], \"Gender\": [\"\", \"\", \"\"], \"Age\": [0, 0, 0]}) Mydataframe['Department'] = np.nandisplay(Mydataframe) nan_value = float(\"NaN\")Mydataframe.replace(0, nan_value, inplace=True)Mydataframe.replace(\"\", nan_value, inplace=True) Mydataframe.dropna(how='all', axis=1, inplace=True) # show the dataframedisplay(Mydataframe)", "e": 28017, "s": 27491, "text": null }, { "code": null, "e": 28025, "s": 28017, "text": "Output:" }, { "code": null, "e": 28032, "s": 28025, "text": "Picked" }, { "code": null, "e": 28056, "s": 28032, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28070, "s": 28056, "text": "Python-pandas" }, { "code": null, "e": 28077, "s": 28070, "text": "Python" }, { "code": null, "e": 28175, "s": 28077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28207, "s": 28175, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28249, "s": 28207, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28305, "s": 28249, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28347, "s": 28305, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28402, "s": 28347, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28433, "s": 28402, "text": "Python | os.path.join() method" }, { "code": null, "e": 28455, "s": 28433, "text": "Defaultdict in Python" }, { "code": null, "e": 28484, "s": 28455, "text": "Create a directory in Python" }, { "code": null, "e": 28523, "s": 28484, "text": "Python | Get unique values from a list" } ]
Sentiment Analysis on Amazon Reviews | by Enes Gokce | Towards Data Science
Understanding the data better is one of the crucial steps in data analysis. In this study, I will analyze the Amazon reviews. The reviews are unstructured. In other words, the text is unorganized. Sentiment analysis, however, helps us make sense of all this unstructured text by automatically tagging it. Sentiment analysis helps us to process huge amounts of data in an efficient and cost-effective way. This study in part of the bigger study. In order to check feature extraction and data cleaning part (previous step), you can check my previous posting. You can find all Python codes for this study here. In this study, I will: Give a brief theoretical background about sentiment analysis Perform sentiment analysis Provide python codes for each step. For performing sentiment analysis, we will use NLTK package of the Python. Christopher Manning says, β€œNLTK is sort of the Swiss Army Knife of NLP meaning that it’s not terribly good for anything. But it has a lot of basic tools.” For accessing Wordnet, it’s an easy solution. WordNet is a large lexical database of English developed by the Princeton University. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations (Fellbaum, 1998). In other words, Wordnet can be described as online thesaurus. It tells you about word meanings and relationships between word meanings. Wordnet was first created in 1985, and still in improvement. Wordnet can be obtained by: import nltknltk.download('wordnet') In this study, we will use two main sentiment classifiers: 1. Polarity 2. Subjectivity The TextBlob package for Python is a convenient way to perform sentiment analysis. When calculating sentiment for a single word, TextBlob takes average for the entire text. For heteronym words, Textblob does not negotiate with different meanings. In the other words, only the most common meaning of a word in entire text is taken into consideration. For making all these modelling, Textblob uses WordNet Database. Polarity is float which lies in the range of [-1,1] where 1 means positive statement and -1 means a negative statement. Figure 1 shows the distribution of polarity score in reviews. Most of the reviews are on positive side of the plot (Fig. 1). # Create quick lambda functions to find the polarity of each review# Terminal / Anaconda Navigator: conda install -c conda-forge textblobfrom textblob import TextBlobdf['Text']= df['Text'].astype(str) #Make sure about the correct data typepol = lambda x: TextBlob(x).sentiment.polaritydf['polarity'] = df['Text'].apply(pol) # depending on the size of your data, this step may take some time.import matplotlib.pyplot as pltimport seaborn as snsnum_bins = 50plt.figure(figsize=(10,6))n, bins, patches = plt.hist(df.polarity, num_bins, facecolor='blue', alpha=0.5)plt.xlabel('Polarity')plt.ylabel('Number of Reviews')plt.title('Histogram of Polarity Score')plt.show(); In Figure 2, it can be observed that good reviews (Good reviews =1) have higher polarity compared to bad reviews. On the other hand, good reviews also have higher number of negative polarity reviews. This is an unbalanced data and number of good reviews are higher than bad reviews. Therefore, it is not much surprising to see a greater number of extreme values in this category. plt.figure(figsize=(10,6))sns.boxenplot(x=’Good_reviews’, y=’polarity’, data=df)plt.show(); As we can see from this box plot, we have some good reviews that has very low polarity (very negative) Some bad reviews that has high polarity (positive statement) Let’s check some of them: df.loc[(df.polarity == 1 & (df.Good_reviews == 0))].Text.head(10).tolist() When Table 1 is examined, it can be seen that some of the reviews are actually positive but somehow got bad review scores. Keep in mind that these are extreme case reviews, and it is not surprising to see that their rating doesn’t make much sense. Punctuation vs Polarity: From Figure 3, we can see that when the value of punctuation is low, polarity is higher. A possible explanation for this is people who are paying more attention to punctuation tend to be more balanced in their product evaluation. Despite outliers, the average polarity score is almost a line, and it is around 0.25. This information is consistent with Figure 1. We can also see that there are extreme cases in both direction of the polarity (Fig. 3) plt.figure(figsize=(15,8))df3= df.loc[df.upper <= 50]sns.boxenplot(x='upper', y='polarity', data=df3)plt.xlabel('Punctuation', fontsize=13)plt.ylabel('Polarity Score', fontsize=13)plt.title('Punctuation vs Polarity Plot', fontsize=15)plt.show(); Helpfulness vs Polarity: Figure 4 presents the relation between helpfulness and polarity in the Good Reviews category. There are interesting outliers. For example, some reviews have the lowest polarity (most negative) but have a good rating (good review is 1) and helpfulness is more than 3. This combination is a controversial case. When we look at these cases more closely, we can see that those reviews are not using negative words for the purchase (Table 2). Those negative expressions are for comparison with other purchases. For now, NLP methods are not doing great at handling this kind of usage of words. plt.figure(figsize=(12,6))df_sub= df.loc[df.HelpfulnessNumerator <=30]sns.boxenplot(x='HelpfulnessNumerator', y='polarity', hue='Good_reviews', data=df_sub)plt.xlabel('Helpfulness Numerator', fontsize=13)plt.ylabel('Polarity Score', fontsize=13)plt.title('Helpfulness Numerator vs Polarity', fontsize=15)plt.show(); Subjectivity is used for individual sentences to determine whether a sentence expresses an opinion or not. In terms of subjectivity, textual information in the world can be broadly categorized into two main types: facts and opinions. Subjective sentences generally refer to personal opinion, emotion, or judgment whereas objective refers to factual information. Facts are objective expressions about entities, events, and properties. Opinions are usually subjective expressions that describe people’s sentiments, appraisals, or feelings toward entities, events, and their properties (Liu, 2010). In sentiment analysis, subjectivity is also a float that lies in the range of [0,1]. When it is close to 0, it is more about facts. When subjectivity increases, it comes close to be an opinion. In the data set, the distribution of subjectivity scores for the reviews are similar to a normal distribution (Fig. 5). When we examined the relation between subjectivity, polarity, and Good Reviews features we can see that subjectivity and polarity shows a funneling pattern (Fig. 6). It can also be observed that low subjectivity score reviews are also neutral reviews in terms of polarity. For creating subjectivity scores: sub = lambda x: TextBlob(x).sentiment.subjectivitydf['subjectivity'] = df['Text'].apply(sub)df.sample(10) Checking the distribution of the subjectivity score: # Density Plot and Histogram of subjectivityplt.figure(figsize=(10,5))sns.distplot(df['subjectivity'], hist=True, kde=True,bins=int(30), color = 'darkblue',hist_kws={'edgecolor':'black'},kde_kws={'linewidth': 4})plt.xlim([-0.001,1.001])plt.xlabel('Subjectivity', fontsize=13)plt.ylabel('Frequency', fontsize=13)plt.title('Distribution of Subjectivity Score', fontsize=15) plt.figure(figsize=(10,6))sns.scatterplot(x='polarity', y='subjectivity', hue="Good_reviews", data=df)plt.xlabel('Polarity', fontsize=13)plt.ylabel('Subjectivity', fontsize=13)plt.title('Polarity vs Subjectivity', fontsize=15)plt.show(); Figure 7 is a presentation of how polarity and subjectivity are affected by the rating of the reviews (Good review feature). While reading this plot, we need to keep in mind that the y-axis is in a very small range. We can see that the mean subjectivity score difference between the two groups is negligible. (You can find the codes for this plot on my GitHub repo) In order to understand our data better, we need to check it from a different perspective. There are some reviews that can be considered as an extreme cases. For example, Table 3 presents 10 reviews that have the highest polarity (most positive sentiment) but the β€˜good review’ value is 0, and the most subjective (opinion). These tweets are hard to score for sentiment analysis algorithms. It is not surprising that they have the most positive score (polarity =1). df.loc[(df["Good_reviews"] == 0) & (df.polarity == 1 ) & (df.subjectivity ==1), "Text"].head(10).tolist() In order to understand how the data is shaped and how the sentiment analysis works, let’s examine more reviews with different criteria (Table 4 and 5). df.loc[(df["Good_reviews"] == 1) & (df.polarity == 1 ) & (df.subjectivity ==1), "Text"].sample(5).tolist() df.loc[(df["Good_reviews"] == 1) & (df.polarity == -1 ) & (df.subjectivity ==1), "Text"].sample(5).tolist() In conclusion, with this study, I tried to show how sentiment analysis works by applying it on Amazon review data. In the next study, I will show how to perform topic analysis with Latent Dirichlet Allocation (LDA) by explaining it step by step. Happy analysis! *Special thanks to my friend Tabitha Stickel for proofreading this article. My further content recommendations for sentiment analysis: Alice Zhao: https://youtu.be/xvqsFTUsOmc?t=4125 Calculating Polarity and Subjectivity: https://planspace.org/20150607-textblob_sentiment/ References: Fellbaum, C. (1998). WordNet: An Electronic Lexical Database. Bradford Books. Guibon, G., Ochs, M., & Bellot, P. (2016, June). From emojis to sentiment analysis. Liu, B. (2010). Sentiment analysis and subjectivity. Handbook of natural language processing, 2(2010), 627–666. Stanford CS224N: NLP with Deep Learning
[ { "code": null, "e": 452, "s": 47, "text": "Understanding the data better is one of the crucial steps in data analysis. In this study, I will analyze the Amazon reviews. The reviews are unstructured. In other words, the text is unorganized. Sentiment analysis, however, helps us make sense of all this unstructured text by automatically tagging it. Sentiment analysis helps us to process huge amounts of data in an efficient and cost-effective way." }, { "code": null, "e": 678, "s": 452, "text": "This study in part of the bigger study. In order to check feature extraction and data cleaning part (previous step), you can check my previous posting. You can find all Python codes for this study here. In this study, I will:" }, { "code": null, "e": 739, "s": 678, "text": "Give a brief theoretical background about sentiment analysis" }, { "code": null, "e": 766, "s": 739, "text": "Perform sentiment analysis" }, { "code": null, "e": 802, "s": 766, "text": "Provide python codes for each step." }, { "code": null, "e": 1078, "s": 802, "text": "For performing sentiment analysis, we will use NLTK package of the Python. Christopher Manning says, β€œNLTK is sort of the Swiss Army Knife of NLP meaning that it’s not terribly good for anything. But it has a lot of basic tools.” For accessing Wordnet, it’s an easy solution." }, { "code": null, "e": 1585, "s": 1078, "text": "WordNet is a large lexical database of English developed by the Princeton University. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations (Fellbaum, 1998). In other words, Wordnet can be described as online thesaurus. It tells you about word meanings and relationships between word meanings. Wordnet was first created in 1985, and still in improvement." }, { "code": null, "e": 1613, "s": 1585, "text": "Wordnet can be obtained by:" }, { "code": null, "e": 1649, "s": 1613, "text": "import nltknltk.download('wordnet')" }, { "code": null, "e": 1708, "s": 1649, "text": "In this study, we will use two main sentiment classifiers:" }, { "code": null, "e": 1720, "s": 1708, "text": "1. Polarity" }, { "code": null, "e": 1736, "s": 1720, "text": "2. Subjectivity" }, { "code": null, "e": 2150, "s": 1736, "text": "The TextBlob package for Python is a convenient way to perform sentiment analysis. When calculating sentiment for a single word, TextBlob takes average for the entire text. For heteronym words, Textblob does not negotiate with different meanings. In the other words, only the most common meaning of a word in entire text is taken into consideration. For making all these modelling, Textblob uses WordNet Database." }, { "code": null, "e": 2395, "s": 2150, "text": "Polarity is float which lies in the range of [-1,1] where 1 means positive statement and -1 means a negative statement. Figure 1 shows the distribution of polarity score in reviews. Most of the reviews are on positive side of the plot (Fig. 1)." }, { "code": null, "e": 3061, "s": 2395, "text": "# Create quick lambda functions to find the polarity of each review# Terminal / Anaconda Navigator: conda install -c conda-forge textblobfrom textblob import TextBlobdf['Text']= df['Text'].astype(str) #Make sure about the correct data typepol = lambda x: TextBlob(x).sentiment.polaritydf['polarity'] = df['Text'].apply(pol) # depending on the size of your data, this step may take some time.import matplotlib.pyplot as pltimport seaborn as snsnum_bins = 50plt.figure(figsize=(10,6))n, bins, patches = plt.hist(df.polarity, num_bins, facecolor='blue', alpha=0.5)plt.xlabel('Polarity')plt.ylabel('Number of Reviews')plt.title('Histogram of Polarity Score')plt.show();" }, { "code": null, "e": 3441, "s": 3061, "text": "In Figure 2, it can be observed that good reviews (Good reviews =1) have higher polarity compared to bad reviews. On the other hand, good reviews also have higher number of negative polarity reviews. This is an unbalanced data and number of good reviews are higher than bad reviews. Therefore, it is not much surprising to see a greater number of extreme values in this category." }, { "code": null, "e": 3533, "s": 3441, "text": "plt.figure(figsize=(10,6))sns.boxenplot(x=’Good_reviews’, y=’polarity’, data=df)plt.show();" }, { "code": null, "e": 3567, "s": 3533, "text": "As we can see from this box plot," }, { "code": null, "e": 3636, "s": 3567, "text": "we have some good reviews that has very low polarity (very negative)" }, { "code": null, "e": 3697, "s": 3636, "text": "Some bad reviews that has high polarity (positive statement)" }, { "code": null, "e": 3723, "s": 3697, "text": "Let’s check some of them:" }, { "code": null, "e": 3798, "s": 3723, "text": "df.loc[(df.polarity == 1 & (df.Good_reviews == 0))].Text.head(10).tolist()" }, { "code": null, "e": 4046, "s": 3798, "text": "When Table 1 is examined, it can be seen that some of the reviews are actually positive but somehow got bad review scores. Keep in mind that these are extreme case reviews, and it is not surprising to see that their rating doesn’t make much sense." }, { "code": null, "e": 4521, "s": 4046, "text": "Punctuation vs Polarity: From Figure 3, we can see that when the value of punctuation is low, polarity is higher. A possible explanation for this is people who are paying more attention to punctuation tend to be more balanced in their product evaluation. Despite outliers, the average polarity score is almost a line, and it is around 0.25. This information is consistent with Figure 1. We can also see that there are extreme cases in both direction of the polarity (Fig. 3)" }, { "code": null, "e": 4767, "s": 4521, "text": "plt.figure(figsize=(15,8))df3= df.loc[df.upper <= 50]sns.boxenplot(x='upper', y='polarity', data=df3)plt.xlabel('Punctuation', fontsize=13)plt.ylabel('Polarity Score', fontsize=13)plt.title('Punctuation vs Polarity Plot', fontsize=15)plt.show();" }, { "code": null, "e": 5380, "s": 4767, "text": "Helpfulness vs Polarity: Figure 4 presents the relation between helpfulness and polarity in the Good Reviews category. There are interesting outliers. For example, some reviews have the lowest polarity (most negative) but have a good rating (good review is 1) and helpfulness is more than 3. This combination is a controversial case. When we look at these cases more closely, we can see that those reviews are not using negative words for the purchase (Table 2). Those negative expressions are for comparison with other purchases. For now, NLP methods are not doing great at handling this kind of usage of words." }, { "code": null, "e": 5696, "s": 5380, "text": "plt.figure(figsize=(12,6))df_sub= df.loc[df.HelpfulnessNumerator <=30]sns.boxenplot(x='HelpfulnessNumerator', y='polarity', hue='Good_reviews', data=df_sub)plt.xlabel('Helpfulness Numerator', fontsize=13)plt.ylabel('Polarity Score', fontsize=13)plt.title('Helpfulness Numerator vs Polarity', fontsize=15)plt.show();" }, { "code": null, "e": 6292, "s": 5696, "text": "Subjectivity is used for individual sentences to determine whether a sentence expresses an opinion or not. In terms of subjectivity, textual information in the world can be broadly categorized into two main types: facts and opinions. Subjective sentences generally refer to personal opinion, emotion, or judgment whereas objective refers to factual information. Facts are objective expressions about entities, events, and properties. Opinions are usually subjective expressions that describe people’s sentiments, appraisals, or feelings toward entities, events, and their properties (Liu, 2010)." }, { "code": null, "e": 6879, "s": 6292, "text": "In sentiment analysis, subjectivity is also a float that lies in the range of [0,1]. When it is close to 0, it is more about facts. When subjectivity increases, it comes close to be an opinion. In the data set, the distribution of subjectivity scores for the reviews are similar to a normal distribution (Fig. 5). When we examined the relation between subjectivity, polarity, and Good Reviews features we can see that subjectivity and polarity shows a funneling pattern (Fig. 6). It can also be observed that low subjectivity score reviews are also neutral reviews in terms of polarity." }, { "code": null, "e": 6913, "s": 6879, "text": "For creating subjectivity scores:" }, { "code": null, "e": 7019, "s": 6913, "text": "sub = lambda x: TextBlob(x).sentiment.subjectivitydf['subjectivity'] = df['Text'].apply(sub)df.sample(10)" }, { "code": null, "e": 7072, "s": 7019, "text": "Checking the distribution of the subjectivity score:" }, { "code": null, "e": 7444, "s": 7072, "text": "# Density Plot and Histogram of subjectivityplt.figure(figsize=(10,5))sns.distplot(df['subjectivity'], hist=True, kde=True,bins=int(30), color = 'darkblue',hist_kws={'edgecolor':'black'},kde_kws={'linewidth': 4})plt.xlim([-0.001,1.001])plt.xlabel('Subjectivity', fontsize=13)plt.ylabel('Frequency', fontsize=13)plt.title('Distribution of Subjectivity Score', fontsize=15)" }, { "code": null, "e": 7682, "s": 7444, "text": "plt.figure(figsize=(10,6))sns.scatterplot(x='polarity', y='subjectivity', hue=\"Good_reviews\", data=df)plt.xlabel('Polarity', fontsize=13)plt.ylabel('Subjectivity', fontsize=13)plt.title('Polarity vs Subjectivity', fontsize=15)plt.show();" }, { "code": null, "e": 8048, "s": 7682, "text": "Figure 7 is a presentation of how polarity and subjectivity are affected by the rating of the reviews (Good review feature). While reading this plot, we need to keep in mind that the y-axis is in a very small range. We can see that the mean subjectivity score difference between the two groups is negligible. (You can find the codes for this plot on my GitHub repo)" }, { "code": null, "e": 8513, "s": 8048, "text": "In order to understand our data better, we need to check it from a different perspective. There are some reviews that can be considered as an extreme cases. For example, Table 3 presents 10 reviews that have the highest polarity (most positive sentiment) but the β€˜good review’ value is 0, and the most subjective (opinion). These tweets are hard to score for sentiment analysis algorithms. It is not surprising that they have the most positive score (polarity =1)." }, { "code": null, "e": 8619, "s": 8513, "text": "df.loc[(df[\"Good_reviews\"] == 0) & (df.polarity == 1 ) & (df.subjectivity ==1), \"Text\"].head(10).tolist()" }, { "code": null, "e": 8771, "s": 8619, "text": "In order to understand how the data is shaped and how the sentiment analysis works, let’s examine more reviews with different criteria (Table 4 and 5)." }, { "code": null, "e": 8878, "s": 8771, "text": "df.loc[(df[\"Good_reviews\"] == 1) & (df.polarity == 1 ) & (df.subjectivity ==1), \"Text\"].sample(5).tolist()" }, { "code": null, "e": 8986, "s": 8878, "text": "df.loc[(df[\"Good_reviews\"] == 1) & (df.polarity == -1 ) & (df.subjectivity ==1), \"Text\"].sample(5).tolist()" }, { "code": null, "e": 9232, "s": 8986, "text": "In conclusion, with this study, I tried to show how sentiment analysis works by applying it on Amazon review data. In the next study, I will show how to perform topic analysis with Latent Dirichlet Allocation (LDA) by explaining it step by step." }, { "code": null, "e": 9248, "s": 9232, "text": "Happy analysis!" }, { "code": null, "e": 9324, "s": 9248, "text": "*Special thanks to my friend Tabitha Stickel for proofreading this article." }, { "code": null, "e": 9383, "s": 9324, "text": "My further content recommendations for sentiment analysis:" }, { "code": null, "e": 9431, "s": 9383, "text": "Alice Zhao: https://youtu.be/xvqsFTUsOmc?t=4125" }, { "code": null, "e": 9521, "s": 9431, "text": "Calculating Polarity and Subjectivity: https://planspace.org/20150607-textblob_sentiment/" }, { "code": null, "e": 9533, "s": 9521, "text": "References:" }, { "code": null, "e": 9695, "s": 9533, "text": "Fellbaum, C. (1998). WordNet: An Electronic Lexical Database. Bradford Books. Guibon, G., Ochs, M., & Bellot, P. (2016, June). From emojis to sentiment analysis." }, { "code": null, "e": 9807, "s": 9695, "text": "Liu, B. (2010). Sentiment analysis and subjectivity. Handbook of natural language processing, 2(2010), 627–666." } ]
Spark MLlib on AWS Glue. Distributed ML on AWS that’s ready to... | by John Elliott | Towards Data Science
AWS pushes Sagemaker as its machine learning platform. However, Spark’s MLlib is a comprehensive library that runs distributed ML natively on AWS Glue β€” and provides a viable alternative to their primary ML platform. One of the big benefits of Sagemaker is that it easily supports experimentation via its Jupyter Notebooks. But operationalising your Sagemaker ML can be difficult, particularly if you need to include ETL processing at the start of your pipeline. In this situation, Apache Spark’s MLlib running on AWS Glue can be a good option β€” by its very nature, it is immediately operationalised, integrated with ETL pre-processing and ready to be used in production for an end-to-end machine learning pipeline. By its very nature, [AWS Glue] is immediately operationalised, integrated with ETL pre-processing and ready to be used in production for an end-to-end machine learning pipeline AWS Glue is a managed Spark ETL platform for processing large volumes of data via distributed machines. MLlib comes as part of Spark 2.4, which is the default version on AWS Glue. There is no need to add libraries to use MLlib within AWS Glue. As a distributed ETL platform, AWS Glue (via Spark) allows you to perform your data pre-processing at large scale easily. Glue Studio provides a nice UI for building directed acyclic graphs that represent the flow of data through each pre-processing step (see above image for an example). From the graph UI, you can rename fields, convert types, filter records and remove columns. However, some of the more complex data processing activities require a β€˜Custom Transform’ to be added. Actions that require a Custom Transform include: Running MLlib functions, such as TF-IDF or models such as Random Forest or Gradient Boosted Tree algorithmsAggregating values, such as generating count, mean and sum valuesComplex column transforms such as one-hot encoding or concatenating values Running MLlib functions, such as TF-IDF or models such as Random Forest or Gradient Boosted Tree algorithms Aggregating values, such as generating count, mean and sum values Complex column transforms such as one-hot encoding or concatenating values After performing your pre-processing and featurization using ETL transforms, you need to train your data. To access MLlib in AWS Glue, you just need to add the import statements and you’re ready to go. Below is an example of how to train a regression Decision Tree model in a AWS Glue Studio Custom Transform using PySpark: # Get the dataframe. Ensure there's a 'features' column.df = dfc.select(list(dfc.keys())[0]).toDF()# Get the logger for Cloudwatch Logslogger = glueContext.get_logger()from pyspark.ml import Pipelinefrom pyspark.ml.regression import DecisionTreeRegressorfrom pyspark.ml.evaluation import RegressionEvaluator# Split data into training and test sets(trainingData, testData) = df.randomSplit([0.7, 0.3])# Create a DecisionTree model.dt = DecisionTreeRegressor(featuresCol="features")# Create a pipeline to wrap the DecisionTree pipeline = Pipeline(stages=[dt])# Train model.model = pipeline.fit(trainingData)# Make predictions.predictions = model.transform(testData)# Select (prediction, true label) and compute test errorevaluator = RegressionEvaluator( labelCol="label", predictionCol="prediction", metricName="rmse")rmse = evaluator.evaluate(predictions)logger.info("Root Mean Squared Error (RMSE) on test data = %g" % rmse) In the above code, the root-mean-squared error (RMSE) is logged out to Cloudwatch Logs. To use the model to predict, the simplest option is to use the same Custom Transform and run model.transform on a dataframe of unseen inference data. To then use the predictions, you will need to return them from the Custom Transform in a DynamicFrameCollection (see code snippet at the bottom of this article). There are a few gotchas to look out for when running Spark’s MLlib in AWS Glue: Experimentation can be slow and difficult. Iterating and debugging can be frustrating because at a minimum each job takes one minute to run. When experimenting, run on a reduced data set to speed up the process (it will still take 1 minute+). Reduce the number of workers to 2 and use G.1X to save money. Disable bookmarks and retries.To help with debugging, you can log out information to Cloudwatch from your Custom Transform. You will have to go to the /aws-glue/jobs/logs-v2 log group on Cloudwatch, then open the log stream that ends with β€˜-driver’ to see the logged-out values. Below is a PySpark example of a Glue Studio Custom Transform with Cloudwatch logging set up.AWS Glue Developer Endpoints may help with experimentation and debugging. These allow you to run a development notebook on a Spark cluster and speed up your development iterations when writing code. The main downside is that they are expensive (and can take 5–15 minutes to spin-up the cluster). Note that they charge by the second, so can be significantly more expensive than just executing your jobs directly. One option is to use Developer Endpoints while you are learning Spark, then move over to directly executing jobs in AWS Glue after you are familiar with writing Spark code.While you can run your ML training and predictions in the same job as your featurization ETL, you may want to separate them into two jobs. By separating them into two jobs, you can separate their configurations. AWS Glue provides two worker types: G.1X and G.2X. You may find that G.1X is adequate for ETL, but G.2X may be more suitable for ML training and inference as each worker has twice as much memory available.Only batch inference works on AWS Glue β€” real-time inference isn’t an option here. Use Sagemaker endpoints for that use case.MLlib on AWS Glue easily allows you to retrain your whole dataset, then perform inference in a single job. Training is probably the most expensive step, however, you can benefit from better predictions by retraining before batch inferenceTry to use native Spark dataframes and libraries, rather than, for example, Pandas dataframes. This will allow you to leverage the distributed capabilities of Spark much better.There are two APIs available in MLlib β€” the dataframe-based API and the RDD-based API. You should use the dataframe based approaches as much as possible. Likewise, try to avoid using user-defined functions (UDFs). Both UDFs and RDD-based capabilities are slower than native dataframe methods.SparseVector is an efficient way of representing sparse datasets (i.e. data sources with a large number of columns and most values being zero). A common example of this is the output of TF-IDF when performing natural language processing. Using a SparseVector column avoids adding hundreds or thousands of columns to a dataframe (which would most likely cause your job to fail due to out-of-memory or timeout).Some dataframe column types created by MLlib cannot be written out of a Custom Transform without being cast to integer or string first. You may get an error such as β€˜An error occurred while calling o341.toDF. org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 (of class org.apache.spark.ml.linalg.VectorUDT)’ when this happens.In AWS Glue reading to and from S3 is much easier than any other data source / destination. Directly connecting to a database may be more trouble than it’s worth.You will most likely need to make use of Glue Crawlers to learn your schema on S3. You will need to re-run the crawler each time your data changes. Use partition keys in your S3 path/key and partition predicates on your AWS Glue β€˜S3 data source’ input node to filter the data to a specific date.JSON and CSV can be useful data types when developing as you can see the inputs and outputs. However, they are slow and large. For production, consider switching to Parquet format inputs and outputs.Exporting a SparseVector column (that has been cast to String) to CSV leads to an invalid CSV structure. Parquet format works instead.Be careful to distinguish between the new dataframe-based API and the older RDD-based API. Ensure you import the correct classes. In PySpark, you should import β€˜pyspark.ml.linalg’ rather than β€˜pyspark.mllib.linalg’ to access the newer API. If you mix-up types, you may get strange errors such as β€œIllegalArgumentException: β€˜requirement failed: Column features must be of type struct<type:tinyint,size:int,indices:array<int>,values:array<double>> but was actually struct<type:tinyint,size:int,indices:array<int>,values:array<double>>.’. Both of those values look the same but the difference is that they’re using an incompatible version of the object from the wrong API. Experimentation can be slow and difficult. Iterating and debugging can be frustrating because at a minimum each job takes one minute to run. When experimenting, run on a reduced data set to speed up the process (it will still take 1 minute+). Reduce the number of workers to 2 and use G.1X to save money. Disable bookmarks and retries. To help with debugging, you can log out information to Cloudwatch from your Custom Transform. You will have to go to the /aws-glue/jobs/logs-v2 log group on Cloudwatch, then open the log stream that ends with β€˜-driver’ to see the logged-out values. Below is a PySpark example of a Glue Studio Custom Transform with Cloudwatch logging set up. AWS Glue Developer Endpoints may help with experimentation and debugging. These allow you to run a development notebook on a Spark cluster and speed up your development iterations when writing code. The main downside is that they are expensive (and can take 5–15 minutes to spin-up the cluster). Note that they charge by the second, so can be significantly more expensive than just executing your jobs directly. One option is to use Developer Endpoints while you are learning Spark, then move over to directly executing jobs in AWS Glue after you are familiar with writing Spark code. While you can run your ML training and predictions in the same job as your featurization ETL, you may want to separate them into two jobs. By separating them into two jobs, you can separate their configurations. AWS Glue provides two worker types: G.1X and G.2X. You may find that G.1X is adequate for ETL, but G.2X may be more suitable for ML training and inference as each worker has twice as much memory available. Only batch inference works on AWS Glue β€” real-time inference isn’t an option here. Use Sagemaker endpoints for that use case. MLlib on AWS Glue easily allows you to retrain your whole dataset, then perform inference in a single job. Training is probably the most expensive step, however, you can benefit from better predictions by retraining before batch inference Try to use native Spark dataframes and libraries, rather than, for example, Pandas dataframes. This will allow you to leverage the distributed capabilities of Spark much better. There are two APIs available in MLlib β€” the dataframe-based API and the RDD-based API. You should use the dataframe based approaches as much as possible. Likewise, try to avoid using user-defined functions (UDFs). Both UDFs and RDD-based capabilities are slower than native dataframe methods. SparseVector is an efficient way of representing sparse datasets (i.e. data sources with a large number of columns and most values being zero). A common example of this is the output of TF-IDF when performing natural language processing. Using a SparseVector column avoids adding hundreds or thousands of columns to a dataframe (which would most likely cause your job to fail due to out-of-memory or timeout). Some dataframe column types created by MLlib cannot be written out of a Custom Transform without being cast to integer or string first. You may get an error such as β€˜An error occurred while calling o341.toDF. org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 (of class org.apache.spark.ml.linalg.VectorUDT)’ when this happens. In AWS Glue reading to and from S3 is much easier than any other data source / destination. Directly connecting to a database may be more trouble than it’s worth. You will most likely need to make use of Glue Crawlers to learn your schema on S3. You will need to re-run the crawler each time your data changes. Use partition keys in your S3 path/key and partition predicates on your AWS Glue β€˜S3 data source’ input node to filter the data to a specific date. JSON and CSV can be useful data types when developing as you can see the inputs and outputs. However, they are slow and large. For production, consider switching to Parquet format inputs and outputs. Exporting a SparseVector column (that has been cast to String) to CSV leads to an invalid CSV structure. Parquet format works instead. Be careful to distinguish between the new dataframe-based API and the older RDD-based API. Ensure you import the correct classes. In PySpark, you should import β€˜pyspark.ml.linalg’ rather than β€˜pyspark.mllib.linalg’ to access the newer API. If you mix-up types, you may get strange errors such as β€œIllegalArgumentException: β€˜requirement failed: Column features must be of type struct<type:tinyint,size:int,indices:array<int>,values:array<double>> but was actually struct<type:tinyint,size:int,indices:array<int>,values:array<double>>.’. Both of those values look the same but the difference is that they’re using an incompatible version of the object from the wrong API. Yes, Spark ETL via AWS Glue can be integrated with Amazon Sagemaker. A typical workflow might be: Experiment and train the model in Sagemaker using Jupyter NotebooksProductionize the model by deploying a batch inference model from Sagemaker notebooksProductionize pre-processing and featurization using ETL in AWS GlueSchedule / trigger a batch inference model to run after completion of the AWS Glue ETL Experiment and train the model in Sagemaker using Jupyter Notebooks Productionize the model by deploying a batch inference model from Sagemaker notebooks Productionize pre-processing and featurization using ETL in AWS Glue Schedule / trigger a batch inference model to run after completion of the AWS Glue ETL The above approach may seem to be optimal use of AWS services for their intended purposes. However, you do need to look out for some things before going down this path. Some column types, for example, are not compatible between Spark MLlib and Sagemaker models. For instance, Sagemaker XGBoost requires its inputs to be in a specific format and cannot read SparseVector columns from Spark. Below is an example of a PySpark Custom Transform on AWS Glue Studio for logging out to the β€˜-driver’ log stream under the /aws-glue/jobs/logs-v2 log stream. def MyTransform (glueContext, dfc) -> DynamicFrameCollection: logger = glueContext.get_logger() df = dfc.select(list(dfc.keys())[0]).toDF() logger.info("Number of df rows:" + str(df.count())) dyf = DynamicFrame.fromDF(df, glueContext, "df") return DynamicFrameCollection({"CustomTransform": dyf}, glueContext) Without casting some MLlib column types to a String or integer first, you will get an error when trying to return the dataframe from the Custom Transform. VectorUDT is a β€˜user-defined type’ of column that is often produced by MLlib transforms. Below is an example of casting the column to String before returning it. # Cast VectorUDT column to StringrescaledData=rescaledData.withColumn("features",rescaledData["features"].cast("String"))# Reduce the number of columns being returnedrescaledData = rescaledData.selectExpr("labels", "features")# Convert from Spark dataframe to AWS Glue DynamicFramedyf_out = DynamicFrame.fromDF(rescaledData, glueContext, "rescaledData") # Wrap the DynamicFrame in a DynamicFrameCollection and returnreturn DynamicFrameCollection({"CustomTransform": dyf_out}, glueContext)
[ { "code": null, "e": 264, "s": 47, "text": "AWS pushes Sagemaker as its machine learning platform. However, Spark’s MLlib is a comprehensive library that runs distributed ML natively on AWS Glue β€” and provides a viable alternative to their primary ML platform." }, { "code": null, "e": 763, "s": 264, "text": "One of the big benefits of Sagemaker is that it easily supports experimentation via its Jupyter Notebooks. But operationalising your Sagemaker ML can be difficult, particularly if you need to include ETL processing at the start of your pipeline. In this situation, Apache Spark’s MLlib running on AWS Glue can be a good option β€” by its very nature, it is immediately operationalised, integrated with ETL pre-processing and ready to be used in production for an end-to-end machine learning pipeline." }, { "code": null, "e": 940, "s": 763, "text": "By its very nature, [AWS Glue] is immediately operationalised, integrated with ETL pre-processing and ready to be used in production for an end-to-end machine learning pipeline" }, { "code": null, "e": 1184, "s": 940, "text": "AWS Glue is a managed Spark ETL platform for processing large volumes of data via distributed machines. MLlib comes as part of Spark 2.4, which is the default version on AWS Glue. There is no need to add libraries to use MLlib within AWS Glue." }, { "code": null, "e": 1717, "s": 1184, "text": "As a distributed ETL platform, AWS Glue (via Spark) allows you to perform your data pre-processing at large scale easily. Glue Studio provides a nice UI for building directed acyclic graphs that represent the flow of data through each pre-processing step (see above image for an example). From the graph UI, you can rename fields, convert types, filter records and remove columns. However, some of the more complex data processing activities require a β€˜Custom Transform’ to be added. Actions that require a Custom Transform include:" }, { "code": null, "e": 1964, "s": 1717, "text": "Running MLlib functions, such as TF-IDF or models such as Random Forest or Gradient Boosted Tree algorithmsAggregating values, such as generating count, mean and sum valuesComplex column transforms such as one-hot encoding or concatenating values" }, { "code": null, "e": 2072, "s": 1964, "text": "Running MLlib functions, such as TF-IDF or models such as Random Forest or Gradient Boosted Tree algorithms" }, { "code": null, "e": 2138, "s": 2072, "text": "Aggregating values, such as generating count, mean and sum values" }, { "code": null, "e": 2213, "s": 2138, "text": "Complex column transforms such as one-hot encoding or concatenating values" }, { "code": null, "e": 2537, "s": 2213, "text": "After performing your pre-processing and featurization using ETL transforms, you need to train your data. To access MLlib in AWS Glue, you just need to add the import statements and you’re ready to go. Below is an example of how to train a regression Decision Tree model in a AWS Glue Studio Custom Transform using PySpark:" }, { "code": null, "e": 3465, "s": 2537, "text": "# Get the dataframe. Ensure there's a 'features' column.df = dfc.select(list(dfc.keys())[0]).toDF()# Get the logger for Cloudwatch Logslogger = glueContext.get_logger()from pyspark.ml import Pipelinefrom pyspark.ml.regression import DecisionTreeRegressorfrom pyspark.ml.evaluation import RegressionEvaluator# Split data into training and test sets(trainingData, testData) = df.randomSplit([0.7, 0.3])# Create a DecisionTree model.dt = DecisionTreeRegressor(featuresCol=\"features\")# Create a pipeline to wrap the DecisionTree pipeline = Pipeline(stages=[dt])# Train model.model = pipeline.fit(trainingData)# Make predictions.predictions = model.transform(testData)# Select (prediction, true label) and compute test errorevaluator = RegressionEvaluator( labelCol=\"label\", predictionCol=\"prediction\", metricName=\"rmse\")rmse = evaluator.evaluate(predictions)logger.info(\"Root Mean Squared Error (RMSE) on test data = %g\" % rmse)" }, { "code": null, "e": 3865, "s": 3465, "text": "In the above code, the root-mean-squared error (RMSE) is logged out to Cloudwatch Logs. To use the model to predict, the simplest option is to use the same Custom Transform and run model.transform on a dataframe of unseen inference data. To then use the predictions, you will need to return them from the Custom Transform in a DynamicFrameCollection (see code snippet at the bottom of this article)." }, { "code": null, "e": 3945, "s": 3865, "text": "There are a few gotchas to look out for when running Spark’s MLlib in AWS Glue:" }, { "code": null, "e": 8645, "s": 3945, "text": "Experimentation can be slow and difficult. Iterating and debugging can be frustrating because at a minimum each job takes one minute to run. When experimenting, run on a reduced data set to speed up the process (it will still take 1 minute+). Reduce the number of workers to 2 and use G.1X to save money. Disable bookmarks and retries.To help with debugging, you can log out information to Cloudwatch from your Custom Transform. You will have to go to the /aws-glue/jobs/logs-v2 log group on Cloudwatch, then open the log stream that ends with β€˜-driver’ to see the logged-out values. Below is a PySpark example of a Glue Studio Custom Transform with Cloudwatch logging set up.AWS Glue Developer Endpoints may help with experimentation and debugging. These allow you to run a development notebook on a Spark cluster and speed up your development iterations when writing code. The main downside is that they are expensive (and can take 5–15 minutes to spin-up the cluster). Note that they charge by the second, so can be significantly more expensive than just executing your jobs directly. One option is to use Developer Endpoints while you are learning Spark, then move over to directly executing jobs in AWS Glue after you are familiar with writing Spark code.While you can run your ML training and predictions in the same job as your featurization ETL, you may want to separate them into two jobs. By separating them into two jobs, you can separate their configurations. AWS Glue provides two worker types: G.1X and G.2X. You may find that G.1X is adequate for ETL, but G.2X may be more suitable for ML training and inference as each worker has twice as much memory available.Only batch inference works on AWS Glue β€” real-time inference isn’t an option here. Use Sagemaker endpoints for that use case.MLlib on AWS Glue easily allows you to retrain your whole dataset, then perform inference in a single job. Training is probably the most expensive step, however, you can benefit from better predictions by retraining before batch inferenceTry to use native Spark dataframes and libraries, rather than, for example, Pandas dataframes. This will allow you to leverage the distributed capabilities of Spark much better.There are two APIs available in MLlib β€” the dataframe-based API and the RDD-based API. You should use the dataframe based approaches as much as possible. Likewise, try to avoid using user-defined functions (UDFs). Both UDFs and RDD-based capabilities are slower than native dataframe methods.SparseVector is an efficient way of representing sparse datasets (i.e. data sources with a large number of columns and most values being zero). A common example of this is the output of TF-IDF when performing natural language processing. Using a SparseVector column avoids adding hundreds or thousands of columns to a dataframe (which would most likely cause your job to fail due to out-of-memory or timeout).Some dataframe column types created by MLlib cannot be written out of a Custom Transform without being cast to integer or string first. You may get an error such as β€˜An error occurred while calling o341.toDF. org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 (of class org.apache.spark.ml.linalg.VectorUDT)’ when this happens.In AWS Glue reading to and from S3 is much easier than any other data source / destination. Directly connecting to a database may be more trouble than it’s worth.You will most likely need to make use of Glue Crawlers to learn your schema on S3. You will need to re-run the crawler each time your data changes. Use partition keys in your S3 path/key and partition predicates on your AWS Glue β€˜S3 data source’ input node to filter the data to a specific date.JSON and CSV can be useful data types when developing as you can see the inputs and outputs. However, they are slow and large. For production, consider switching to Parquet format inputs and outputs.Exporting a SparseVector column (that has been cast to String) to CSV leads to an invalid CSV structure. Parquet format works instead.Be careful to distinguish between the new dataframe-based API and the older RDD-based API. Ensure you import the correct classes. In PySpark, you should import β€˜pyspark.ml.linalg’ rather than β€˜pyspark.mllib.linalg’ to access the newer API. If you mix-up types, you may get strange errors such as β€œIllegalArgumentException: β€˜requirement failed: Column features must be of type struct<type:tinyint,size:int,indices:array<int>,values:array<double>> but was actually struct<type:tinyint,size:int,indices:array<int>,values:array<double>>.’. Both of those values look the same but the difference is that they’re using an incompatible version of the object from the wrong API." }, { "code": null, "e": 8981, "s": 8645, "text": "Experimentation can be slow and difficult. Iterating and debugging can be frustrating because at a minimum each job takes one minute to run. When experimenting, run on a reduced data set to speed up the process (it will still take 1 minute+). Reduce the number of workers to 2 and use G.1X to save money. Disable bookmarks and retries." }, { "code": null, "e": 9323, "s": 8981, "text": "To help with debugging, you can log out information to Cloudwatch from your Custom Transform. You will have to go to the /aws-glue/jobs/logs-v2 log group on Cloudwatch, then open the log stream that ends with β€˜-driver’ to see the logged-out values. Below is a PySpark example of a Glue Studio Custom Transform with Cloudwatch logging set up." }, { "code": null, "e": 9908, "s": 9323, "text": "AWS Glue Developer Endpoints may help with experimentation and debugging. These allow you to run a development notebook on a Spark cluster and speed up your development iterations when writing code. The main downside is that they are expensive (and can take 5–15 minutes to spin-up the cluster). Note that they charge by the second, so can be significantly more expensive than just executing your jobs directly. One option is to use Developer Endpoints while you are learning Spark, then move over to directly executing jobs in AWS Glue after you are familiar with writing Spark code." }, { "code": null, "e": 10326, "s": 9908, "text": "While you can run your ML training and predictions in the same job as your featurization ETL, you may want to separate them into two jobs. By separating them into two jobs, you can separate their configurations. AWS Glue provides two worker types: G.1X and G.2X. You may find that G.1X is adequate for ETL, but G.2X may be more suitable for ML training and inference as each worker has twice as much memory available." }, { "code": null, "e": 10452, "s": 10326, "text": "Only batch inference works on AWS Glue β€” real-time inference isn’t an option here. Use Sagemaker endpoints for that use case." }, { "code": null, "e": 10691, "s": 10452, "text": "MLlib on AWS Glue easily allows you to retrain your whole dataset, then perform inference in a single job. Training is probably the most expensive step, however, you can benefit from better predictions by retraining before batch inference" }, { "code": null, "e": 10869, "s": 10691, "text": "Try to use native Spark dataframes and libraries, rather than, for example, Pandas dataframes. This will allow you to leverage the distributed capabilities of Spark much better." }, { "code": null, "e": 11162, "s": 10869, "text": "There are two APIs available in MLlib β€” the dataframe-based API and the RDD-based API. You should use the dataframe based approaches as much as possible. Likewise, try to avoid using user-defined functions (UDFs). Both UDFs and RDD-based capabilities are slower than native dataframe methods." }, { "code": null, "e": 11572, "s": 11162, "text": "SparseVector is an efficient way of representing sparse datasets (i.e. data sources with a large number of columns and most values being zero). A common example of this is the output of TF-IDF when performing natural language processing. Using a SparseVector column avoids adding hundreds or thousands of columns to a dataframe (which would most likely cause your job to fail due to out-of-memory or timeout)." }, { "code": null, "e": 11895, "s": 11572, "text": "Some dataframe column types created by MLlib cannot be written out of a Custom Transform without being cast to integer or string first. You may get an error such as β€˜An error occurred while calling o341.toDF. org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 (of class org.apache.spark.ml.linalg.VectorUDT)’ when this happens." }, { "code": null, "e": 12058, "s": 11895, "text": "In AWS Glue reading to and from S3 is much easier than any other data source / destination. Directly connecting to a database may be more trouble than it’s worth." }, { "code": null, "e": 12354, "s": 12058, "text": "You will most likely need to make use of Glue Crawlers to learn your schema on S3. You will need to re-run the crawler each time your data changes. Use partition keys in your S3 path/key and partition predicates on your AWS Glue β€˜S3 data source’ input node to filter the data to a specific date." }, { "code": null, "e": 12554, "s": 12354, "text": "JSON and CSV can be useful data types when developing as you can see the inputs and outputs. However, they are slow and large. For production, consider switching to Parquet format inputs and outputs." }, { "code": null, "e": 12689, "s": 12554, "text": "Exporting a SparseVector column (that has been cast to String) to CSV leads to an invalid CSV structure. Parquet format works instead." }, { "code": null, "e": 13359, "s": 12689, "text": "Be careful to distinguish between the new dataframe-based API and the older RDD-based API. Ensure you import the correct classes. In PySpark, you should import β€˜pyspark.ml.linalg’ rather than β€˜pyspark.mllib.linalg’ to access the newer API. If you mix-up types, you may get strange errors such as β€œIllegalArgumentException: β€˜requirement failed: Column features must be of type struct<type:tinyint,size:int,indices:array<int>,values:array<double>> but was actually struct<type:tinyint,size:int,indices:array<int>,values:array<double>>.’. Both of those values look the same but the difference is that they’re using an incompatible version of the object from the wrong API." }, { "code": null, "e": 13457, "s": 13359, "text": "Yes, Spark ETL via AWS Glue can be integrated with Amazon Sagemaker. A typical workflow might be:" }, { "code": null, "e": 13764, "s": 13457, "text": "Experiment and train the model in Sagemaker using Jupyter NotebooksProductionize the model by deploying a batch inference model from Sagemaker notebooksProductionize pre-processing and featurization using ETL in AWS GlueSchedule / trigger a batch inference model to run after completion of the AWS Glue ETL" }, { "code": null, "e": 13832, "s": 13764, "text": "Experiment and train the model in Sagemaker using Jupyter Notebooks" }, { "code": null, "e": 13918, "s": 13832, "text": "Productionize the model by deploying a batch inference model from Sagemaker notebooks" }, { "code": null, "e": 13987, "s": 13918, "text": "Productionize pre-processing and featurization using ETL in AWS Glue" }, { "code": null, "e": 14074, "s": 13987, "text": "Schedule / trigger a batch inference model to run after completion of the AWS Glue ETL" }, { "code": null, "e": 14464, "s": 14074, "text": "The above approach may seem to be optimal use of AWS services for their intended purposes. However, you do need to look out for some things before going down this path. Some column types, for example, are not compatible between Spark MLlib and Sagemaker models. For instance, Sagemaker XGBoost requires its inputs to be in a specific format and cannot read SparseVector columns from Spark." }, { "code": null, "e": 14622, "s": 14464, "text": "Below is an example of a PySpark Custom Transform on AWS Glue Studio for logging out to the β€˜-driver’ log stream under the /aws-glue/jobs/logs-v2 log stream." }, { "code": null, "e": 14954, "s": 14622, "text": "def MyTransform (glueContext, dfc) -> DynamicFrameCollection: logger = glueContext.get_logger() df = dfc.select(list(dfc.keys())[0]).toDF() logger.info(\"Number of df rows:\" + str(df.count())) dyf = DynamicFrame.fromDF(df, glueContext, \"df\") return DynamicFrameCollection({\"CustomTransform\": dyf}, glueContext)" }, { "code": null, "e": 15271, "s": 14954, "text": "Without casting some MLlib column types to a String or integer first, you will get an error when trying to return the dataframe from the Custom Transform. VectorUDT is a β€˜user-defined type’ of column that is often produced by MLlib transforms. Below is an example of casting the column to String before returning it." } ]
How can I aggregate nested documents in MongoDB?
To aggregate nested documents in MongoDB, you can use $group. Let us first create a collection with documents βˆ’ > db.aggregateDemo.insertOne( ... { ... "ProductInformation": [ ... { ... "Product1": [ ... { ... Amount: 50 ... }, ... { ... Amount: 90 ... }, ... { ... Amount: 30 ... } ... ] ... }, ... { ... "Product1": [ ... { ... Amount: 200 ... }, ... { ... Amount: 30 ... }, ... { ... Amount: 40 ... } ... ] ... }, ... { ... "Product1": [ ... { ... Amount: 150 ... }, ... { ... Amount: 190 ... }, ... { ... Amount: 198 ... } ... ] ... } ... ... ] ... }); { "acknowledged" : true, "insertedId" : ObjectId("5e04df58150ee0e76c06a04d") } > db.aggregateDemo.insertOne( ... { ... "ProductInformation": [ ... { ... "Product1": [ ... { ... Amount: 100 ... }, ... { ... Amount: 1002 ... }, ... { ... Amount: 78 ... } ... ] ... }, ... { ... "Product1": [ ... { ... Amount: 75 ... }, ... { ... Amount: 400 ... }, ... { ... Amount: 600 ... } ... ] ... }, ... { ... "Product1": [ ... { ... Amount: 700 ... }, ... { ... Amount: 500 ... }, ... { ... Amount: 600 ... } ... ] ... } ... ... ] ... }); { "acknowledged" : true, "insertedId" : ObjectId("5e04df93150ee0e76c06a04e") } Following is the query to display all documents from a collection with the help of find() method βˆ’ > db.aggregateDemo.find().pretty(); This will produce the following output βˆ’ { "_id" : ObjectId("5e04df58150ee0e76c06a04d"), "ProductInformation" : [ { "Product1" : [ { "Amount" : 50 }, { "Amount" : 90 }, { "Amount" : 30 } ] }, { "Product1" : [ { "Amount" : 200 }, { "Amount" : 30 }, { "Amount" : 40 } ] }, { "Product1" : [ { "Amount" : 150 }, { "Amount" : 190 }, { "Amount" : 198 } ] } ] } { "_id" : ObjectId("5e04df93150ee0e76c06a04e"), "ProductInformation" : [ { "Product1" : [ { "Amount" : 100 }, { "Amount" : 1002 }, { "Amount" : 78 } ] }, { "Product1" : [ { "Amount" : 75 }, { "Amount" : 400 }, { "Amount" : 600 } ] }, { "Product1" : [ { "Amount" : 700 }, { "Amount" : 500 }, { "Amount" : 600 } ] } ] } Here is the query to aggregate nested documents βˆ’ > db.aggregateDemo.aggregate([ ... { ... $unwind:"$ProductInformation" ... }, ... { ... $unwind:"$ProductInformation.Product1" ... }, ... { ... $group:{ ... _id:null, ... MaximumAmount:{ ... $max:"$ProductInformation.Product1.Amount" ... } ... } ... } ... ]); This will produce the following output βˆ’ { "_id" : null, "MaximumAmount" : 1002 }
[ { "code": null, "e": 1174, "s": 1062, "text": "To aggregate nested documents in MongoDB, you can use $group. Let us first create a collection with documents βˆ’" }, { "code": null, "e": 3384, "s": 1174, "text": "> db.aggregateDemo.insertOne(\n... {\n... \"ProductInformation\": [\n... {\n... \"Product1\": [\n... {\n... Amount: 50\n... },\n... {\n... Amount: 90\n... },\n... {\n... Amount: 30\n... }\n... ]\n... },\n... {\n... \"Product1\": [\n... {\n... Amount: 200\n... },\n... {\n... Amount: 30\n... },\n... {\n... Amount: 40\n... }\n... ]\n... },\n... {\n... \"Product1\": [\n... {\n... Amount: 150\n... },\n... {\n... Amount: 190\n... },\n... {\n... Amount: 198\n... }\n... ]\n... }\n...\n... ]\n... });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04df58150ee0e76c06a04d\")\n}\n> db.aggregateDemo.insertOne(\n... {\n... \"ProductInformation\": [\n... {\n... \"Product1\": [\n... {\n... Amount: 100\n... },\n... {\n... Amount: 1002\n... },\n... {\n... Amount: 78\n... }\n... ]\n... },\n... {\n... \"Product1\": [\n... {\n... Amount: 75\n... },\n... {\n... Amount: 400\n... },\n... {\n... Amount: 600\n... }\n... ]\n... },\n... {\n... \"Product1\": [\n... {\n... Amount: 700\n... },\n... {\n... Amount: 500\n... },\n... {\n... Amount: 600\n... }\n... ]\n... }\n...\n... ]\n... });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04df93150ee0e76c06a04e\")\n}" }, { "code": null, "e": 3483, "s": 3384, "text": "Following is the query to display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 3519, "s": 3483, "text": "> db.aggregateDemo.find().pretty();" }, { "code": null, "e": 3560, "s": 3519, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 4864, "s": 3560, "text": "{\n \"_id\" : ObjectId(\"5e04df58150ee0e76c06a04d\"),\n \"ProductInformation\" : [\n {\n \"Product1\" : [\n {\n \"Amount\" : 50\n },\n {\n \"Amount\" : 90\n },\n {\n \"Amount\" : 30\n }\n ]\n },\n {\n \"Product1\" : [\n {\n \"Amount\" : 200\n },\n {\n \"Amount\" : 30\n },\n {\n \"Amount\" : 40\n }\n ]\n},\n{\n \"Product1\" : [\n {\n \"Amount\" : 150\n },\n {\n \"Amount\" : 190\n },\n {\n \"Amount\" : 198\n }\n ]\n}\n]\n}\n{\n \"_id\" : ObjectId(\"5e04df93150ee0e76c06a04e\"),\n \"ProductInformation\" : [\n {\n \"Product1\" : [\n {\n \"Amount\" : 100\n },\n {\n \"Amount\" : 1002\n },\n {\n \"Amount\" : 78\n }\n ]\n },\n {\n \"Product1\" : [\n {\n \"Amount\" : 75\n },\n {\n \"Amount\" : 400\n },\n {\n \"Amount\" : 600\n }\n ]\n },\n {\n \"Product1\" : [\n {\n \"Amount\" : 700\n },\n {\n \"Amount\" : 500\n },\n {\n \"Amount\" : 600\n }\n ]\n }\n]\n}" }, { "code": null, "e": 4914, "s": 4864, "text": "Here is the query to aggregate nested documents βˆ’" }, { "code": null, "e": 5213, "s": 4914, "text": "> db.aggregateDemo.aggregate([\n... {\n... $unwind:\"$ProductInformation\"\n... },\n... {\n... $unwind:\"$ProductInformation.Product1\"\n... },\n... {\n... $group:{\n... _id:null,\n... MaximumAmount:{\n... $max:\"$ProductInformation.Product1.Amount\"\n... }\n... }\n... }\n... ]);" }, { "code": null, "e": 5254, "s": 5213, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 5295, "s": 5254, "text": "{ \"_id\" : null, \"MaximumAmount\" : 1002 }" } ]
JavaScript Number - MAX_VALUE
The Number.MAX_VALUE property belongs to the static Number object. It represents constants for the largest possible positive numbers that JavaScript can work with. The actual value of this constant is 1.7976931348623157 x 10308 The syntax to use MAX_VALUE is βˆ’ var val = Number.MAX_VALUE; Try the following example to learn how to use MAX_VALUE. <html> <head> <script type = "text/javascript"> <!-- function showValue() { var val = Number.MAX_VALUE; document.write ("Value of Number.MAX_VALUE : " + val ); } //--> </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "showValue();" /> </form> </body> </html> Click the following to see the result: 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2630, "s": 2466, "text": "The Number.MAX_VALUE property belongs to the static Number object. It represents constants for the largest possible positive numbers that JavaScript can work with." }, { "code": null, "e": 2694, "s": 2630, "text": "The actual value of this constant is 1.7976931348623157 x 10308" }, { "code": null, "e": 2727, "s": 2694, "text": "The syntax to use MAX_VALUE is βˆ’" }, { "code": null, "e": 2756, "s": 2727, "text": "var val = Number.MAX_VALUE;\n" }, { "code": null, "e": 2813, "s": 2756, "text": "Try the following example to learn how to use MAX_VALUE." }, { "code": null, "e": 3303, "s": 2813, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function showValue() {\n var val = Number.MAX_VALUE;\n document.write (\"Value of Number.MAX_VALUE : \" + val );\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following to see the result:</p> \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"showValue();\" />\n </form> \n </body>\n</html>" }, { "code": null, "e": 3342, "s": 3303, "text": "Click the following to see the result:" }, { "code": null, "e": 3377, "s": 3342, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3391, "s": 3377, "text": " Anadi Sharma" }, { "code": null, "e": 3425, "s": 3391, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3439, "s": 3425, "text": " Lets Kode It" }, { "code": null, "e": 3474, "s": 3439, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3491, "s": 3474, "text": " Frahaan Hussain" }, { "code": null, "e": 3526, "s": 3491, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3543, "s": 3526, "text": " Frahaan Hussain" }, { "code": null, "e": 3576, "s": 3543, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3604, "s": 3576, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3638, "s": 3604, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3666, "s": 3638, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3673, "s": 3666, "text": " Print" }, { "code": null, "e": 3684, "s": 3673, "text": " Add Notes" } ]
How to put a Tkinter window on top of the others?
Whenever we create a GUI program, tkinter generally presents the output screen in the background. In other words, tkinter displays the program window behind other programs. In order to put the tkinter window on top of others, we are required to use attributes('- topmost',True) property. It pulls up the window on the upside. #Importing the library from tkinter import * #Create an instance of tkinter window or frame win= Tk() #Setting the geometry of window win.geometry("600x350") #Create a Label Label(win, text= "Hello World! ",font=('Helvetica bold', 15)).pack(pady=20) #Make the window jump above all win.attributes('-topmost',True) win.mainloop() Running the above code will make the window stay on top all other windows βˆ’
[ { "code": null, "e": 1388, "s": 1062, "text": "Whenever we create a GUI program, tkinter generally presents the output screen in the background. In other words, tkinter displays the program window behind other programs. In order to put the tkinter window on top of others, we are required to use attributes('- topmost',True) property. It pulls up the window on the upside." }, { "code": null, "e": 1722, "s": 1388, "text": "#Importing the library\nfrom tkinter import *\n\n#Create an instance of tkinter window or frame\nwin= Tk()\n\n#Setting the geometry of window\nwin.geometry(\"600x350\")\n\n#Create a Label\nLabel(win, text= \"Hello World! \",font=('Helvetica bold', 15)).pack(pady=20)\n\n#Make the window jump above all\nwin.attributes('-topmost',True)\n\nwin.mainloop()" }, { "code": null, "e": 1798, "s": 1722, "text": "Running the above code will make the window stay on top all other windows βˆ’" } ]
Spam Email Classifier with KNN β€” From Scratch (Python) | by Abdelrahman Ragab | Towards Data Science
KNN (K-Nearest Neighbours) is one of the very straightforward supervised learning algorithms. However, unlike the traditional supervised learning algorithms, such as Multinomial Naive Bayes algorithm, KNN doesn’t have an independent training stage, and then a stage where the labels for the test data are predicted based on the trained model. Rather, the features of every test data item are compared with the features of every training data item in real time, and then the K nearest training data items are selected, and the most frequent class among them is given to the test data item. In the context of email classification (spam or ham), the features to be compared are the frequencies of words in each email. The euclidean distance is used to determine the similarity between two emails; the smaller the distance, the more similar. The Euclidean Distance formula used in the algorithm is as follows : Once the Euclidean Distance between a test email and each training email is calculated, the distances are sorted in ascending order (nearest to farthest), and the K-nearest neighbouring emails are selected. If the majority is spam, then the test email is labelled as spam, else, it is labelled as ham. In the example shown above, K = 5; we are comparing the email we want to classify to the nearest 5 neighbours. In this case, 3 out of 5 emails are classified as ham (non-spam), and 2 are classified as spam. Therefore, the unknown email will be given the class of the majority: ham. Now that we have seen how KNN works, let’s move on to implementing the classifier using code! To have a quick idea of what we’ll be coding in Python, it’s always a good practice to write pseudo code: 1. Load the spam and ham emails2. Remove common punctuation and symbols3. Lowercase all letters4. Remove stopwords (very common words like pronouns, articles, etc.)5. Split emails into training email and testing emails6. For each test email, calculate the similarity between it and all training emails 6.1. For each word that exists in either test email or training email, count its frequency in both emails 6.2. calculate the euclidean distance between both emails to determine similarity7. Sort the emails in ascending order of euclidean distance8. Select the k nearest neighbors (shortest distance)9. Assign the class which is most frequent in the selected k nearest neighbours to the new email The email data set for spam and ham (normal email) is obtained from β€œThe Enron-Spam datasets”. It can be found at http://nlp.cs.aueb.gr/software_and_datasets/Enron-Spam/index.html under Enron2. The data set we’re using contains 5857 emails. Every email is stored in a text file, and the text files are divided and stored into two folders, ham folder, and spam folder. This means that the emails are already labelled. Every text file will be loaded by the program, and each email will be read and stored as a string variable. Every distinct word inside the string will be counted as a feature. import osimport stringfrom nltk.corpus import stopwordsfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scoreimport numpy as np os library to open and read files.string library for list of punctuationstopwords contains the list of stopwords.train_test_split to split the data into training and test data.accuracy_score to calculate accuracy of algorithms.numpy to allow advanced array manipulation. def load_data(): print("Loading data...") ham_files_location = os.listdir("dataset/ham") spam_files_location = os.listdir("dataset/spam") data = [] os.listdir() returns a list of all filenames inside a folder. This is used to retrieve all filenames of the text files in each of the ham and spam folder and store them in ham_files_location and spam_files_location respectively. data is a list to store each email text and its corresponding label. # Load ham email for file_path in ham_files_location: f = open("dataset/ham/" + file_path, "r") text = str(f.read()) data.append([text, "ham"]) # Load spam email for file_path in spam_files_location: f = open("dataset/spam/" + file_path, "r") text = str(f.read()) data.append([text, "spam"]) We iterate over the list of ham text filenames, use open() to open a file, then use str(f.read()) to read the email text as a string and store it in variable text. A list made of text and the corresponding label β€œham” are appended to the list data. data = np.array(data) print("flag 1: loaded data") return data The list data is transformed into a numpy array, to allow better manipulation of the array later. data is then returned. # Preprocessing data: noise removaldef preprocess_data(data): print("Preprocessing data...") punc = string.punctuation # Punctuation list sw = stopwords.words('english') # Stopwords list punc holds a list of punctuation and symbolssw holds a list of stopwords from nltk.corpus library for record in data: # Remove common punctuation and symbols for item in punc: record[0] = record[0].replace(item, "") For every record in data, for every item (symbol or punctuation) in punc, replace the item with an empty string, to delete the item from record[0] (email text string). # Lowercase all letters and remove stopwords splittedWords = record[0].split() newText = "" for word in splittedWords: if word not in sw: word = word.lower() newText = newText + " " + word record[0] = newText print("flag 2: preprocessed data") return data Use split() method on email text record[0] to return a list of all words in the email. Iterate over that list of words, and if the word is not in stopwords list, set it to lowercase, and add the word to newText. newText will contain the email but empty of stopwords. newText is assigned back to record[0]. After every record[0] is preprocessed, the clean data is returned. The data set is split into a training set (73%) and a testing set (27%). # Splitting original dataset into training dataset and test datasetdef split_data(data): print("Splitting data...") features = data[:, 0] # array containing all email text bodies labels = data[:, 1] # array containing corresponding labels print(labels) training_data, test_data, training_labels, test_labels =\ train_test_split(features, labels, test_size = 0.27, random_state = 42) print("flag 3: splitted data") return training_data, test_data, training_labels, test_labels First, it was necessary to have the email texts in an array of their own, and labels in another array of their own. So, the email texts were stored in features and the labels were stored in labels. train_test_split method was then used to split the data into training_data, test_data, training_labels, and test_labels. The random state was set to 42 to ensure the same output of random shuffling will be obtained for testing purposes. After splitting, training_data, test_data, training_labels, and test_labels are returned. get_count() function def get_count(text): wordCounts = dict() for word in text.split(): if word in wordCounts: wordCounts[word] += 1 else: wordCounts[word] = 1 return wordCounts This function takes a single email text, and splits it using split(). The frequency of occurrence of each word in the email is counted and saved in wordCounts, which is of dictionary data type. The dictionary wordCounts is then returned. euclidean_difference() function def euclidean_difference(test_WordCounts, training_WordCounts): total = 0 This function takes in a dictionary of word counts of a test email test_WordCounts, and another dictionary of a training email, training_wordCounts. total stores the sum of the squared difference of the frequency of a word in the test and training email. for word in test_WordCounts: if word in test_WordCounts and word in training_WordCounts: total += (test_WordCounts[word] - training_WordCounts[word])**2 First, we iterate over the words in the test email dictionary. For each word, there are three cases. First case is that it exists in both, test email and training email. In that case, total is incremented with the squared difference of the word’s frequency in the test email and training email. del training_WordCounts[word] Then the common word is removed from the training email dictionary, to speed up the next for-loop else: total += test_WordCounts[word]**2 Second case is that the word is in test email only. In that case there is no need to find the difference (since its frequency is 0 in training email), so we just add the word’s squared frequency to total. for word in training_WordCounts: total += training_WordCounts[word]**2 The last case is that the word is only in the training email. Since we deleted all common words in the previous for loop, we just loop through the training email dictionary and add every word’s squared frequency to total. return total**0.5 Finally, the square root of total (the square root of the sum of the squared difference of frequencies of each word) is returned as a double. This is the end of the Euclidean Distance calculation function. get_class() function def get_class(selected_Kvalues): spam_count = 0 ham_count = 0 This function takes in the list of the selected K nearest neighbours to determine the class of the current test email. spam_count and ham_count store the frequency of occurrence of each β€œspam” label and β€œham” label respectively within the K selected nearest neighbours. for value in selected_Kvalues: if value[0] == "spam": spam_count += 1 else: ham_count += 1 Using a for loop, for each value in the K selected values, if the label value[0] is equal to β€œspam”, then spam_count is incremented by 1. Else, ham_count is incremented by 1. if spam_count > ham_count: return "spam" else: return "ham" After the for loop, if spam_count is greater than ham_count, it means that the current test email has a greater tendency to be spam, so a string β€œspam” is returned as the predicted label. Else, the string β€œham” is returned as the predicted label. knn_classifier() function def knn_classifier(training_data, training_labels, test_data, K, tsize): print("Running KNN Classifier...") result = [] counter = 1 This is the KNN classifier function. It takes in the training email, training labels, test data, the K value, and the number of test emails to be tested out of the original 27% test emails. result is the list which would contain the predicted labels. counter will be just used for display purposes to indicate progress when the program is run. # word counts for training email training_WordCounts = [] for training_text in training_data: training_WordCounts.append(get_count(training_text)) Since the training set is constant, we can count the word frequency in each training email once and for all. So, for each email text in training data, its word frequency dictionary is obtained using get_count(). The dictionary is then appended to the training_WordCounts list to be stored. for test_text in test_data: similarity = [] # List of euclidean distances test_WordCounts = get_count(test_text) # word counts for test email Now, for every test email in the test data, the following is done. An empty list similarity is declared. It will store the Euclidean distances between the current test email and each training email. Then, the test email’s word frequency dictionary is obtained using get_count(). # Getting euclidean difference for index in range(len(training_data)): euclidean_diff =\ euclidean_difference(test_WordCounts, training_WordCounts[index]) similarity.append([training_labels[index], euclidean_diff]) Since we already have the word frequency dictionaries of all training emails, and the current test email. We can go ahead calculate the Euclidean distance between the current test email, and each training email using a for-loop which iterates x times, where x is equal to the size of the training data set. After every iteration, the Euclidean distance calculated is appended to the similarity list, along with the corresponding label of the training email. # Sort list in ascending order based on euclidean difference similarity = sorted(similarity, key = lambda i:i[1]) After all Euclidean distances have been stored. We sort the similarity list in ascending order based on the second column, i.e. based on the Euclidean distance (nearest to farthest). # Select K nearest neighbours selected_Kvalues = [] for i in range(K): selected_Kvalues.append(similarity[i]) Now, since the similarity list is already sorted, we can easily append the nearest K neighbours to the selected_Kvalues list using a simple for loop. # Predicting the class of email result.append(get_class(selected_Kvalues)) Lastly, and before moving on to the next test email. We determine the class of the current test email using get_class(). Now, we have reached the end of one iteration, and the next iteration can begin to classify the next test email. return result Once all test emails have been classified, and the for-loop has reached its end, the result list, which contains the list of predicted labels, is returned. main() function def main(K): data = load_data() data = preprocess_data(data) training_data, test_data, training_labels, test_labels = split_data(data) This is the main function where the program begins to run. This is where everything is put together. The main function takes in the K value. First, all emails are loaded using load_data() and then stored in data. The emails are then preprocessed using preprocess_data() and stored again in data. data is then split into training_data, test_data, training_labels, and test_labels using split_data(). tsize = len(test_data) tsize specifies the number of test emails (out of the original 27% test data) to predict their labels. Currently tsize is set to be equal to the entire set of test emails. result = knn_classifier(training_data, training_labels, test_data[:tsize], K, tsize) accuracy = accuracy_score(test_labels[:tsize], result) Now, the knn_classifier() function is called to predict the labels for the test emails. The returned list of predicted labels is stored in result. After that, accuracy is calculated using the accuracy_score() method from sklearn library. This method compares the actual labels list test_labels with the predicted labels list result. print("training data size\t: " + str(len(training_data))) print("test data size\t\t: " + str(len(test_data))) print("K value\t\t\t\t: " + str(K)) print("Samples tested\t\t: " + str(tsize)) print("% accuracy\t\t\t: " + str(accuracy * 100)) print("Number correct\t\t: " + str(int(accuracy * tsize))) print("Number wrong\t\t: " + str(int((1 - accuracy) * tsize))) These lines display the details of the run such as the training data size, test data size, K value, number of samples tested, percentage accuracy, number of emails correctly identified, and number of emails falsely identified. main(11) Finally, this is the line which initiates the program by calling the main function, and gives it the K value (which is 11 in this case). This is the final output of all the code that has been explained above. It can be seen that using KNN algorithm to classify email into spam and ham, with a K value of 11, and test data size 1582, it gives a 76.7% accuracy rate. Though not the best, it is satisfactory. One downside to note is that it takes a long time to classify the 1582 emails. This is primarily due to the high time complexity, which is the result of three nested for-loops when calculating the euclidean difference between test emails and training emails. You can find the full source-code on my Github repository here.
[ { "code": null, "e": 760, "s": 171, "text": "KNN (K-Nearest Neighbours) is one of the very straightforward supervised learning algorithms. However, unlike the traditional supervised learning algorithms, such as Multinomial Naive Bayes algorithm, KNN doesn’t have an independent training stage, and then a stage where the labels for the test data are predicted based on the trained model. Rather, the features of every test data item are compared with the features of every training data item in real time, and then the K nearest training data items are selected, and the most frequent class among them is given to the test data item." }, { "code": null, "e": 1078, "s": 760, "text": "In the context of email classification (spam or ham), the features to be compared are the frequencies of words in each email. The euclidean distance is used to determine the similarity between two emails; the smaller the distance, the more similar. The Euclidean Distance formula used in the algorithm is as follows :" }, { "code": null, "e": 1380, "s": 1078, "text": "Once the Euclidean Distance between a test email and each training email is calculated, the distances are sorted in ascending order (nearest to farthest), and the K-nearest neighbouring emails are selected. If the majority is spam, then the test email is labelled as spam, else, it is labelled as ham." }, { "code": null, "e": 1756, "s": 1380, "text": "In the example shown above, K = 5; we are comparing the email we want to classify to the nearest 5 neighbours. In this case, 3 out of 5 emails are classified as ham (non-spam), and 2 are classified as spam. Therefore, the unknown email will be given the class of the majority: ham. Now that we have seen how KNN works, let’s move on to implementing the classifier using code!" }, { "code": null, "e": 1862, "s": 1756, "text": "To have a quick idea of what we’ll be coding in Python, it’s always a good practice to write pseudo code:" }, { "code": null, "e": 2566, "s": 1862, "text": "1. Load the spam and ham emails2. Remove common punctuation and symbols3. Lowercase all letters4. Remove stopwords (very common words like pronouns, articles, etc.)5. Split emails into training email and testing emails6. For each test email, calculate the similarity between it and all training emails 6.1. For each word that exists in either test email or training email, count its frequency in both emails 6.2. calculate the euclidean distance between both emails to determine similarity7. Sort the emails in ascending order of euclidean distance8. Select the k nearest neighbors (shortest distance)9. Assign the class which is most frequent in the selected k nearest neighbours to the new email" }, { "code": null, "e": 3159, "s": 2566, "text": "The email data set for spam and ham (normal email) is obtained from β€œThe Enron-Spam datasets”. It can be found at http://nlp.cs.aueb.gr/software_and_datasets/Enron-Spam/index.html under Enron2. The data set we’re using contains 5857 emails. Every email is stored in a text file, and the text files are divided and stored into two folders, ham folder, and spam folder. This means that the emails are already labelled. Every text file will be loaded by the program, and each email will be read and stored as a string variable. Every distinct word inside the string will be counted as a feature." }, { "code": null, "e": 3327, "s": 3159, "text": "import osimport stringfrom nltk.corpus import stopwordsfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scoreimport numpy as np" }, { "code": null, "e": 3598, "s": 3327, "text": "os library to open and read files.string library for list of punctuationstopwords contains the list of stopwords.train_test_split to split the data into training and test data.accuracy_score to calculate accuracy of algorithms.numpy to allow advanced array manipulation." }, { "code": null, "e": 3762, "s": 3598, "text": "def load_data(): print(\"Loading data...\") ham_files_location = os.listdir(\"dataset/ham\") spam_files_location = os.listdir(\"dataset/spam\") data = []" }, { "code": null, "e": 4060, "s": 3762, "text": "os.listdir() returns a list of all filenames inside a folder. This is used to retrieve all filenames of the text files in each of the ham and spam folder and store them in ham_files_location and spam_files_location respectively. data is a list to store each email text and its corresponding label." }, { "code": null, "e": 4411, "s": 4060, "text": " # Load ham email for file_path in ham_files_location: f = open(\"dataset/ham/\" + file_path, \"r\") text = str(f.read()) data.append([text, \"ham\"]) # Load spam email for file_path in spam_files_location: f = open(\"dataset/spam/\" + file_path, \"r\") text = str(f.read()) data.append([text, \"spam\"])" }, { "code": null, "e": 4660, "s": 4411, "text": "We iterate over the list of ham text filenames, use open() to open a file, then use str(f.read()) to read the email text as a string and store it in variable text. A list made of text and the corresponding label β€œham” are appended to the list data." }, { "code": null, "e": 4737, "s": 4660, "text": " data = np.array(data) print(\"flag 1: loaded data\") return data" }, { "code": null, "e": 4858, "s": 4737, "text": "The list data is transformed into a numpy array, to allow better manipulation of the array later. data is then returned." }, { "code": null, "e": 5072, "s": 4858, "text": "# Preprocessing data: noise removaldef preprocess_data(data): print(\"Preprocessing data...\") punc = string.punctuation # Punctuation list sw = stopwords.words('english') # Stopwords list" }, { "code": null, "e": 5170, "s": 5072, "text": "punc holds a list of punctuation and symbolssw holds a list of stopwords from nltk.corpus library" }, { "code": null, "e": 5317, "s": 5170, "text": " for record in data: # Remove common punctuation and symbols for item in punc: record[0] = record[0].replace(item, \"\")" }, { "code": null, "e": 5485, "s": 5317, "text": "For every record in data, for every item (symbol or punctuation) in punc, replace the item with an empty string, to delete the item from record[0] (email text string)." }, { "code": null, "e": 5843, "s": 5485, "text": " # Lowercase all letters and remove stopwords splittedWords = record[0].split() newText = \"\" for word in splittedWords: if word not in sw: word = word.lower() newText = newText + \" \" + word record[0] = newText print(\"flag 2: preprocessed data\") return data" }, { "code": null, "e": 6216, "s": 5843, "text": "Use split() method on email text record[0] to return a list of all words in the email. Iterate over that list of words, and if the word is not in stopwords list, set it to lowercase, and add the word to newText. newText will contain the email but empty of stopwords. newText is assigned back to record[0]. After every record[0] is preprocessed, the clean data is returned." }, { "code": null, "e": 6289, "s": 6216, "text": "The data set is split into a training set (73%) and a testing set (27%)." }, { "code": null, "e": 6807, "s": 6289, "text": "# Splitting original dataset into training dataset and test datasetdef split_data(data): print(\"Splitting data...\") features = data[:, 0] # array containing all email text bodies labels = data[:, 1] # array containing corresponding labels print(labels) training_data, test_data, training_labels, test_labels =\\ train_test_split(features, labels, test_size = 0.27, random_state = 42) print(\"flag 3: splitted data\") return training_data, test_data, training_labels, test_labels" }, { "code": null, "e": 7332, "s": 6807, "text": "First, it was necessary to have the email texts in an array of their own, and labels in another array of their own. So, the email texts were stored in features and the labels were stored in labels. train_test_split method was then used to split the data into training_data, test_data, training_labels, and test_labels. The random state was set to 42 to ensure the same output of random shuffling will be obtained for testing purposes. After splitting, training_data, test_data, training_labels, and test_labels are returned." }, { "code": null, "e": 7353, "s": 7332, "text": "get_count() function" }, { "code": null, "e": 7559, "s": 7353, "text": "def get_count(text): wordCounts = dict() for word in text.split(): if word in wordCounts: wordCounts[word] += 1 else: wordCounts[word] = 1 return wordCounts" }, { "code": null, "e": 7797, "s": 7559, "text": "This function takes a single email text, and splits it using split(). The frequency of occurrence of each word in the email is counted and saved in wordCounts, which is of dictionary data type. The dictionary wordCounts is then returned." }, { "code": null, "e": 7829, "s": 7797, "text": "euclidean_difference() function" }, { "code": null, "e": 7906, "s": 7829, "text": "def euclidean_difference(test_WordCounts, training_WordCounts): total = 0" }, { "code": null, "e": 8161, "s": 7906, "text": "This function takes in a dictionary of word counts of a test email test_WordCounts, and another dictionary of a training email, training_wordCounts. total stores the sum of the squared difference of the frequency of a word in the test and training email." }, { "code": null, "e": 8336, "s": 8161, "text": " for word in test_WordCounts: if word in test_WordCounts and word in training_WordCounts: total += (test_WordCounts[word] - training_WordCounts[word])**2" }, { "code": null, "e": 8631, "s": 8336, "text": "First, we iterate over the words in the test email dictionary. For each word, there are three cases. First case is that it exists in both, test email and training email. In that case, total is incremented with the squared difference of the word’s frequency in the test email and training email." }, { "code": null, "e": 8673, "s": 8631, "text": " del training_WordCounts[word]" }, { "code": null, "e": 8771, "s": 8673, "text": "Then the common word is removed from the training email dictionary, to speed up the next for-loop" }, { "code": null, "e": 8830, "s": 8771, "text": " else: total += test_WordCounts[word]**2" }, { "code": null, "e": 9035, "s": 8830, "text": "Second case is that the word is in test email only. In that case there is no need to find the difference (since its frequency is 0 in training email), so we just add the word’s squared frequency to total." }, { "code": null, "e": 9121, "s": 9035, "text": " for word in training_WordCounts: total += training_WordCounts[word]**2" }, { "code": null, "e": 9343, "s": 9121, "text": "The last case is that the word is only in the training email. Since we deleted all common words in the previous for loop, we just loop through the training email dictionary and add every word’s squared frequency to total." }, { "code": null, "e": 9365, "s": 9343, "text": " return total**0.5" }, { "code": null, "e": 9571, "s": 9365, "text": "Finally, the square root of total (the square root of the sum of the squared difference of frequencies of each word) is returned as a double. This is the end of the Euclidean Distance calculation function." }, { "code": null, "e": 9592, "s": 9571, "text": "get_class() function" }, { "code": null, "e": 9660, "s": 9592, "text": "def get_class(selected_Kvalues): spam_count = 0 ham_count = 0" }, { "code": null, "e": 9930, "s": 9660, "text": "This function takes in the list of the selected K nearest neighbours to determine the class of the current test email. spam_count and ham_count store the frequency of occurrence of each β€œspam” label and β€œham” label respectively within the K selected nearest neighbours." }, { "code": null, "e": 10061, "s": 9930, "text": " for value in selected_Kvalues: if value[0] == \"spam\": spam_count += 1 else: ham_count += 1" }, { "code": null, "e": 10236, "s": 10061, "text": "Using a for loop, for each value in the K selected values, if the label value[0] is equal to β€œspam”, then spam_count is incremented by 1. Else, ham_count is incremented by 1." }, { "code": null, "e": 10317, "s": 10236, "text": " if spam_count > ham_count: return \"spam\" else: return \"ham\"" }, { "code": null, "e": 10564, "s": 10317, "text": "After the for loop, if spam_count is greater than ham_count, it means that the current test email has a greater tendency to be spam, so a string β€œspam” is returned as the predicted label. Else, the string β€œham” is returned as the predicted label." }, { "code": null, "e": 10590, "s": 10564, "text": "knn_classifier() function" }, { "code": null, "e": 10735, "s": 10590, "text": "def knn_classifier(training_data, training_labels, test_data, K, tsize): print(\"Running KNN Classifier...\") result = [] counter = 1" }, { "code": null, "e": 11079, "s": 10735, "text": "This is the KNN classifier function. It takes in the training email, training labels, test data, the K value, and the number of test emails to be tested out of the original 27% test emails. result is the list which would contain the predicted labels. counter will be just used for display purposes to indicate progress when the program is run." }, { "code": null, "e": 11248, "s": 11079, "text": " # word counts for training email training_WordCounts = [] for training_text in training_data: training_WordCounts.append(get_count(training_text))" }, { "code": null, "e": 11538, "s": 11248, "text": "Since the training set is constant, we can count the word frequency in each training email once and for all. So, for each email text in training data, its word frequency dictionary is obtained using get_count(). The dictionary is then appended to the training_WordCounts list to be stored." }, { "code": null, "e": 11699, "s": 11538, "text": " for test_text in test_data: similarity = [] # List of euclidean distances test_WordCounts = get_count(test_text) # word counts for test email" }, { "code": null, "e": 11978, "s": 11699, "text": "Now, for every test email in the test data, the following is done. An empty list similarity is declared. It will store the Euclidean distances between the current test email and each training email. Then, the test email’s word frequency dictionary is obtained using get_count()." }, { "code": null, "e": 12246, "s": 11978, "text": " # Getting euclidean difference for index in range(len(training_data)): euclidean_diff =\\ euclidean_difference(test_WordCounts, training_WordCounts[index]) similarity.append([training_labels[index], euclidean_diff])" }, { "code": null, "e": 12704, "s": 12246, "text": "Since we already have the word frequency dictionaries of all training emails, and the current test email. We can go ahead calculate the Euclidean distance between the current test email, and each training email using a for-loop which iterates x times, where x is equal to the size of the training data set. After every iteration, the Euclidean distance calculated is appended to the similarity list, along with the corresponding label of the training email." }, { "code": null, "e": 12833, "s": 12704, "text": " # Sort list in ascending order based on euclidean difference similarity = sorted(similarity, key = lambda i:i[1])" }, { "code": null, "e": 13016, "s": 12833, "text": "After all Euclidean distances have been stored. We sort the similarity list in ascending order based on the second column, i.e. based on the Euclidean distance (nearest to farthest)." }, { "code": null, "e": 13160, "s": 13016, "text": " # Select K nearest neighbours selected_Kvalues = [] for i in range(K): selected_Kvalues.append(similarity[i])" }, { "code": null, "e": 13310, "s": 13160, "text": "Now, since the similarity list is already sorted, we can easily append the nearest K neighbours to the selected_Kvalues list using a simple for loop." }, { "code": null, "e": 13400, "s": 13310, "text": " # Predicting the class of email result.append(get_class(selected_Kvalues))" }, { "code": null, "e": 13634, "s": 13400, "text": "Lastly, and before moving on to the next test email. We determine the class of the current test email using get_class(). Now, we have reached the end of one iteration, and the next iteration can begin to classify the next test email." }, { "code": null, "e": 13652, "s": 13634, "text": " return result" }, { "code": null, "e": 13808, "s": 13652, "text": "Once all test emails have been classified, and the for-loop has reached its end, the result list, which contains the list of predicted labels, is returned." }, { "code": null, "e": 13824, "s": 13808, "text": "main() function" }, { "code": null, "e": 13968, "s": 13824, "text": "def main(K): data = load_data() data = preprocess_data(data) training_data, test_data, training_labels, test_labels = split_data(data)" }, { "code": null, "e": 14367, "s": 13968, "text": "This is the main function where the program begins to run. This is where everything is put together. The main function takes in the K value. First, all emails are loaded using load_data() and then stored in data. The emails are then preprocessed using preprocess_data() and stored again in data. data is then split into training_data, test_data, training_labels, and test_labels using split_data()." }, { "code": null, "e": 14394, "s": 14367, "text": " tsize = len(test_data)" }, { "code": null, "e": 14566, "s": 14394, "text": "tsize specifies the number of test emails (out of the original 27% test data) to predict their labels. Currently tsize is set to be equal to the entire set of test emails." }, { "code": null, "e": 14714, "s": 14566, "text": " result = knn_classifier(training_data, training_labels, test_data[:tsize], K, tsize) accuracy = accuracy_score(test_labels[:tsize], result)" }, { "code": null, "e": 15047, "s": 14714, "text": "Now, the knn_classifier() function is called to predict the labels for the test emails. The returned list of predicted labels is stored in result. After that, accuracy is calculated using the accuracy_score() method from sklearn library. This method compares the actual labels list test_labels with the predicted labels list result." }, { "code": null, "e": 15430, "s": 15047, "text": " print(\"training data size\\t: \" + str(len(training_data))) print(\"test data size\\t\\t: \" + str(len(test_data))) print(\"K value\\t\\t\\t\\t: \" + str(K)) print(\"Samples tested\\t\\t: \" + str(tsize)) print(\"% accuracy\\t\\t\\t: \" + str(accuracy * 100)) print(\"Number correct\\t\\t: \" + str(int(accuracy * tsize))) print(\"Number wrong\\t\\t: \" + str(int((1 - accuracy) * tsize)))" }, { "code": null, "e": 15657, "s": 15430, "text": "These lines display the details of the run such as the training data size, test data size, K value, number of samples tested, percentage accuracy, number of emails correctly identified, and number of emails falsely identified." }, { "code": null, "e": 15666, "s": 15657, "text": "main(11)" }, { "code": null, "e": 15803, "s": 15666, "text": "Finally, this is the line which initiates the program by calling the main function, and gives it the K value (which is 11 in this case)." }, { "code": null, "e": 16331, "s": 15803, "text": "This is the final output of all the code that has been explained above. It can be seen that using KNN algorithm to classify email into spam and ham, with a K value of 11, and test data size 1582, it gives a 76.7% accuracy rate. Though not the best, it is satisfactory. One downside to note is that it takes a long time to classify the 1582 emails. This is primarily due to the high time complexity, which is the result of three nested for-loops when calculating the euclidean difference between test emails and training emails." } ]
Ackermann Function - GeeksforGeeks
11 Jun, 2021 In computability theory, the Ackermann function, named after Wilhelm Ackermann, is one of the simplest and earliest-discovered examples of a total computable function that is not primitive recursive. All primitive recursive functions are total and computable, but the Ackermann function illustrates that not all total computable functions are primitive recursive. Refer this for more.It’s a function with two arguments each of which can be assigned any non-negative integer.Ackermann function is defined as: Ackermann algorithm: Ackermann(m, n) {next and goal are arrays indexed from 0 to m, initialized so that next[O] through next[m] are 0, goal[O] through goal[m - l] are 1, and goal[m] is -1} repeat value <-- next[O] + 1 transferring <-- true current <-- O while transferring do begin if next[current] = goal[current] then goal[current] <-- value else transferring <-- false next[current] <-- next[current]+l current <-- current + 1 end while until next[m] = n + 1 return value {the value of A(m, n)} end Ackermann Here’s the explanation of the given Algorithm: Let me explain the algorithm by taking the example A(1, 2) where m = 1 and n = 2 So according to the algorithm initially the value of next, goal, value and current are: Though next[current] != goal[current], so else statement will execute and transferring become false. So now, the value of next, goal, value and current are: Similarly by tracing the algorithm until next[m] = 3 the value of next, goal, value and current are changing accordingly. Here’s the explanation how the values are changing, Finally returning the value e.g 4Analysis of this algorithm: The time complexity of this algorithm is: O(mA(m, n)) to compute A(m, n) The space complexity of this algorithm is: O(m) to compute A(m, n) Let’s understand the definition by solving a problem! Solve A(1, 2)?Answer:Given problem is A(1, 2) Here m = 1, n = 2 e.g m > 0 and n > 0 Hence applying third condition of Ackermann function A(1, 2) = A(0, A(1, 1)) β€”β€”β€”- (1) Now, Let’s find A(1, 1) by applying third condition of Ackermann function A(1, 1) = A(0, A(1, 0)) β€”β€”β€”- (2) Now, Let’s find A(1, 0) by applying second condition of Ackermann function A(1, 0) = A(0, 1) β€”β€”β€”- (3) Now, Let’s find A(0, 1) by applying first condition of Ackermann function A(0, 1) = 1 + 1 = 2 Now put this value in equation 3 Hence A(1, 0) = 2 Now put this value in equation 2 A(1, 1) = A(0, 2) β€”β€”β€”- (4) Now, Let’s find A(0, 2) by applying first condition of Ackermann function A(0, 2) = 2 + 1 = 3 Now put this value in equation 4 Hence A(1, 1) = 3 Now put this value in equation 1 A(1, 2) = A(0, 3) β€”β€”β€”- (5) Now, Let’s find A(0, 3) by applying first condition of Ackermann function A(0, 3) = 3 + 1 = 4 Now put this value in equation 5 Hence A(1, 2) = 4So, A (1, 2) = 4 Let’s solve another two questions on this by yourself!Question: Solve A(2, 1)? Answer: 5Question: Solve A(2, 2)? Answer: 7 Here is the simplest c and python recursion function code for generating Ackermann function C++ C Java Python3 C# Javascript // C++ program to illustrate Ackermann function#include <iostream>using namespace std; int ack(int m, int n){ if (m == 0){ return n + 1; } else if((m > 0) && (n == 0)){ return ack(m - 1, 1); } else if((m > 0) && (n > 0)){ return ack(m - 1, ack(m, n - 1)); }} // Driver codeint main(){ int A; A = ack(1, 2); cout << A << endl; return 0;} // This code is contributed by SHUBHAMSINGH10 // C program to illustrate Ackermann function #include <stdio.h>int ack(int m, int n){ if (m == 0){ return n+1; } else if((m > 0) && (n == 0)){ return ack(m-1, 1); } else if((m > 0) && (n > 0)){ return ack(m-1, ack(m, n-1)); }} int main(){ int A; A = ack(1, 2); printf("%d", A); return 0;} // This code is contributed by Amiya Rout // Java program to illustrate Ackermann function class GFG{ static int ack(int m, int n) { if (m == 0) { return n + 1; } else if((m > 0) && (n == 0)) { return ack(m - 1, 1); } else if((m > 0) && (n > 0)) { return ack(m - 1, ack(m, n - 1)); }else return n + 1; } // Driver code public static void main(String args[]) { System.out.println(ack(1, 2)); }} // This code is contributed by AnkitRai01 # Python program to illustrate Ackermann function def A(m, n, s ="% s"): print(s % ("A(% d, % d)" % (m, n))) if m == 0: return n + 1 if n == 0: return A(m - 1, 1, s) n2 = A(m, n - 1, s % ("A(% d, %% s)" % (m - 1))) return A(m - 1, n2, s) print(A(1, 2)) # This code is contributed by Amiya Rout // C# program to illustrate Ackermann functionusing System; class GFG{ static int ack(int m, int n) { if (m == 0) { return n + 1; } else if((m > 0) && (n == 0)) { return ack(m - 1, 1); } else if((m > 0) && (n > 0)) { return ack(m - 1, ack(m, n - 1)); }else return n + 1; } // Driver code public static void Main() { Console.WriteLine(ack(1, 2)); }} // This code is contributed by mohit kumar 29 <script>// Javascript program to illustrate Ackermann function function ack(m,n){ if (m == 0) { return n + 1; } else if((m > 0) && (n == 0)) { return ack(m - 1, 1); } else if((m > 0) && (n > 0)) { return ack(m - 1, ack(m, n - 1)); }else return n + 1;} // Driver codedocument.write(ack(1, 2)); // This code is contributed by unknown2108</script> If you still wish to visualize how this result is arrived at, you can take a look at this page, which animates the calculation of every recursion step. mohit kumar 29 ankthon SHUBHAMSINGH10 unknown2108 Technical Scripter 2019 Advanced Data Structure GATE CS Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Quad Tree Proof that Dominant Set of a Graph is NP-Complete Suffix Array | Set 1 (Introduction) Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems
[ { "code": null, "e": 24462, "s": 24434, "text": "\n11 Jun, 2021" }, { "code": null, "e": 24971, "s": 24462, "text": "In computability theory, the Ackermann function, named after Wilhelm Ackermann, is one of the simplest and earliest-discovered examples of a total computable function that is not primitive recursive. All primitive recursive functions are total and computable, but the Ackermann function illustrates that not all total computable functions are primitive recursive. Refer this for more.It’s a function with two arguments each of which can be assigned any non-negative integer.Ackermann function is defined as: " }, { "code": null, "e": 24994, "s": 24971, "text": "Ackermann algorithm: " }, { "code": null, "e": 25589, "s": 24994, "text": "Ackermann(m, n) \n {next and goal are arrays indexed from 0 to m, initialized so that next[O] \n through next[m] are 0, goal[O] through goal[m - l] are 1, and goal[m] is -1} \nrepeat\n value <-- next[O] + 1 \n transferring <-- true \n current <-- O \n while transferring do begin\n if next[current] = goal[current] then goal[current] <-- value\n else transferring <-- false\n next[current] <-- next[current]+l\n current <-- current + 1 \n end while\nuntil next[m] = n + 1 \nreturn value {the value of A(m, n)}\nend Ackermann " }, { "code": null, "e": 25806, "s": 25589, "text": "Here’s the explanation of the given Algorithm: Let me explain the algorithm by taking the example A(1, 2) where m = 1 and n = 2 So according to the algorithm initially the value of next, goal, value and current are: " }, { "code": null, "e": 25964, "s": 25806, "text": "Though next[current] != goal[current], so else statement will execute and transferring become false. So now, the value of next, goal, value and current are: " }, { "code": null, "e": 26139, "s": 25964, "text": "Similarly by tracing the algorithm until next[m] = 3 the value of next, goal, value and current are changing accordingly. Here’s the explanation how the values are changing, " }, { "code": null, "e": 26205, "s": 26143, "text": "Finally returning the value e.g 4Analysis of this algorithm: " }, { "code": null, "e": 26280, "s": 26205, "text": "The time complexity of this algorithm is: O(mA(m, n)) to compute A(m, n) " }, { "code": null, "e": 26349, "s": 26280, "text": "The space complexity of this algorithm is: O(m) to compute A(m, n) " }, { "code": null, "e": 26404, "s": 26349, "text": "Let’s understand the definition by solving a problem! " }, { "code": null, "e": 27355, "s": 26404, "text": "Solve A(1, 2)?Answer:Given problem is A(1, 2) Here m = 1, n = 2 e.g m > 0 and n > 0 Hence applying third condition of Ackermann function A(1, 2) = A(0, A(1, 1)) β€”β€”β€”- (1) Now, Let’s find A(1, 1) by applying third condition of Ackermann function A(1, 1) = A(0, A(1, 0)) β€”β€”β€”- (2) Now, Let’s find A(1, 0) by applying second condition of Ackermann function A(1, 0) = A(0, 1) β€”β€”β€”- (3) Now, Let’s find A(0, 1) by applying first condition of Ackermann function A(0, 1) = 1 + 1 = 2 Now put this value in equation 3 Hence A(1, 0) = 2 Now put this value in equation 2 A(1, 1) = A(0, 2) β€”β€”β€”- (4) Now, Let’s find A(0, 2) by applying first condition of Ackermann function A(0, 2) = 2 + 1 = 3 Now put this value in equation 4 Hence A(1, 1) = 3 Now put this value in equation 1 A(1, 2) = A(0, 3) β€”β€”β€”- (5) Now, Let’s find A(0, 3) by applying first condition of Ackermann function A(0, 3) = 3 + 1 = 4 Now put this value in equation 5 Hence A(1, 2) = 4So, A (1, 2) = 4 " }, { "code": null, "e": 27481, "s": 27357, "text": "Let’s solve another two questions on this by yourself!Question: Solve A(2, 1)? Answer: 5Question: Solve A(2, 2)? Answer: 7 " }, { "code": null, "e": 27574, "s": 27481, "text": "Here is the simplest c and python recursion function code for generating Ackermann function " }, { "code": null, "e": 27578, "s": 27574, "text": "C++" }, { "code": null, "e": 27580, "s": 27578, "text": "C" }, { "code": null, "e": 27585, "s": 27580, "text": "Java" }, { "code": null, "e": 27593, "s": 27585, "text": "Python3" }, { "code": null, "e": 27596, "s": 27593, "text": "C#" }, { "code": null, "e": 27607, "s": 27596, "text": "Javascript" }, { "code": "// C++ program to illustrate Ackermann function#include <iostream>using namespace std; int ack(int m, int n){ if (m == 0){ return n + 1; } else if((m > 0) && (n == 0)){ return ack(m - 1, 1); } else if((m > 0) && (n > 0)){ return ack(m - 1, ack(m, n - 1)); }} // Driver codeint main(){ int A; A = ack(1, 2); cout << A << endl; return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 28041, "s": 27607, "text": null }, { "code": "// C program to illustrate Ackermann function #include <stdio.h>int ack(int m, int n){ if (m == 0){ return n+1; } else if((m > 0) && (n == 0)){ return ack(m-1, 1); } else if((m > 0) && (n > 0)){ return ack(m-1, ack(m, n-1)); }} int main(){ int A; A = ack(1, 2); printf(\"%d\", A); return 0;} // This code is contributed by Amiya Rout", "e": 28424, "s": 28041, "text": null }, { "code": "// Java program to illustrate Ackermann function class GFG{ static int ack(int m, int n) { if (m == 0) { return n + 1; } else if((m > 0) && (n == 0)) { return ack(m - 1, 1); } else if((m > 0) && (n > 0)) { return ack(m - 1, ack(m, n - 1)); }else return n + 1; } // Driver code public static void main(String args[]) { System.out.println(ack(1, 2)); }} // This code is contributed by AnkitRai01", "e": 28951, "s": 28424, "text": null }, { "code": "# Python program to illustrate Ackermann function def A(m, n, s =\"% s\"): print(s % (\"A(% d, % d)\" % (m, n))) if m == 0: return n + 1 if n == 0: return A(m - 1, 1, s) n2 = A(m, n - 1, s % (\"A(% d, %% s)\" % (m - 1))) return A(m - 1, n2, s) print(A(1, 2)) # This code is contributed by Amiya Rout", "e": 29274, "s": 28951, "text": null }, { "code": "// C# program to illustrate Ackermann functionusing System; class GFG{ static int ack(int m, int n) { if (m == 0) { return n + 1; } else if((m > 0) && (n == 0)) { return ack(m - 1, 1); } else if((m > 0) && (n > 0)) { return ack(m - 1, ack(m, n - 1)); }else return n + 1; } // Driver code public static void Main() { Console.WriteLine(ack(1, 2)); }} // This code is contributed by mohit kumar 29", "e": 29811, "s": 29274, "text": null }, { "code": "<script>// Javascript program to illustrate Ackermann function function ack(m,n){ if (m == 0) { return n + 1; } else if((m > 0) && (n == 0)) { return ack(m - 1, 1); } else if((m > 0) && (n > 0)) { return ack(m - 1, ack(m, n - 1)); }else return n + 1;} // Driver codedocument.write(ack(1, 2)); // This code is contributed by unknown2108</script>", "e": 30256, "s": 29811, "text": null }, { "code": null, "e": 30409, "s": 30256, "text": "If you still wish to visualize how this result is arrived at, you can take a look at this page, which animates the calculation of every recursion step. " }, { "code": null, "e": 30424, "s": 30409, "text": "mohit kumar 29" }, { "code": null, "e": 30432, "s": 30424, "text": "ankthon" }, { "code": null, "e": 30447, "s": 30432, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30459, "s": 30447, "text": "unknown2108" }, { "code": null, "e": 30483, "s": 30459, "text": "Technical Scripter 2019" }, { "code": null, "e": 30507, "s": 30483, "text": "Advanced Data Structure" }, { "code": null, "e": 30515, "s": 30507, "text": "GATE CS" }, { "code": null, "e": 30534, "s": 30515, "text": "Technical Scripter" }, { "code": null, "e": 30632, "s": 30534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30674, "s": 30632, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 30720, "s": 30674, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 30730, "s": 30720, "text": "Quad Tree" }, { "code": null, "e": 30780, "s": 30730, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 30816, "s": 30780, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 30836, "s": 30816, "text": "Layers of OSI Model" }, { "code": null, "e": 30860, "s": 30836, "text": "ACID Properties in DBMS" }, { "code": null, "e": 30873, "s": 30860, "text": "TCP/IP Model" }, { "code": null, "e": 30922, "s": 30873, "text": "Page Replacement Algorithms in Operating Systems" } ]
numpy.resize
This function returns a new array with the specified size. If the new size is greater than the original, the repeated copies of entries in the original are contained. The function takes the following parameters. numpy.resize(arr, shape) Where, arr Input array to be resized shape New shape of the resulting array import numpy as np a = np.array([[1,2,3],[4,5,6]]) print 'First array:' print a print '\n' print 'The shape of first array:' print a.shape print '\n' b = np.resize(a, (3,2)) print 'Second array:' print b print '\n' print 'The shape of second array:' print b.shape print '\n' # Observe that first row of a is repeated in b since size is bigger print 'Resize the second array:' b = np.resize(a,(3,3)) print b The above program will produce the following output βˆ’ First array: [[1 2 3] [4 5 6]] The shape of first array: (2, 3) Second array: [[1 2] [3 4] [5 6]] The shape of second array: (3, 2) Resize the second array: [[1 2 3] [4 5 6] [1 2 3]] 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": 2455, "s": 2243, "text": "This function returns a new array with the specified size. If the new size is greater than the original, the repeated copies of entries in the original are contained. The function takes the following parameters." }, { "code": null, "e": 2481, "s": 2455, "text": "numpy.resize(arr, shape)\n" }, { "code": null, "e": 2488, "s": 2481, "text": "Where," }, { "code": null, "e": 2492, "s": 2488, "text": "arr" }, { "code": null, "e": 2518, "s": 2492, "text": "Input array to be resized" }, { "code": null, "e": 2524, "s": 2518, "text": "shape" }, { "code": null, "e": 2557, "s": 2524, "text": "New shape of the resulting array" }, { "code": null, "e": 2989, "s": 2557, "text": "import numpy as np \na = np.array([[1,2,3],[4,5,6]]) \n\nprint 'First array:' \nprint a \nprint '\\n'\n\nprint 'The shape of first array:' \nprint a.shape \nprint '\\n' \nb = np.resize(a, (3,2)) \n\nprint 'Second array:' \nprint b \nprint '\\n' \n\nprint 'The shape of second array:' \nprint b.shape \nprint '\\n' \n# Observe that first row of a is repeated in b since size is bigger \n\nprint 'Resize the second array:' \nb = np.resize(a,(3,3)) \nprint b" }, { "code": null, "e": 3043, "s": 2989, "text": "The above program will produce the following output βˆ’" }, { "code": null, "e": 3236, "s": 3043, "text": "First array:\n[[1 2 3]\n [4 5 6]]\n\nThe shape of first array:\n(2, 3)\n\nSecond array:\n[[1 2]\n [3 4]\n [5 6]]\n\nThe shape of second array:\n(3, 2)\n\nResize the second array:\n[[1 2 3]\n [4 5 6]\n [1 2 3]]\n" }, { "code": null, "e": 3269, "s": 3236, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3286, "s": 3269, "text": " Abhilash Nelson" }, { "code": null, "e": 3319, "s": 3286, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 3354, "s": 3319, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3387, "s": 3354, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 3422, "s": 3387, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3457, "s": 3422, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3469, "s": 3457, "text": " Akbar Khan" }, { "code": null, "e": 3502, "s": 3469, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3517, "s": 3502, "text": " Pruthviraja L" }, { "code": null, "e": 3550, "s": 3517, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3557, "s": 3550, "text": " Anmol" }, { "code": null, "e": 3564, "s": 3557, "text": " Print" }, { "code": null, "e": 3575, "s": 3564, "text": " Add Notes" } ]
How Turi Create is Disrupting the Machine Learning Landscape | by Jonathan Balaban | Towards Data Science
A few months ago β€” Thursday, January 18 β€” I presented at my first Seattle meetup. This was three days after I moved my family cross-country from Chicago, so no time was wasted! The reason? Nothing was more on my radar than the news that Apple had open-sourced Turi Create, the Machine Learning (ML) library it had come to own with the 2016 acquisition of Turi. Bottom line: Turi Create is a Pythonic Machine Learning library that’s amazingly powerful and easy to use, and you should explore its capabilities! First, I’d like to thank Metis, BeMyApp, and Intel for co-sponsoring the event. This post is a summary of the meetup: what I presented, pertinent questions asked by the audience, a note on a few surprise visitors, and my thoughts on how Turi Create may evolve in the future. I’ll also share best practices, lessons learned, and ideas for my future projects with the package. To start, I shared lessons learned in preparing the GraphLab Create environment. Keen-eyed readers may notice that GraphLab Create (henceforth GC) looks like a different product than Turi Create (TC); this differenceβ€” I was informed by the Turi team β€” is only skin deep, as both packages use the same core code, and the open-source variant (TC) can do basically everything GC can. Therefore, while a few procedural items may differ, general usage is quite similar. To deeply understand how the product has evolved, I highly recommend this walkthrough by Carlos Guestrin, the founder. It’s five years old, but Guestrin touches on motivations and areas of focus during the early development years. And to understand where the package fits in the β€˜stack’, here’s a common architecture: Of note, GC and TC both run on Python 2, and the environment must be set up with specific versions of supporting libraries. As a challenge, I attempted to incorporate the new package in my main anaconda environment, but ran into version and dependency hell. So, for first-timers: Ensure you have at least 8GB of RAM for serious work, or set up in a Virtual EnvironmentCreate a new conda environment, per setup instructionsThen, register for a license (for GC)If using TC, clone the repo to your machineTry a few exercises in the Getting Started guide Ensure you have at least 8GB of RAM for serious work, or set up in a Virtual Environment Create a new conda environment, per setup instructions Then, register for a license (for GC) If using TC, clone the repo to your machine Try a few exercises in the Getting Started guide Loading and managing data is very similar to Pandas: import graphlab as gl%matplotlib inline# load data into SFrameurl = 'https://raw.githubusercontent.com/plotly/datasets/master/data.csv'df = gl.SFrame.read_csv(url) From there, we can invoke summary stats and an interactive dashboard with the following functions: # summary statistics for a columndf['column'].sketch_summary()# show dashboarddf.show() You’ll then be able to quickly find specific row ranges, track more summary stats, and build interactive charts like the ones below: Modeling looks eerily similar to SciKit-Learn, but that’s a good thing. If it ain’t broke, don’t fix it: # load housing data and fit a linear modelurl = 'https://static.turi.com/datasets/regression/Housing.csv'x = gl.SFrame.read_csv(url)lm = gl.linear_regression.create(x, target='price') Of note, GC auto-creates a validation β€˜out of sample’ set for tracking true model performance. There are a number of clever tricks incorporated throughout that allow you to code more efficiently and get results faster. However, GC pre-selects common approaches, so you’ll need to be aware of the default arguments and assumptions per the documentation! One common audience question related to performance compared to SciKit-Learn. If you’re fitting models or churning data using just the CPU, differences are small, and will come down to code optimization, slightly different solver approaches, etc. However, if you have a highly parallelizable task, and are running on AWS P2 or P3 instances, or you have a powerhouse Cuda setup in the office, we’re talking orders of magnitude faster with TC. That fact alone could be the perfect reason to move your firm’s modeling to a Turi environment. The general comparison between TC and SciKit-Learn’s Python-based ML libraries β€” for now β€” looks like this: Open Source: Scikit-learn is an open source library with over 500 contributors and strong support Support for Python 3: Scikit-learn supports Python 3 while Graphlab Create is only compatible with Python 2 More Algorithms: Scikit-learn has more algorithms compared to Graphlab Graphlab Create is commercial software with dedicated 24/7 support Scalable: Scikit-learn implementations are executed ONLY in memory. GraphLab Create is able to scale out-of-core, and many of the multi-threaded implementations take advantage of multiple cores on the machine. GPU Support: You can install Graphlab Create with GPU Acceleration, which can make it insanely fast for certain tasks Finally, after the talk, three of Turi’s core members β€” responsible for coding and development of both GC and TC β€” came up and introduced themselves! Now Apple employees, we had an in-depth chat about the future of the product, external market perceptions, and business model. Amazing! And probably a good I didn’t know they were watching me all along... ignorance is bliss. Apple is quite serious about building out its Machine Learning (ML) capabilities, as it seeks to compete within the lucrative β€œbig data” domain with other giants like Google and Facebook. Apple’s strategy, however, is quite different. As an organization which prides itself on customers’ data privacy, the focus firmly sits on leveraging what Apple knows about users of its products to better the general user experience, including: Siri becoming more intelligent to predict your needs Apple Music leveraging ML to help you discover amazing new artists Caller ID for new numbers that call your iPhone Using ML to predict your calorie expenditure and general activity Differential privacy to power all of these services We can see hints at the latest and greatest products and services β€” and how data science is implemented β€” on Apple’s regularly-updated and public-facing blog. TC is already a worthy competitor to the Pandas and SciKit-Learn combo, with its full stack data management and modeling capabilities. It’s fast and efficient, and has certain features β€” like GPU acceleration β€” that are non-existent or early stage in SciKit-Learn. In addition, because the product is a key facet in Apple’s ML push, I expect to see deep integration with frameworks like Core ML, ARKit, and HealthKit. Turi has functionality overlap with platforms like Tensorflow, and this overlap will likely grow within the deep learning space, given the focus and hype around models like neural networks. In fact, one of the key value-propositions of GPU acceleration is to allow faster fitting of deep models on large datasets. I also hope to see wrappers like Keras expand the ease with which data scientists modify parameters and architectures. There’s already a quick guide on how to integrate TC into an iPhone app and deploy your ML models straight to users via the App Store. Current model offerings include the list below, but we should see more added with time: Recommender systems Image classification Image similarity Object detection Activity classifier Text classifier Finally, I expect to see a strong push deeper into the Topic Modeling and NLP space over the coming years, especially as the sophistication of Siri continues. So TC seems like an amazing platform, but the question that really matters is this: How can Turi Create benefit my business? If your business sells a subscription service, or licenses software, TC’s extensive suite of classification models may determine which customers are more likely to turn over, or β€œchurn”. You can then incentivize those customers to renew, or determine if another product fits their needs. If your firm provides a number of products or services β€” and you know something about your customer base β€” you can implement TC’s recommender system to quantify the customers’ interest and prioritize which new items you market or offer. These models power Amazon and eBay’s β€œrecommended for you” listings, Spotify’s music playlist curation, and GrubHub’s vendor spotlights. Finally, if you run a medical business that collects heart, brain, or activity metrics using on-body sensors, TC’s activity classifier can ingest data from devices like accelerometers, gyroscopes, thermostats, and others. The model will then predict what form of exercise, heart condition, or medical emergency may be happening. This application can extend to other domains, like cybersecurity, engineering applications, or any field where patterns are deduced from noisy data. I’d like to recreate some of my past projects in the TC environment, as a real-world test with a vetted baseline. I’ll deploy some of this code β€” especially my ensemble models β€” to various AWS instance types in order to guage which architecture gives me the highest performance. This year, I’m focused on applying more data science to my investment and cryptocurrency strategy, and TC is a strong contender for building a neural network or similar portfolio optimization model. And last but not least, as a data science instructor with Metis, I’ll be looking for ways to incorporate TC in our curriculum for student exposure. Ultimate success in my book: a student builds an iOS Application centered on ML and successfully deploys it to a market of over one billion smartphone users! How are you thinking of getting started with Turi Create? Comment below or connect with me on Twitter and LinkedIn.
[ { "code": null, "e": 349, "s": 172, "text": "A few months ago β€” Thursday, January 18 β€” I presented at my first Seattle meetup. This was three days after I moved my family cross-country from Chicago, so no time was wasted!" }, { "code": null, "e": 533, "s": 349, "text": "The reason? Nothing was more on my radar than the news that Apple had open-sourced Turi Create, the Machine Learning (ML) library it had come to own with the 2016 acquisition of Turi." }, { "code": null, "e": 681, "s": 533, "text": "Bottom line: Turi Create is a Pythonic Machine Learning library that’s amazingly powerful and easy to use, and you should explore its capabilities!" }, { "code": null, "e": 761, "s": 681, "text": "First, I’d like to thank Metis, BeMyApp, and Intel for co-sponsoring the event." }, { "code": null, "e": 1056, "s": 761, "text": "This post is a summary of the meetup: what I presented, pertinent questions asked by the audience, a note on a few surprise visitors, and my thoughts on how Turi Create may evolve in the future. I’ll also share best practices, lessons learned, and ideas for my future projects with the package." }, { "code": null, "e": 1521, "s": 1056, "text": "To start, I shared lessons learned in preparing the GraphLab Create environment. Keen-eyed readers may notice that GraphLab Create (henceforth GC) looks like a different product than Turi Create (TC); this differenceβ€” I was informed by the Turi team β€” is only skin deep, as both packages use the same core code, and the open-source variant (TC) can do basically everything GC can. Therefore, while a few procedural items may differ, general usage is quite similar." }, { "code": null, "e": 1839, "s": 1521, "text": "To deeply understand how the product has evolved, I highly recommend this walkthrough by Carlos Guestrin, the founder. It’s five years old, but Guestrin touches on motivations and areas of focus during the early development years. And to understand where the package fits in the β€˜stack’, here’s a common architecture:" }, { "code": null, "e": 2119, "s": 1839, "text": "Of note, GC and TC both run on Python 2, and the environment must be set up with specific versions of supporting libraries. As a challenge, I attempted to incorporate the new package in my main anaconda environment, but ran into version and dependency hell. So, for first-timers:" }, { "code": null, "e": 2390, "s": 2119, "text": "Ensure you have at least 8GB of RAM for serious work, or set up in a Virtual EnvironmentCreate a new conda environment, per setup instructionsThen, register for a license (for GC)If using TC, clone the repo to your machineTry a few exercises in the Getting Started guide" }, { "code": null, "e": 2479, "s": 2390, "text": "Ensure you have at least 8GB of RAM for serious work, or set up in a Virtual Environment" }, { "code": null, "e": 2534, "s": 2479, "text": "Create a new conda environment, per setup instructions" }, { "code": null, "e": 2572, "s": 2534, "text": "Then, register for a license (for GC)" }, { "code": null, "e": 2616, "s": 2572, "text": "If using TC, clone the repo to your machine" }, { "code": null, "e": 2665, "s": 2616, "text": "Try a few exercises in the Getting Started guide" }, { "code": null, "e": 2718, "s": 2665, "text": "Loading and managing data is very similar to Pandas:" }, { "code": null, "e": 2882, "s": 2718, "text": "import graphlab as gl%matplotlib inline# load data into SFrameurl = 'https://raw.githubusercontent.com/plotly/datasets/master/data.csv'df = gl.SFrame.read_csv(url)" }, { "code": null, "e": 2981, "s": 2882, "text": "From there, we can invoke summary stats and an interactive dashboard with the following functions:" }, { "code": null, "e": 3069, "s": 2981, "text": "# summary statistics for a columndf['column'].sketch_summary()# show dashboarddf.show()" }, { "code": null, "e": 3202, "s": 3069, "text": "You’ll then be able to quickly find specific row ranges, track more summary stats, and build interactive charts like the ones below:" }, { "code": null, "e": 3307, "s": 3202, "text": "Modeling looks eerily similar to SciKit-Learn, but that’s a good thing. If it ain’t broke, don’t fix it:" }, { "code": null, "e": 3491, "s": 3307, "text": "# load housing data and fit a linear modelurl = 'https://static.turi.com/datasets/regression/Housing.csv'x = gl.SFrame.read_csv(url)lm = gl.linear_regression.create(x, target='price')" }, { "code": null, "e": 3844, "s": 3491, "text": "Of note, GC auto-creates a validation β€˜out of sample’ set for tracking true model performance. There are a number of clever tricks incorporated throughout that allow you to code more efficiently and get results faster. However, GC pre-selects common approaches, so you’ll need to be aware of the default arguments and assumptions per the documentation!" }, { "code": null, "e": 4286, "s": 3844, "text": "One common audience question related to performance compared to SciKit-Learn. If you’re fitting models or churning data using just the CPU, differences are small, and will come down to code optimization, slightly different solver approaches, etc. However, if you have a highly parallelizable task, and are running on AWS P2 or P3 instances, or you have a powerhouse Cuda setup in the office, we’re talking orders of magnitude faster with TC." }, { "code": null, "e": 4382, "s": 4286, "text": "That fact alone could be the perfect reason to move your firm’s modeling to a Turi environment." }, { "code": null, "e": 4490, "s": 4382, "text": "The general comparison between TC and SciKit-Learn’s Python-based ML libraries β€” for now β€” looks like this:" }, { "code": null, "e": 4588, "s": 4490, "text": "Open Source: Scikit-learn is an open source library with over 500 contributors and strong support" }, { "code": null, "e": 4696, "s": 4588, "text": "Support for Python 3: Scikit-learn supports Python 3 while Graphlab Create is only compatible with Python 2" }, { "code": null, "e": 4767, "s": 4696, "text": "More Algorithms: Scikit-learn has more algorithms compared to Graphlab" }, { "code": null, "e": 4834, "s": 4767, "text": "Graphlab Create is commercial software with dedicated 24/7 support" }, { "code": null, "e": 5044, "s": 4834, "text": "Scalable: Scikit-learn implementations are executed ONLY in memory. GraphLab Create is able to scale out-of-core, and many of the multi-threaded implementations take advantage of multiple cores on the machine." }, { "code": null, "e": 5162, "s": 5044, "text": "GPU Support: You can install Graphlab Create with GPU Acceleration, which can make it insanely fast for certain tasks" }, { "code": null, "e": 5439, "s": 5162, "text": "Finally, after the talk, three of Turi’s core members β€” responsible for coding and development of both GC and TC β€” came up and introduced themselves! Now Apple employees, we had an in-depth chat about the future of the product, external market perceptions, and business model." }, { "code": null, "e": 5448, "s": 5439, "text": "Amazing!" }, { "code": null, "e": 5537, "s": 5448, "text": "And probably a good I didn’t know they were watching me all along... ignorance is bliss." }, { "code": null, "e": 5970, "s": 5537, "text": "Apple is quite serious about building out its Machine Learning (ML) capabilities, as it seeks to compete within the lucrative β€œbig data” domain with other giants like Google and Facebook. Apple’s strategy, however, is quite different. As an organization which prides itself on customers’ data privacy, the focus firmly sits on leveraging what Apple knows about users of its products to better the general user experience, including:" }, { "code": null, "e": 6023, "s": 5970, "text": "Siri becoming more intelligent to predict your needs" }, { "code": null, "e": 6090, "s": 6023, "text": "Apple Music leveraging ML to help you discover amazing new artists" }, { "code": null, "e": 6138, "s": 6090, "text": "Caller ID for new numbers that call your iPhone" }, { "code": null, "e": 6204, "s": 6138, "text": "Using ML to predict your calorie expenditure and general activity" }, { "code": null, "e": 6256, "s": 6204, "text": "Differential privacy to power all of these services" }, { "code": null, "e": 6415, "s": 6256, "text": "We can see hints at the latest and greatest products and services β€” and how data science is implemented β€” on Apple’s regularly-updated and public-facing blog." }, { "code": null, "e": 6833, "s": 6415, "text": "TC is already a worthy competitor to the Pandas and SciKit-Learn combo, with its full stack data management and modeling capabilities. It’s fast and efficient, and has certain features β€” like GPU acceleration β€” that are non-existent or early stage in SciKit-Learn. In addition, because the product is a key facet in Apple’s ML push, I expect to see deep integration with frameworks like Core ML, ARKit, and HealthKit." }, { "code": null, "e": 7266, "s": 6833, "text": "Turi has functionality overlap with platforms like Tensorflow, and this overlap will likely grow within the deep learning space, given the focus and hype around models like neural networks. In fact, one of the key value-propositions of GPU acceleration is to allow faster fitting of deep models on large datasets. I also hope to see wrappers like Keras expand the ease with which data scientists modify parameters and architectures." }, { "code": null, "e": 7489, "s": 7266, "text": "There’s already a quick guide on how to integrate TC into an iPhone app and deploy your ML models straight to users via the App Store. Current model offerings include the list below, but we should see more added with time:" }, { "code": null, "e": 7509, "s": 7489, "text": "Recommender systems" }, { "code": null, "e": 7530, "s": 7509, "text": "Image classification" }, { "code": null, "e": 7547, "s": 7530, "text": "Image similarity" }, { "code": null, "e": 7564, "s": 7547, "text": "Object detection" }, { "code": null, "e": 7584, "s": 7564, "text": "Activity classifier" }, { "code": null, "e": 7600, "s": 7584, "text": "Text classifier" }, { "code": null, "e": 7759, "s": 7600, "text": "Finally, I expect to see a strong push deeper into the Topic Modeling and NLP space over the coming years, especially as the sophistication of Siri continues." }, { "code": null, "e": 7843, "s": 7759, "text": "So TC seems like an amazing platform, but the question that really matters is this:" }, { "code": null, "e": 7884, "s": 7843, "text": "How can Turi Create benefit my business?" }, { "code": null, "e": 8172, "s": 7884, "text": "If your business sells a subscription service, or licenses software, TC’s extensive suite of classification models may determine which customers are more likely to turn over, or β€œchurn”. You can then incentivize those customers to renew, or determine if another product fits their needs." }, { "code": null, "e": 8546, "s": 8172, "text": "If your firm provides a number of products or services β€” and you know something about your customer base β€” you can implement TC’s recommender system to quantify the customers’ interest and prioritize which new items you market or offer. These models power Amazon and eBay’s β€œrecommended for you” listings, Spotify’s music playlist curation, and GrubHub’s vendor spotlights." }, { "code": null, "e": 9024, "s": 8546, "text": "Finally, if you run a medical business that collects heart, brain, or activity metrics using on-body sensors, TC’s activity classifier can ingest data from devices like accelerometers, gyroscopes, thermostats, and others. The model will then predict what form of exercise, heart condition, or medical emergency may be happening. This application can extend to other domains, like cybersecurity, engineering applications, or any field where patterns are deduced from noisy data." }, { "code": null, "e": 9303, "s": 9024, "text": "I’d like to recreate some of my past projects in the TC environment, as a real-world test with a vetted baseline. I’ll deploy some of this code β€” especially my ensemble models β€” to various AWS instance types in order to guage which architecture gives me the highest performance." }, { "code": null, "e": 9502, "s": 9303, "text": "This year, I’m focused on applying more data science to my investment and cryptocurrency strategy, and TC is a strong contender for building a neural network or similar portfolio optimization model." }, { "code": null, "e": 9808, "s": 9502, "text": "And last but not least, as a data science instructor with Metis, I’ll be looking for ways to incorporate TC in our curriculum for student exposure. Ultimate success in my book: a student builds an iOS Application centered on ML and successfully deploys it to a market of over one billion smartphone users!" } ]
DFA of a string with at least two 0’s and at least two 1’s - GeeksforGeeks
11 May, 2018 Problem – Draw detereministic finite automata (DFA) of a string with at least two 0’s and at least two 1’s. The first thing that come to mind after reading this question us that we count the number of 1’s and 0’s. Thereafter if they both are at least 2 the string is accepted else not accepted. But we do not have any concept of memory in a DFA so we cannot do it by this method. Input : 1 0 1 1 0 0 Output : Accepted Input : 1 1 1 0 1 Output : Not accepted Approach Used –The first thing we observe is that both 0’s and 1’s should be at least 2. If any of these is less than 2, then string will not be accepted. In this string will be accepted in only last case where both 0’s and 1’s will be at least 2. Initially count of both 0 and 1 is zero and we are on state Q0. Step-1: If input is 1 then count of 1 increases to 1. Goto state Q1If input is 0 then count of 0 increases to 1. Goto state Q3 Step-2: If input is 1 then count of 1 increases to 2. Goto state Q2If input is 0 then count of 0 increases to 1. Goto state Q4 Step-3: If input is 1 then count of 1 keeps increasing by 1. Remain in the same stateIf input is 0 then count of 0 increases to 1. Goto state Q5 Step-4: If input is 1 then count of 1 increases to 1. Goto state Q4If input is 0 then count of 0 increases to 2. Goto state Q6 Step-5: If input is 1 then count of 1 increases to 2. Goto state Q5If input is 0 then count of 0 increases to 2. Goto state Q7 Step-6: If input is 1 then count of 1 keeps increasing by 1. Remain in the same state.If input is 0 then count of 0 increases to 2. Goto state Q8 Step-7: If input is 1 then count of 1 increases to 1. Goto state Q7If input is 0 then count of 0 keeps increasing by 1. Remain in the same state. Step-8: If input is 1 then count of 1 increases to 2. Goto state Q8If input is 0 then count of 0 keeps increasing by 1. Remain in the same state. Step-9: If input is 1 then count of 1 keeps increasing by 1. Remain in the same state.If input is 0 then count of 0 keeps increasing by 1. Remain in the same state.If string is finished then ACCEPTED GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems Difference between DFA and NFA Design 101 sequence detector (Mealy machine) Closure properties of Regular languages Conversion of Epsilon-NFA to NFA Boyer-Moore Majority Voting Algorithm
[ { "code": null, "e": 29836, "s": 29808, "text": "\n11 May, 2018" }, { "code": null, "e": 29944, "s": 29836, "text": "Problem – Draw detereministic finite automata (DFA) of a string with at least two 0’s and at least two 1’s." }, { "code": null, "e": 30216, "s": 29944, "text": "The first thing that come to mind after reading this question us that we count the number of 1’s and 0’s. Thereafter if they both are at least 2 the string is accepted else not accepted. But we do not have any concept of memory in a DFA so we cannot do it by this method." }, { "code": null, "e": 30299, "s": 30216, "text": "Input : 1 0 1 1 0 0\nOutput : Accepted\n\nInput : 1 1 1 0 1 \nOutput : Not accepted\n" }, { "code": null, "e": 30547, "s": 30299, "text": "Approach Used –The first thing we observe is that both 0’s and 1’s should be at least 2. If any of these is less than 2, then string will not be accepted. In this string will be accepted in only last case where both 0’s and 1’s will be at least 2." }, { "code": null, "e": 30611, "s": 30547, "text": "Initially count of both 0 and 1 is zero and we are on state Q0." }, { "code": null, "e": 30738, "s": 30611, "text": "Step-1: If input is 1 then count of 1 increases to 1. Goto state Q1If input is 0 then count of 0 increases to 1. Goto state Q3" }, { "code": null, "e": 30865, "s": 30738, "text": "Step-2: If input is 1 then count of 1 increases to 2. Goto state Q2If input is 0 then count of 0 increases to 1. Goto state Q4" }, { "code": null, "e": 31010, "s": 30865, "text": "Step-3: If input is 1 then count of 1 keeps increasing by 1. Remain in the same stateIf input is 0 then count of 0 increases to 1. Goto state Q5" }, { "code": null, "e": 31137, "s": 31010, "text": "Step-4: If input is 1 then count of 1 increases to 1. Goto state Q4If input is 0 then count of 0 increases to 2. Goto state Q6" }, { "code": null, "e": 31264, "s": 31137, "text": "Step-5: If input is 1 then count of 1 increases to 2. Goto state Q5If input is 0 then count of 0 increases to 2. Goto state Q7" }, { "code": null, "e": 31410, "s": 31264, "text": "Step-6: If input is 1 then count of 1 keeps increasing by 1. Remain in the same state.If input is 0 then count of 0 increases to 2. Goto state Q8" }, { "code": null, "e": 31556, "s": 31410, "text": "Step-7: If input is 1 then count of 1 increases to 1. Goto state Q7If input is 0 then count of 0 keeps increasing by 1. Remain in the same state." }, { "code": null, "e": 31702, "s": 31556, "text": "Step-8: If input is 1 then count of 1 increases to 2. Goto state Q8If input is 0 then count of 0 keeps increasing by 1. Remain in the same state." }, { "code": null, "e": 31902, "s": 31702, "text": "Step-9: If input is 1 then count of 1 keeps increasing by 1. Remain in the same state.If input is 0 then count of 0 keeps increasing by 1. Remain in the same state.If string is finished then ACCEPTED" }, { "code": null, "e": 31910, "s": 31902, "text": "GATE CS" }, { "code": null, "e": 31943, "s": 31910, "text": "Theory of Computation & Automata" }, { "code": null, "e": 32041, "s": 31943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32061, "s": 32041, "text": "Layers of OSI Model" }, { "code": null, "e": 32085, "s": 32061, "text": "ACID Properties in DBMS" }, { "code": null, "e": 32098, "s": 32085, "text": "TCP/IP Model" }, { "code": null, "e": 32147, "s": 32098, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 32174, "s": 32147, "text": "Types of Operating Systems" }, { "code": null, "e": 32205, "s": 32174, "text": "Difference between DFA and NFA" }, { "code": null, "e": 32250, "s": 32205, "text": "Design 101 sequence detector (Mealy machine)" }, { "code": null, "e": 32290, "s": 32250, "text": "Closure properties of Regular languages" }, { "code": null, "e": 32323, "s": 32290, "text": "Conversion of Epsilon-NFA to NFA" } ]
CSS Full Form - GeeksforGeeks
20 Dec, 2019 CSS stands for Cascading Style Sheet, it is a style sheet language used to shape the HTML elements that will be displayed in the browsers as a web-page. Without using CSS, the website which has been created by using HTML, will look dull. Basically CSS gives the outer cover on any HTML elements. If you consider HTML as a skeleton of the web-page then the CSS will be the skin of the skeleton. The Internet media type (MIME type) of CSS is text/CSS. The CSS was developed by the World Wide Web Consortium (W3C) in the year of 1996. The CSS can be applied to HTML documents in different ways. The inline CSS style that will look like below code:<h1 style="color: green;">GeeksforGeeks</h1> <h1 style="color: green;">GeeksforGeeks</h1> The internal CSS style that will look like below code:<!DOCTYPE html> <html> <head> <title> internal CSS </title> <style> h1 { color: green; } </style> <head> <body> <h1">GeeksforGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> internal CSS </title> <style> h1 { color: green; } </style> <head> <body> <h1">GeeksforGeeks</h1> </body> </html> The external CSS style that will look like below code:/* this will be separate file */ <style> h1 { color: green; } </style> /* this will be separate file */ <style> h1 { color: green; } </style> CSS version release year: Characteristics of CSS: Maintenance: It is easy to maintain, changing in a single place will affect globally in your web site. No need to change every specific place. Time-saving: You can easily use any single CSS script at multiple places. Support: CSS is supported by all the browsers and search engines. Cache storing: CSS can store web applications locally with the help of offline cache so you can see the web site when you are offline. Native front-end: CSS contains a huge list of attributes and function that is helpful to design the HTML page. Selectors: In CSS, there are lots of selectors (ID selectors, Class Selectors, etc.) that will be helpful to perform specific tasks. Advantages of CSS: CSS is compatible with all the devices. With the help of CSS, website maintenance is easy and faster. CSS support consistent and spontaneous changes. CSS make the website faster and enhances search engine capabilities to crawl the web pages It holds a special feature that is the ability to re-position. Disadvantages of CSS: In CSS, there is a cross browsers issue if you design anything and check on chrome it looks perfect but that does not mean it will look the same in the other browsers. Then you have to add the script for that browser also. There is a lack of security in CSS. CSS is vulnerable, it is exposed to possibly being attacked. CSS has a fragmentation issue. CSS-Basics CSS-Misc CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27679, "s": 27651, "text": "\n20 Dec, 2019" }, { "code": null, "e": 28271, "s": 27679, "text": "CSS stands for Cascading Style Sheet, it is a style sheet language used to shape the HTML elements that will be displayed in the browsers as a web-page. Without using CSS, the website which has been created by using HTML, will look dull. Basically CSS gives the outer cover on any HTML elements. If you consider HTML as a skeleton of the web-page then the CSS will be the skin of the skeleton. The Internet media type (MIME type) of CSS is text/CSS. The CSS was developed by the World Wide Web Consortium (W3C) in the year of 1996. The CSS can be applied to HTML documents in different ways." }, { "code": null, "e": 28368, "s": 28271, "text": "The inline CSS style that will look like below code:<h1 style=\"color: green;\">GeeksforGeeks</h1>" }, { "code": null, "e": 28413, "s": 28368, "text": "<h1 style=\"color: green;\">GeeksforGeeks</h1>" }, { "code": null, "e": 28663, "s": 28413, "text": "The internal CSS style that will look like below code:<!DOCTYPE html>\n<html>\n <head>\n <title> internal CSS </title>\n <style>\n h1 {\n color: green;\n } \n </style>\n <head>\n <body>\n <h1\">GeeksforGeeks</h1>\n </body>\n</html>\n" }, { "code": null, "e": 28859, "s": 28663, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> internal CSS </title>\n <style>\n h1 {\n color: green;\n } \n </style>\n <head>\n <body>\n <h1\">GeeksforGeeks</h1>\n </body>\n</html>\n" }, { "code": null, "e": 28987, "s": 28859, "text": "The external CSS style that will look like below code:/* this will be separate file */\n<style>\nh1 {\n color: green;\n}\n</style>" }, { "code": null, "e": 29061, "s": 28987, "text": "/* this will be separate file */\n<style>\nh1 {\n color: green;\n}\n</style>" }, { "code": null, "e": 29087, "s": 29061, "text": "CSS version release year:" }, { "code": null, "e": 29111, "s": 29087, "text": "Characteristics of CSS:" }, { "code": null, "e": 29254, "s": 29111, "text": "Maintenance: It is easy to maintain, changing in a single place will affect globally in your web site. No need to change every specific place." }, { "code": null, "e": 29328, "s": 29254, "text": "Time-saving: You can easily use any single CSS script at multiple places." }, { "code": null, "e": 29394, "s": 29328, "text": "Support: CSS is supported by all the browsers and search engines." }, { "code": null, "e": 29529, "s": 29394, "text": "Cache storing: CSS can store web applications locally with the help of offline cache so you can see the web site when you are offline." }, { "code": null, "e": 29640, "s": 29529, "text": "Native front-end: CSS contains a huge list of attributes and function that is helpful to design the HTML page." }, { "code": null, "e": 29773, "s": 29640, "text": "Selectors: In CSS, there are lots of selectors (ID selectors, Class Selectors, etc.) that will be helpful to perform specific tasks." }, { "code": null, "e": 29792, "s": 29773, "text": "Advantages of CSS:" }, { "code": null, "e": 29832, "s": 29792, "text": "CSS is compatible with all the devices." }, { "code": null, "e": 29894, "s": 29832, "text": "With the help of CSS, website maintenance is easy and faster." }, { "code": null, "e": 29942, "s": 29894, "text": "CSS support consistent and spontaneous changes." }, { "code": null, "e": 30033, "s": 29942, "text": "CSS make the website faster and enhances search engine capabilities to crawl the web pages" }, { "code": null, "e": 30096, "s": 30033, "text": "It holds a special feature that is the ability to re-position." }, { "code": null, "e": 30118, "s": 30096, "text": "Disadvantages of CSS:" }, { "code": null, "e": 30341, "s": 30118, "text": "In CSS, there is a cross browsers issue if you design anything and check on chrome it looks perfect but that does not mean it will look the same in the other browsers. Then you have to add the script for that browser also." }, { "code": null, "e": 30377, "s": 30341, "text": "There is a lack of security in CSS." }, { "code": null, "e": 30438, "s": 30377, "text": "CSS is vulnerable, it is exposed to possibly being attacked." }, { "code": null, "e": 30469, "s": 30438, "text": "CSS has a fragmentation issue." }, { "code": null, "e": 30480, "s": 30469, "text": "CSS-Basics" }, { "code": null, "e": 30489, "s": 30480, "text": "CSS-Misc" }, { "code": null, "e": 30493, "s": 30489, "text": "CSS" }, { "code": null, "e": 30510, "s": 30493, "text": "Web Technologies" }, { "code": null, "e": 30537, "s": 30510, "text": "Web technologies Questions" }, { "code": null, "e": 30635, "s": 30537, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30644, "s": 30635, "text": "Comments" }, { "code": null, "e": 30657, "s": 30644, "text": "Old Comments" }, { "code": null, "e": 30719, "s": 30657, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30769, "s": 30719, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30827, "s": 30769, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 30875, "s": 30827, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30912, "s": 30875, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30968, "s": 30912, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31001, "s": 30968, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31063, "s": 31001, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31106, "s": 31063, "text": "How to fetch data from an API in ReactJS ?" } ]
String Interpolation in JavaScript
11 May, 2020 String interpolation is a great programming language feature that allows injecting variables, function calls, arithmetic expressions directly into a string. String interpolation was absent in JavaScript before ES6. String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well. These are some of the reasons to use string interpolation over string concatenation. Let’s see the difference between string concatenation and string interpolation. <script> // String Concatenationfunction myInfo(fname, lname, country) { return "My name is " + fname + " " + lname + ". " + country + " is my favorite country."; }console.log(myInfo("john", "doe", "India"));</script> Output: My name is john doe. India is my favorite country In string concatenation, it is hard to maintain string as they grow large it becomes tedious and complex. In order to make it readable, the developer has to maintain all the whitespaces. This is where ES6 comes to rescue with String interpolation. In JavaScript, the template literals (strings wrapped in backticks ` `) and ${expression} as placeholders perform the string interpolation. Now we can write above myInfo function with string interpolation. <script> // String Interpolationfunction myInfo(fname, lname, country) { return `My name is ${fname} ${lname}. ${country} is my favorite country`; }console.log(myInfo("john", "doe", "India"));</script> Output: My name is john doe. India is my favorite country We can see that the code is small and easily readable as compared to concatenation. The template string supports placeholders. The expression like variables, function call, arithmetic can be placed inside the placeholder. These expressions are evaluated at runtime and output is inserted in the string. <script> // DEclare and initialize variablesconst x = "GeeksforGeeks"; // I like GeeksforGeeksconsole.log(`I like ${x}.`); // Function callfunction greet() { return "hello!";} // hello! I am a student.console.log(`${greet()} I am a student.`); // Expression evolution//sum of 5 and 6 is 11. console.log(`sum of 5 and 6 is ${5+6}.`); </script> Output: I like GeeksforGeeks hello! I am a student. sum of 5 and 6 is 11. We can also use conditional statements in expression. For example: <script> function isEven(x) { console.log(`x is ${x%2 === 0 ? 'even' : 'odd'}`);} isEven(4); // x is even</script> Output: x is even The string interpolation is a great feature. It helps in inserting values into string literals. It makes code more readable and avoids clumsiness. JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2020" }, { "code": null, "e": 592, "s": 52, "text": "String interpolation is a great programming language feature that allows injecting variables, function calls, arithmetic expressions directly into a string. String interpolation was absent in JavaScript before ES6. String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well. These are some of the reasons to use string interpolation over string concatenation." }, { "code": null, "e": 672, "s": 592, "text": "Let’s see the difference between string concatenation and string interpolation." }, { "code": "<script> // String Concatenationfunction myInfo(fname, lname, country) { return \"My name is \" + fname + \" \" + lname + \". \" + country + \" is my favorite country.\"; }console.log(myInfo(\"john\", \"doe\", \"India\"));</script>", "e": 908, "s": 672, "text": null }, { "code": null, "e": 916, "s": 908, "text": "Output:" }, { "code": null, "e": 966, "s": 916, "text": "My name is john doe. India is my favorite country" }, { "code": null, "e": 1420, "s": 966, "text": "In string concatenation, it is hard to maintain string as they grow large it becomes tedious and complex. In order to make it readable, the developer has to maintain all the whitespaces. This is where ES6 comes to rescue with String interpolation. In JavaScript, the template literals (strings wrapped in backticks ` `) and ${expression} as placeholders perform the string interpolation. Now we can write above myInfo function with string interpolation." }, { "code": "<script> // String Interpolationfunction myInfo(fname, lname, country) { return `My name is ${fname} ${lname}. ${country} is my favorite country`; }console.log(myInfo(\"john\", \"doe\", \"India\"));</script>", "e": 1626, "s": 1420, "text": null }, { "code": null, "e": 1634, "s": 1626, "text": "Output:" }, { "code": null, "e": 1684, "s": 1634, "text": "My name is john doe. India is my favorite country" }, { "code": null, "e": 1987, "s": 1684, "text": "We can see that the code is small and easily readable as compared to concatenation. The template string supports placeholders. The expression like variables, function call, arithmetic can be placed inside the placeholder. These expressions are evaluated at runtime and output is inserted in the string." }, { "code": "<script> // DEclare and initialize variablesconst x = \"GeeksforGeeks\"; // I like GeeksforGeeksconsole.log(`I like ${x}.`); // Function callfunction greet() { return \"hello!\";} // hello! I am a student.console.log(`${greet()} I am a student.`); // Expression evolution//sum of 5 and 6 is 11. console.log(`sum of 5 and 6 is ${5+6}.`); </script>", "e": 2340, "s": 1987, "text": null }, { "code": null, "e": 2348, "s": 2340, "text": "Output:" }, { "code": null, "e": 2415, "s": 2348, "text": "I like GeeksforGeeks\nhello! I am a student.\nsum of 5 and 6 is 11.\n" }, { "code": null, "e": 2482, "s": 2415, "text": "We can also use conditional statements in expression. For example:" }, { "code": "<script> function isEven(x) { console.log(`x is ${x%2 === 0 ? 'even' : 'odd'}`);} isEven(4); // x is even</script>", "e": 2602, "s": 2482, "text": null }, { "code": null, "e": 2610, "s": 2602, "text": "Output:" }, { "code": null, "e": 2620, "s": 2610, "text": "x is even" }, { "code": null, "e": 2767, "s": 2620, "text": "The string interpolation is a great feature. It helps in inserting values into string literals. It makes code more readable and avoids clumsiness." }, { "code": null, "e": 2783, "s": 2767, "text": "JavaScript-Misc" }, { "code": null, "e": 2790, "s": 2783, "text": "Picked" }, { "code": null, "e": 2801, "s": 2790, "text": "JavaScript" }, { "code": null, "e": 2818, "s": 2801, "text": "Web Technologies" }, { "code": null, "e": 2845, "s": 2818, "text": "Web technologies Questions" } ]
Python – Join Tuples to Integers in Tuple List
02 Jun, 2020 Sometimes, while working with Python records, we can have a problem in which we need to concatenate all the elements, in order, to convert elements in tuples in List to integer. This kind of problem can have applications in many domains such as day-day and competitive programming. Let’s discuss certain ways in which this task can be performed. Input : test_list = [(4, 5, 6), (5, 1), (1, 3, 8, 0), (6, 9)]Output : [456, 51, 1380, 69] Input : test_list = [(4, 5, 6, 8, 9)]Output : [45689] Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we perform join of all the elements using number creation mathematically compute the result. # Python3 code to demonstrate working of # Join Tuples to Integers in Tuple List# Using loop # helpr_fncdef join_tup(tup): res = tup[0] for idx in tup[1:]: res = res * 10 + idx return res # initializing listtest_list = [(4, 5), (5, 6), (1, 3), (6, 9)] # printing original listprint("The original list is : " + str(test_list)) # Join Tuples to Integers in Tuple List# Using loopres = [join_tup(idx) for idx in test_list] # printing result print("The joined result : " + str(res)) The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)] The joined result : [45, 56, 13, 69] Method #2 : Using map() + join() + int()The combination of above functions can be used to solve the problem. In this, we perform concatenation by string conversion, joining using join() and int() is used to convert result back to integer. # Python3 code to demonstrate working of # Join Tuples to Integers in Tuple List# Using map() + join() + int() # initializing listtest_list = [(4, 5), (5, 6), (1, 3), (6, 9)] # printing original listprint("The original list is : " + str(test_list)) # Join Tuples to Integers in Tuple List# Using map() + join() + int()res = [int(''.join(map(str, idx))) for idx in test_list] # printing result print("The joined result : " + str(res)) The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)] The joined result : [45, 56, 13, 69] Python List-of-Tuples Python list-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 OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2020" }, { "code": null, "e": 374, "s": 28, "text": "Sometimes, while working with Python records, we can have a problem in which we need to concatenate all the elements, in order, to convert elements in tuples in List to integer. This kind of problem can have applications in many domains such as day-day and competitive programming. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 464, "s": 374, "text": "Input : test_list = [(4, 5, 6), (5, 1), (1, 3, 8, 0), (6, 9)]Output : [456, 51, 1380, 69]" }, { "code": null, "e": 518, "s": 464, "text": "Input : test_list = [(4, 5, 6, 8, 9)]Output : [45689]" }, { "code": null, "e": 706, "s": 518, "text": "Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we perform join of all the elements using number creation mathematically compute the result." }, { "code": "# Python3 code to demonstrate working of # Join Tuples to Integers in Tuple List# Using loop # helpr_fncdef join_tup(tup): res = tup[0] for idx in tup[1:]: res = res * 10 + idx return res # initializing listtest_list = [(4, 5), (5, 6), (1, 3), (6, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Join Tuples to Integers in Tuple List# Using loopres = [join_tup(idx) for idx in test_list] # printing result print(\"The joined result : \" + str(res)) ", "e": 1207, "s": 706, "text": null }, { "code": null, "e": 1301, "s": 1207, "text": "The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]\nThe joined result : [45, 56, 13, 69]\n" }, { "code": null, "e": 1542, "s": 1303, "text": "Method #2 : Using map() + join() + int()The combination of above functions can be used to solve the problem. In this, we perform concatenation by string conversion, joining using join() and int() is used to convert result back to integer." }, { "code": "# Python3 code to demonstrate working of # Join Tuples to Integers in Tuple List# Using map() + join() + int() # initializing listtest_list = [(4, 5), (5, 6), (1, 3), (6, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Join Tuples to Integers in Tuple List# Using map() + join() + int()res = [int(''.join(map(str, idx))) for idx in test_list] # printing result print(\"The joined result : \" + str(res)) ", "e": 1981, "s": 1542, "text": null }, { "code": null, "e": 2075, "s": 1981, "text": "The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]\nThe joined result : [45, 56, 13, 69]\n" }, { "code": null, "e": 2097, "s": 2075, "text": "Python List-of-Tuples" }, { "code": null, "e": 2118, "s": 2097, "text": "Python list-programs" }, { "code": null, "e": 2125, "s": 2118, "text": "Python" }, { "code": null, "e": 2141, "s": 2125, "text": "Python Programs" }, { "code": null, "e": 2239, "s": 2141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2271, "s": 2239, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2298, "s": 2271, "text": "Python Classes and Objects" }, { "code": null, "e": 2319, "s": 2298, "text": "Python OOPs Concepts" }, { "code": null, "e": 2342, "s": 2319, "text": "Introduction To PYTHON" }, { "code": null, "e": 2398, "s": 2342, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2420, "s": 2398, "text": "Defaultdict in Python" }, { "code": null, "e": 2459, "s": 2420, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2497, "s": 2459, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2546, "s": 2497, "text": "Python | Convert string dictionary to dictionary" } ]
Optimum way to compare strings in JavaScript
12 Dec, 2021 In this article, we will know the optimal way to compare the strings using build-in Javascript methods & will see their implementation through the examples. The question is to compare 2 JavaScript strings optimally. To do so, here are a few of the most used techniques discussed. The method discussed below is used in the following examples. String localeCompare() method: This method compares two strings in the current locale. The current locale is based on the language settings of the browser. This method returns a number that tells whether the string comes before, after, or is equal to the compareString in sort order. Syntax: string.localeCompare(String_2); Parameters: String_2: This required parameter specifies the string to be compared with. Please refer to the JavaScript Operators Complete Reference article for further details of operators. Example 1: This example compares the 2 string using localeCompare() method and returns 0, -1 or 1. This method does case-sensitive comparing. HTML <!DOCTYPE html><html> <head> <title>JavaScript Optimum way to compare strings</title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> String_1: <input type="text" id="text1" name="tname1"> <br> <br> String_2: <input type="text" id="text2" name="tname2"> <br> <br> <button onclick="gfg_Run()"> Compare </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var str1 = document.getElementById("text1"); var str2 = document.getElementById("text2"); var el_down = document.getElementById("GFG_DOWN"); function gfg_Run() { var a = str1.value; var b = str2.value; var ans = a.localeCompare(b); var res = ""; if(ans == -1) { res = '"' + a + '" comes before "' + b + '"'; } else if(ans == 0) { res = 'Both string are same'; } else { res = '"' + a + '" comes after "' + b + '"'; } el_down.innerHTML = res; } </script></body> </html> Output: localeCompare() Method Example 2: This example compares the 2 string by writing a condition which returns 0, -1, or 1 depending on the comparison. This method also does case-sensitive comparing. HTML <!DOCTYPE html><html> <head> <title>JavaScript Optimum way to compare strings</title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> String_1: <input type="text" id="text1" name="tname1"> <br> <br> String_2: <input type="text" id="text2" name="tname2"> <br> <br> <button onclick="gfg_Run()">Compare</button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var str1 = document.getElementById("text1"); var str2 = document.getElementById("text2"); var el_down = document.getElementById("GFG_DOWN"); function gfg_Run() { var a = str1.value; var b = str2.value; var ans = a < b ? -1 : (a > b ? 1 : 0); var res = ""; if(ans == -1) { res = '"' + a + '" comes before "' + b + '"'; } else if(ans == 0) { res = 'Both string are same'; } else { res = '"' + a + '" comes after "' + b + '"'; } el_down.innerHTML = res; } </script></body> </html> Output: string comparison Example 3: This example compares the 2 same strings (case-sensitive also) by using the localeCompare() method. HTML <!DOCTYPE html><html> <head> <title>JavaScript Optimum way to compare strings</title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> String_1: <input type="text" id="text1" name="tname1"> <br> <br> String_2: <input type="text" id="text2" name="tname2"> <br> <br> <button onclick="gfg_Run()"> Compare </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var str1 = document.getElementById("text1"); var str2 = document.getElementById("text2"); var el_down = document.getElementById("GFG_DOWN"); function gfg_Run() { var a = str1.value; var b = str2.value; var ans = a.localeCompare(b); var res = ""; if(ans == -1) { res = '"' + a + '" comes before "' + b + '"'; } else if(ans == 0) { res = 'Both string are same'; } else { res = '"' + a + '" comes after "' + b + '"'; } el_down.innerHTML = res; } </script></body> </html> Output: localeCompareMethod for string comparison bhaskargeeksforgeeks simranarora5sos JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2021" }, { "code": null, "e": 395, "s": 52, "text": "In this article, we will know the optimal way to compare the strings using build-in Javascript methods & will see their implementation through the examples. The question is to compare 2 JavaScript strings optimally. To do so, here are a few of the most used techniques discussed. The method discussed below is used in the following examples. " }, { "code": null, "e": 679, "s": 395, "text": "String localeCompare() method: This method compares two strings in the current locale. The current locale is based on the language settings of the browser. This method returns a number that tells whether the string comes before, after, or is equal to the compareString in sort order." }, { "code": null, "e": 687, "s": 679, "text": "Syntax:" }, { "code": null, "e": 719, "s": 687, "text": "string.localeCompare(String_2);" }, { "code": null, "e": 731, "s": 719, "text": "Parameters:" }, { "code": null, "e": 807, "s": 731, "text": "String_2: This required parameter specifies the string to be compared with." }, { "code": null, "e": 909, "s": 807, "text": "Please refer to the JavaScript Operators Complete Reference article for further details of operators." }, { "code": null, "e": 1051, "s": 909, "text": "Example 1: This example compares the 2 string using localeCompare() method and returns 0, -1 or 1. This method does case-sensitive comparing." }, { "code": null, "e": 1056, "s": 1051, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>JavaScript Optimum way to compare strings</title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> String_1: <input type=\"text\" id=\"text1\" name=\"tname1\"> <br> <br> String_2: <input type=\"text\" id=\"text2\" name=\"tname2\"> <br> <br> <button onclick=\"gfg_Run()\"> Compare </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var str1 = document.getElementById(\"text1\"); var str2 = document.getElementById(\"text2\"); var el_down = document.getElementById(\"GFG_DOWN\"); function gfg_Run() { var a = str1.value; var b = str2.value; var ans = a.localeCompare(b); var res = \"\"; if(ans == -1) { res = '\"' + a + '\" comes before \"' + b + '\"'; } else if(ans == 0) { res = 'Both string are same'; } else { res = '\"' + a + '\" comes after \"' + b + '\"'; } el_down.innerHTML = res; } </script></body> </html>", "e": 2241, "s": 1056, "text": null }, { "code": null, "e": 2249, "s": 2241, "text": "Output:" }, { "code": null, "e": 2272, "s": 2249, "text": "localeCompare() Method" }, { "code": null, "e": 2444, "s": 2272, "text": "Example 2: This example compares the 2 string by writing a condition which returns 0, -1, or 1 depending on the comparison. This method also does case-sensitive comparing." }, { "code": null, "e": 2449, "s": 2444, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>JavaScript Optimum way to compare strings</title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> String_1: <input type=\"text\" id=\"text1\" name=\"tname1\"> <br> <br> String_2: <input type=\"text\" id=\"text2\" name=\"tname2\"> <br> <br> <button onclick=\"gfg_Run()\">Compare</button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var str1 = document.getElementById(\"text1\"); var str2 = document.getElementById(\"text2\"); var el_down = document.getElementById(\"GFG_DOWN\"); function gfg_Run() { var a = str1.value; var b = str2.value; var ans = a < b ? -1 : (a > b ? 1 : 0); var res = \"\"; if(ans == -1) { res = '\"' + a + '\" comes before \"' + b + '\"'; } else if(ans == 0) { res = 'Both string are same'; } else { res = '\"' + a + '\" comes after \"' + b + '\"'; } el_down.innerHTML = res; } </script></body> </html>", "e": 3642, "s": 2449, "text": null }, { "code": null, "e": 3651, "s": 3642, "text": "Output: " }, { "code": null, "e": 3669, "s": 3651, "text": "string comparison" }, { "code": null, "e": 3780, "s": 3669, "text": "Example 3: This example compares the 2 same strings (case-sensitive also) by using the localeCompare() method." }, { "code": null, "e": 3785, "s": 3780, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>JavaScript Optimum way to compare strings</title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> String_1: <input type=\"text\" id=\"text1\" name=\"tname1\"> <br> <br> String_2: <input type=\"text\" id=\"text2\" name=\"tname2\"> <br> <br> <button onclick=\"gfg_Run()\"> Compare </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var str1 = document.getElementById(\"text1\"); var str2 = document.getElementById(\"text2\"); var el_down = document.getElementById(\"GFG_DOWN\"); function gfg_Run() { var a = str1.value; var b = str2.value; var ans = a.localeCompare(b); var res = \"\"; if(ans == -1) { res = '\"' + a + '\" comes before \"' + b + '\"'; } else if(ans == 0) { res = 'Both string are same'; } else { res = '\"' + a + '\" comes after \"' + b + '\"'; } el_down.innerHTML = res; } </script></body> </html>", "e": 4908, "s": 3785, "text": null }, { "code": null, "e": 4916, "s": 4908, "text": "Output:" }, { "code": null, "e": 4958, "s": 4916, "text": "localeCompareMethod for string comparison" }, { "code": null, "e": 4979, "s": 4958, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 4995, "s": 4979, "text": "simranarora5sos" }, { "code": null, "e": 5016, "s": 4995, "text": "JavaScript-Questions" }, { "code": null, "e": 5027, "s": 5016, "text": "JavaScript" }, { "code": null, "e": 5044, "s": 5027, "text": "Web Technologies" }, { "code": null, "e": 5142, "s": 5044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5203, "s": 5142, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5275, "s": 5203, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5315, "s": 5275, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5368, "s": 5315, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5409, "s": 5368, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5442, "s": 5409, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5504, "s": 5442, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5565, "s": 5504, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5615, "s": 5565, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Get Nth word in given String
29 Nov, 2019 Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loopThis is one way in which this problem can be solved. In this, we run a loop and check for spaces. The Nth word is when there is N-1th space. We return that word. # Python3 code to demonstrate working of# Get Nth word in String# using loop # initializing string test_str = "GFG is for Geeks" # printing original string print("The original string is : " + test_str) # initializing N N = 3 # Get Nth word in String# using loopcount = 0res = ""for ele in test_str: if ele == ' ': count = count + 1 if count == N: break res = "" else : res = res + ele # printing resultprint("The Nth word in String : " + res) The original string is : GFG is for Geeks The Nth word in String : for Method #2 : Using split()This is a shorthand with the help of which this problem can be solved. In this, we split the string into a list and then return the Nth occurring element. # Python3 code to demonstrate working of# Get Nth word in String# using split() # initializing string test_str = "GFG is for Geeks" # printing original string print("The original string is : " + test_str) # initializing N N = 3 # Get Nth word in String# using split()res = test_str.split(' ')[N-1] # printing resultprint("The Nth word in String : " + res) The original string is : GFG is for Geeks The Nth word in String : for Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Nov, 2019" }, { "code": null, "e": 303, "s": 54, "text": "Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 487, "s": 303, "text": "Method #1 : Using loopThis is one way in which this problem can be solved. In this, we run a loop and check for spaces. The Nth word is when there is N-1th space. We return that word." }, { "code": "# Python3 code to demonstrate working of# Get Nth word in String# using loop # initializing string test_str = \"GFG is for Geeks\" # printing original string print(\"The original string is : \" + test_str) # initializing N N = 3 # Get Nth word in String# using loopcount = 0res = \"\"for ele in test_str: if ele == ' ': count = count + 1 if count == N: break res = \"\" else : res = res + ele # printing resultprint(\"The Nth word in String : \" + res)", "e": 980, "s": 487, "text": null }, { "code": null, "e": 1052, "s": 980, "text": "The original string is : GFG is for Geeks\nThe Nth word in String : for\n" }, { "code": null, "e": 1234, "s": 1054, "text": "Method #2 : Using split()This is a shorthand with the help of which this problem can be solved. In this, we split the string into a list and then return the Nth occurring element." }, { "code": "# Python3 code to demonstrate working of# Get Nth word in String# using split() # initializing string test_str = \"GFG is for Geeks\" # printing original string print(\"The original string is : \" + test_str) # initializing N N = 3 # Get Nth word in String# using split()res = test_str.split(' ')[N-1] # printing resultprint(\"The Nth word in String : \" + res)", "e": 1595, "s": 1234, "text": null }, { "code": null, "e": 1667, "s": 1595, "text": "The original string is : GFG is for Geeks\nThe Nth word in String : for\n" }, { "code": null, "e": 1690, "s": 1667, "text": "Python string-programs" }, { "code": null, "e": 1697, "s": 1690, "text": "Python" }, { "code": null, "e": 1713, "s": 1697, "text": "Python Programs" }, { "code": null, "e": 1811, "s": 1713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1829, "s": 1811, "text": "Python Dictionary" }, { "code": null, "e": 1871, "s": 1829, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1893, "s": 1871, "text": "Enumerate() in Python" }, { "code": null, "e": 1928, "s": 1893, "text": "Read a file line by line in Python" }, { "code": null, "e": 1960, "s": 1928, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2003, "s": 1960, "text": "Python program to convert a list to string" }, { "code": null, "e": 2025, "s": 2003, "text": "Defaultdict in Python" }, { "code": null, "e": 2064, "s": 2025, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2102, "s": 2064, "text": "Python | Convert a list to dictionary" } ]
Creating your first application using Kivy
10 Dec, 2021 Prerequisites: Introduction to Kivy, Hello World in Kivy Kivymd is graphical user interface library in python based on kivy that allows you to develop multi-platform applications on Windows, MacOS, Android, iOS, Linux, and Raspberry Pi. The best thing about kivy is, it performs better than HTML5 cross-platform alternatives. Kivymd requires fewer lines of code compare to kivy. Kivymd is written in python using the kivy library. In order to start KivyMD, you must first install the Kivy framework on your computer. Once you have installed Kivy, you can install KivyMD. pip install kivymd If you want to install the development version from the master branch, you should specify a link to zip archive: pip install https://github.com/kivymd/KivyMD/archive/master.zip MDFloatingActionButton: To change MDFloatingActionButton background, use the md_bg_color parameter: MDFloatingActionButton: icon: "android" md_bg_color: app.theme_cls.primary_color The length of the shadow is controlled by the elevation_normal parameter: MDFloatingActionButton: icon: "android" elevation_normal: 12 MDFlatButton: To change the text colour of class MDFlatButton use the text_color parameter: MDFlatButton: text: "MDFLATBUTTON" text_color: 0, 0, 1, 1 There are three steps of creating an application with kivymd- Inherit Kivymd’s App class which represents the window for our widgets Create build() method, which will show the content of the widgets. And at last calling of run() method. Code blocks: text: the text you want to show on screen. halign: alignment of that text. pos_hint: position from the text from the left and top (center_x =0.5 and center_y=0.5 represents the centre. of the screen). icon: The type of icon you have to give for your button. Below is the example of how we can create a simple application using kivy: Python3 # import required modulesfrom kivymd.app import MDAppfrom kivymd.uix.button import MDFloatingActionButton, MDFlatButtonfrom kivymd.uix.screen import Screenfrom kivymd.icon_definitions import md_icons class DemoApp(MDApp): def build(self): # create screen object screen = Screen() # create buttons btn1 = MDFlatButton(text='Hello GFG', pos_hint={'center_x': 0.5, 'center_y': 0.8}) btn = MDFloatingActionButton(icon="android", pos_hint={'center_x': 0.5, 'center_y': 0.5}, ) # add buttons screen.add_widget(btn1) screen.add_widget(btn) return screen # run applicationDemoApp().run() Output: rkbhola5 Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2021" }, { "code": null, "e": 85, "s": 28, "text": "Prerequisites: Introduction to Kivy, Hello World in Kivy" }, { "code": null, "e": 459, "s": 85, "text": "Kivymd is graphical user interface library in python based on kivy that allows you to develop multi-platform applications on Windows, MacOS, Android, iOS, Linux, and Raspberry Pi. The best thing about kivy is, it performs better than HTML5 cross-platform alternatives. Kivymd requires fewer lines of code compare to kivy. Kivymd is written in python using the kivy library." }, { "code": null, "e": 599, "s": 459, "text": "In order to start KivyMD, you must first install the Kivy framework on your computer. Once you have installed Kivy, you can install KivyMD." }, { "code": null, "e": 618, "s": 599, "text": "pip install kivymd" }, { "code": null, "e": 731, "s": 618, "text": "If you want to install the development version from the master branch, you should specify a link to zip archive:" }, { "code": null, "e": 795, "s": 731, "text": "pip install https://github.com/kivymd/KivyMD/archive/master.zip" }, { "code": null, "e": 820, "s": 795, "text": "MDFloatingActionButton: " }, { "code": null, "e": 896, "s": 820, "text": "To change MDFloatingActionButton background, use the md_bg_color parameter:" }, { "code": null, "e": 983, "s": 896, "text": "MDFloatingActionButton:\n icon: \"android\"\n md_bg_color: app.theme_cls.primary_color" }, { "code": null, "e": 1057, "s": 983, "text": "The length of the shadow is controlled by the elevation_normal parameter:" }, { "code": null, "e": 1126, "s": 1057, "text": "MDFloatingActionButton:\n icon: \"android\"\n elevation_normal: 12" }, { "code": null, "e": 1140, "s": 1126, "text": "MDFlatButton:" }, { "code": null, "e": 1218, "s": 1140, "text": "To change the text colour of class MDFlatButton use the text_color parameter:" }, { "code": null, "e": 1282, "s": 1218, "text": "MDFlatButton:\n text: \"MDFLATBUTTON\"\n text_color: 0, 0, 1, 1" }, { "code": null, "e": 1344, "s": 1282, "text": "There are three steps of creating an application with kivymd-" }, { "code": null, "e": 1415, "s": 1344, "text": "Inherit Kivymd’s App class which represents the window for our widgets" }, { "code": null, "e": 1482, "s": 1415, "text": "Create build() method, which will show the content of the widgets." }, { "code": null, "e": 1519, "s": 1482, "text": "And at last calling of run() method." }, { "code": null, "e": 1532, "s": 1519, "text": "Code blocks:" }, { "code": null, "e": 1575, "s": 1532, "text": "text: the text you want to show on screen." }, { "code": null, "e": 1607, "s": 1575, "text": "halign: alignment of that text." }, { "code": null, "e": 1733, "s": 1607, "text": "pos_hint: position from the text from the left and top (center_x =0.5 and center_y=0.5 represents the centre. of the screen)." }, { "code": null, "e": 1790, "s": 1733, "text": "icon: The type of icon you have to give for your button." }, { "code": null, "e": 1865, "s": 1790, "text": "Below is the example of how we can create a simple application using kivy:" }, { "code": null, "e": 1873, "s": 1865, "text": "Python3" }, { "code": "# import required modulesfrom kivymd.app import MDAppfrom kivymd.uix.button import MDFloatingActionButton, MDFlatButtonfrom kivymd.uix.screen import Screenfrom kivymd.icon_definitions import md_icons class DemoApp(MDApp): def build(self): # create screen object screen = Screen() # create buttons btn1 = MDFlatButton(text='Hello GFG', pos_hint={'center_x': 0.5, 'center_y': 0.8}) btn = MDFloatingActionButton(icon=\"android\", pos_hint={'center_x': 0.5, 'center_y': 0.5}, ) # add buttons screen.add_widget(btn1) screen.add_widget(btn) return screen # run applicationDemoApp().run()", "e": 2736, "s": 1873, "text": null }, { "code": null, "e": 2744, "s": 2736, "text": "Output:" }, { "code": null, "e": 2753, "s": 2744, "text": "rkbhola5" }, { "code": null, "e": 2765, "s": 2753, "text": "Python-kivy" }, { "code": null, "e": 2772, "s": 2765, "text": "Python" }, { "code": null, "e": 2870, "s": 2772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2902, "s": 2870, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2929, "s": 2902, "text": "Python Classes and Objects" }, { "code": null, "e": 2960, "s": 2929, "text": "Python | os.path.join() method" }, { "code": null, "e": 2981, "s": 2960, "text": "Python OOPs Concepts" }, { "code": null, "e": 3037, "s": 2981, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3060, "s": 3037, "text": "Introduction To PYTHON" }, { "code": null, "e": 3102, "s": 3060, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3144, "s": 3102, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3183, "s": 3144, "text": "Python | datetime.timedelta() function" } ]
Place K-knights such that they do not attack each other
16 Jun, 2022 Given integers M, N and K, the task is to place K knights on an M*N chessboard such that they don’t attack each other. The knights are expected to be placed on different squares on the board. A knight can move two squares vertically and one square horizontally or two squares horizontally and one square vertically. The knights attack each other if one of them can reach the other in single move. There are multiple ways of placing K knights on an M*N board or sometimes, no way of placing them. We are expected to list out all the possible solutions. Examples: Input: M = 3, N = 3, K = 5 Output: K A K A K A K A K A K A K K K A K A Total number of solutions : 2 Input: M = 5, N = 5, K = 13 Output: K A K A K A K A K A K A K A K A K A K A K A K A K Total number of solutions : 1 Approach: This problem can be solved using backtracking. The idea is to place the knights one by one starting from first row and first column and moving forward to first row and second column such that they don’t attack each other. When one row gets over, we move to the next row. Before placing a knight, we always check if the block is safe i.e. it is not an attacking position of some other knight. If it is safe, we place the knight and mark it’s attacking position on the board else we move forward and check for other blocks. While following this procedure, we make a new board every time we insert a new knight into our board. This is done because if we get one solution and we need other solutions, then we can backtrack to our old board with old configuration of knights which can then be checked for other possible solutions. The process of backtracking is continued till we get all our possible solutions. Below is the implementation of the above approach: CPP Java // C++ implementation of the above approach#include <iostream>using namespace std; /* m*n is the board dimensionk is the number of knights to be placed on boardcount is the number of possible solutions */int m, n, k;int count = 0; /* This function is used to create an empty m*n board */void makeBoard(char** board){ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = '_'; } }} /* This function displays our board */void displayBoard(char** board){ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << " " << board[i][j] << " "; } cout << endl; } cout << endl;} /* This function marks all the attackingposition of a knight placed at board[i][j]position */void attack(int i, int j, char a, char** board){ /* conditions to ensure that the block to be checked is inside the board */ if ((i + 2) < m && (j - 1) >= 0) { board[i + 2][j - 1] = a; } if ((i - 2) >= 0 && (j - 1) >= 0) { board[i - 2][j - 1] = a; } if ((i + 2) < m && (j + 1) < n) { board[i + 2][j + 1] = a; } if ((i - 2) >= 0 && (j + 1) < n) { board[i - 2][j + 1] = a; } if ((i + 1) < m && (j + 2) < n) { board[i + 1][j + 2] = a; } if ((i - 1) >= 0 && (j + 2) < n) { board[i - 1][j + 2] = a; } if ((i + 1) < m && (j - 2) >= 0) { board[i + 1][j - 2] = a; } if ((i - 1) >= 0 && (j - 2) >= 0) { board[i - 1][j - 2] = a; }} /* If the position is empty,place the knight */bool canPlace(int i, int j, char** board){ if (board[i][j] == '_') return true; else return false;} /* Place the knight at [i][j] positionon board */void place(int i, int j, char k, char a, char** board, char** new_board){ /* Copy the configurations of old board to new board */ for (int y = 0; y < m; y++) { for (int z = 0; z < n; z++) { new_board[y][z] = board[y][z]; } } /* Place the knight at [i][j] position on new board */ new_board[i][j] = k; /* Mark all the attacking positions of newly placed knight on the new board */ attack(i, j, a, new_board);} /* Function for placing knights on boardsuch that they don't attack each other */void kkn(int k, int sti, int stj, char** board){ /* If there are no knights left to be placed, display the board and increment the count */ if (k == 0) { displayBoard(board); count++; } else { /* Loop for checking all thepositions on m*n board */ for (int i = sti; i < m; i++) { for (int j = stj; j < n; j++) { /* Is it possible to place knight at[i][j] position on board? */ if (canPlace(i, j, board)) { /* Create a new board and place the new knight on it */ char** new_board = new char*[m]; for (int x = 0; x < m; x++) { new_board[x] = new char[n]; } place(i, j, 'K', 'A', board, new_board); /* Call the function recursively for (k-1) leftover knights */ kkn(k - 1, i, j, new_board); /* Delete the new board to free up the memory */ for (int x = 0; x < m; x++) { delete[] new_board[x]; } delete[] new_board; } } stj = 0; } }} // Driver codeint main(){ m = 4, n = 3, k = 6; /* Creation of a m*n board */ char** board = new char*[m]; for (int i = 0; i < m; i++) { board[i] = new char[n]; } /* Make all the places are empty */ makeBoard(board); kkn(k, 0, 0, board); cout << endl << "Total number of solutions : " << count; return 0;} // Java implementation of the above approach class GFG { /* m*n is the board dimension k is the number of knights to be placed on board count is the number of possible solutions */ static int m, n, k; static int count = 0; /* This function is used to create an empty m*n board */ static void makeBoard(char[][] board) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = '_'; } } } /* This function displays our board */ static void displayBoard(char[][] board) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(" " + board[i][j] + " "); } System.out.println(); } System.out.println(); } /* This function marks all the attacking position of a knight placed at board[i][j] position */ static void attack(int i, int j, char a, char[][] board) { /* conditions to ensure that the block to be checked is inside the board */ if ((i + 2) < m && (j - 1) >= 0) { board[i + 2][j - 1] = a; } if ((i - 2) >= 0 && (j - 1) >= 0) { board[i - 2][j - 1] = a; } if ((i + 2) < m && (j + 1) < n) { board[i + 2][j + 1] = a; } if ((i - 2) >= 0 && (j + 1) < n) { board[i - 2][j + 1] = a; } if ((i + 1) < m && (j + 2) < n) { board[i + 1][j + 2] = a; } if ((i - 1) >= 0 && (j + 2) < n) { board[i - 1][j + 2] = a; } if ((i + 1) < m && (j - 2) >= 0) { board[i + 1][j - 2] = a; } if ((i - 1) >= 0 && (j - 2) >= 0) { board[i - 1][j - 2] = a; } } /* If the position is empty, place the knight */ static boolean canPlace(int i, int j, char[][] board) { if (board[i][j] == '_') return true; else return false; } /* Place the knight at [i][j] position on board */ static void place(int i, int j, char k, char a, char[][] board, char[][] new_board) { /* Copy the configurations of old board to new board */ for (int y = 0; y < m; y++) { for (int z = 0; z < n; z++) { new_board[y][z] = board[y][z]; } } /* Place the knight at [i][j] position on new board */ new_board[i][j] = k; /* Mark all the attacking positions of newly placed knight on the new board */ attack(i, j, a, new_board); } /* Function for placing knights on board such that they don't attack each other */ static void kkn(int k, int sti, int stj, char[][] board) { /* If there are no knights left to be placed, display the board and increment the count */ if (k == 0) { displayBoard(board); count++; } else { /* Loop for checking all the positions on m*n board */ for (int i = sti; i < m; i++) { for (int j = stj; j < n; j++) { /* Is it possible to place knight at [i][j] position on board? */ if (canPlace(i, j, board)) { /* Create a new board and place the new knight on it */ char[][] new_board = new char[m][]; for (int x = 0; x < m; x++) { new_board[x] = new char[n]; } place(i, j, 'K', 'A', board, new_board); /* Call the function recursively for (k-1) leftover knights */ kkn(k - 1, i, j, new_board); } } stj = 0; } } } // Driver code public static void main(String[] args) { m = 4; n = 3; k = 6; count = 0; /* Creation of a m*n board */ char[][] board = new char[m][]; for (int i = 0; i < m; i++) { board[i] = new char[n]; } /* Make all the places are empty */ makeBoard(board); kkn(k, 0, 0, board); System.out.println("\n Total number of solutions : " + count); }} // This code is contributed by jainlovely450 K K K A A A A A A K K K K A K A K A K A K A K A A K A K A K A K A K A K Total number of solutions : 3 jainlovely450 simmytarika5 chessboard-problems Technical Scripter 2018 Backtracking Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 605, "s": 52, "text": "Given integers M, N and K, the task is to place K knights on an M*N chessboard such that they don’t attack each other. The knights are expected to be placed on different squares on the board. A knight can move two squares vertically and one square horizontally or two squares horizontally and one square vertically. The knights attack each other if one of them can reach the other in single move. There are multiple ways of placing K knights on an M*N board or sometimes, no way of placing them. We are expected to list out all the possible solutions. " }, { "code": null, "e": 615, "s": 605, "text": "Examples:" }, { "code": null, "e": 718, "s": 615, "text": "Input: M = 3, N = 3, K = 5 Output: K A K A K A K A K A K A K K K A K A Total number of solutions : 2 " }, { "code": null, "e": 834, "s": 718, "text": "Input: M = 5, N = 5, K = 13 Output: K A K A K A K A K A K A K A K A K A K A K A K A K Total number of solutions : 1" }, { "code": null, "e": 1803, "s": 834, "text": "Approach: This problem can be solved using backtracking. The idea is to place the knights one by one starting from first row and first column and moving forward to first row and second column such that they don’t attack each other. When one row gets over, we move to the next row. Before placing a knight, we always check if the block is safe i.e. it is not an attacking position of some other knight. If it is safe, we place the knight and mark it’s attacking position on the board else we move forward and check for other blocks. While following this procedure, we make a new board every time we insert a new knight into our board. This is done because if we get one solution and we need other solutions, then we can backtrack to our old board with old configuration of knights which can then be checked for other possible solutions. The process of backtracking is continued till we get all our possible solutions. Below is the implementation of the above approach: " }, { "code": null, "e": 1807, "s": 1803, "text": "CPP" }, { "code": null, "e": 1812, "s": 1807, "text": "Java" }, { "code": "// C++ implementation of the above approach#include <iostream>using namespace std; /* m*n is the board dimensionk is the number of knights to be placed on boardcount is the number of possible solutions */int m, n, k;int count = 0; /* This function is used to create an empty m*n board */void makeBoard(char** board){ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = '_'; } }} /* This function displays our board */void displayBoard(char** board){ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << \" \" << board[i][j] << \" \"; } cout << endl; } cout << endl;} /* This function marks all the attackingposition of a knight placed at board[i][j]position */void attack(int i, int j, char a, char** board){ /* conditions to ensure that the block to be checked is inside the board */ if ((i + 2) < m && (j - 1) >= 0) { board[i + 2][j - 1] = a; } if ((i - 2) >= 0 && (j - 1) >= 0) { board[i - 2][j - 1] = a; } if ((i + 2) < m && (j + 1) < n) { board[i + 2][j + 1] = a; } if ((i - 2) >= 0 && (j + 1) < n) { board[i - 2][j + 1] = a; } if ((i + 1) < m && (j + 2) < n) { board[i + 1][j + 2] = a; } if ((i - 1) >= 0 && (j + 2) < n) { board[i - 1][j + 2] = a; } if ((i + 1) < m && (j - 2) >= 0) { board[i + 1][j - 2] = a; } if ((i - 1) >= 0 && (j - 2) >= 0) { board[i - 1][j - 2] = a; }} /* If the position is empty,place the knight */bool canPlace(int i, int j, char** board){ if (board[i][j] == '_') return true; else return false;} /* Place the knight at [i][j] positionon board */void place(int i, int j, char k, char a, char** board, char** new_board){ /* Copy the configurations of old board to new board */ for (int y = 0; y < m; y++) { for (int z = 0; z < n; z++) { new_board[y][z] = board[y][z]; } } /* Place the knight at [i][j] position on new board */ new_board[i][j] = k; /* Mark all the attacking positions of newly placed knight on the new board */ attack(i, j, a, new_board);} /* Function for placing knights on boardsuch that they don't attack each other */void kkn(int k, int sti, int stj, char** board){ /* If there are no knights left to be placed, display the board and increment the count */ if (k == 0) { displayBoard(board); count++; } else { /* Loop for checking all thepositions on m*n board */ for (int i = sti; i < m; i++) { for (int j = stj; j < n; j++) { /* Is it possible to place knight at[i][j] position on board? */ if (canPlace(i, j, board)) { /* Create a new board and place the new knight on it */ char** new_board = new char*[m]; for (int x = 0; x < m; x++) { new_board[x] = new char[n]; } place(i, j, 'K', 'A', board, new_board); /* Call the function recursively for (k-1) leftover knights */ kkn(k - 1, i, j, new_board); /* Delete the new board to free up the memory */ for (int x = 0; x < m; x++) { delete[] new_board[x]; } delete[] new_board; } } stj = 0; } }} // Driver codeint main(){ m = 4, n = 3, k = 6; /* Creation of a m*n board */ char** board = new char*[m]; for (int i = 0; i < m; i++) { board[i] = new char[n]; } /* Make all the places are empty */ makeBoard(board); kkn(k, 0, 0, board); cout << endl << \"Total number of solutions : \" << count; return 0;}", "e": 5708, "s": 1812, "text": null }, { "code": "// Java implementation of the above approach class GFG { /* m*n is the board dimension k is the number of knights to be placed on board count is the number of possible solutions */ static int m, n, k; static int count = 0; /* This function is used to create an empty m*n board */ static void makeBoard(char[][] board) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = '_'; } } } /* This function displays our board */ static void displayBoard(char[][] board) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(\" \" + board[i][j] + \" \"); } System.out.println(); } System.out.println(); } /* This function marks all the attacking position of a knight placed at board[i][j] position */ static void attack(int i, int j, char a, char[][] board) { /* conditions to ensure that the block to be checked is inside the board */ if ((i + 2) < m && (j - 1) >= 0) { board[i + 2][j - 1] = a; } if ((i - 2) >= 0 && (j - 1) >= 0) { board[i - 2][j - 1] = a; } if ((i + 2) < m && (j + 1) < n) { board[i + 2][j + 1] = a; } if ((i - 2) >= 0 && (j + 1) < n) { board[i - 2][j + 1] = a; } if ((i + 1) < m && (j + 2) < n) { board[i + 1][j + 2] = a; } if ((i - 1) >= 0 && (j + 2) < n) { board[i - 1][j + 2] = a; } if ((i + 1) < m && (j - 2) >= 0) { board[i + 1][j - 2] = a; } if ((i - 1) >= 0 && (j - 2) >= 0) { board[i - 1][j - 2] = a; } } /* If the position is empty, place the knight */ static boolean canPlace(int i, int j, char[][] board) { if (board[i][j] == '_') return true; else return false; } /* Place the knight at [i][j] position on board */ static void place(int i, int j, char k, char a, char[][] board, char[][] new_board) { /* Copy the configurations of old board to new board */ for (int y = 0; y < m; y++) { for (int z = 0; z < n; z++) { new_board[y][z] = board[y][z]; } } /* Place the knight at [i][j] position on new board */ new_board[i][j] = k; /* Mark all the attacking positions of newly placed knight on the new board */ attack(i, j, a, new_board); } /* Function for placing knights on board such that they don't attack each other */ static void kkn(int k, int sti, int stj, char[][] board) { /* If there are no knights left to be placed, display the board and increment the count */ if (k == 0) { displayBoard(board); count++; } else { /* Loop for checking all the positions on m*n board */ for (int i = sti; i < m; i++) { for (int j = stj; j < n; j++) { /* Is it possible to place knight at [i][j] position on board? */ if (canPlace(i, j, board)) { /* Create a new board and place the new knight on it */ char[][] new_board = new char[m][]; for (int x = 0; x < m; x++) { new_board[x] = new char[n]; } place(i, j, 'K', 'A', board, new_board); /* Call the function recursively for (k-1) leftover knights */ kkn(k - 1, i, j, new_board); } } stj = 0; } } } // Driver code public static void main(String[] args) { m = 4; n = 3; k = 6; count = 0; /* Creation of a m*n board */ char[][] board = new char[m][]; for (int i = 0; i < m; i++) { board[i] = new char[n]; } /* Make all the places are empty */ makeBoard(board); kkn(k, 0, 0, board); System.out.println(\"\\n Total number of solutions : \" + count); }} // This code is contributed by jainlovely450", "e": 10131, "s": 5708, "text": null }, { "code": null, "e": 10285, "s": 10131, "text": " K K K \n A A A \n A A A \n K K K \n\n K A K \n A K A \n K A K \n A K A \n\n A K A \n K A K \n A K A \n K A K \n\n\nTotal number of solutions : 3" }, { "code": null, "e": 10299, "s": 10285, "text": "jainlovely450" }, { "code": null, "e": 10312, "s": 10299, "text": "simmytarika5" }, { "code": null, "e": 10332, "s": 10312, "text": "chessboard-problems" }, { "code": null, "e": 10356, "s": 10332, "text": "Technical Scripter 2018" }, { "code": null, "e": 10369, "s": 10356, "text": "Backtracking" }, { "code": null, "e": 10382, "s": 10369, "text": "Backtracking" } ]
GATE | GATE CS 2010 | Question 65
14 Sep, 2021 The grammar S β†’ aSa | bS | c is(A) LL(1) but not LR(1)(B) LR(1)but not LR(1)(C) Both LL(1)and LR(1)(D) Neither LL(1)nor LR(1)Answer: (C)Explanation: First(aSa) = a First(bS) = b First(c) = c All are mutually disjoint i.e no common terminal between them, the given grammar is LL(1). As the grammar is LL(1) so it will also be LR(1) as LR parsers are more powerful then LL(1) parsers. and all LL(1) grammar are also LR(1) So option C is correct. Below are more details. A grammar is LL(1) if it is possible to choose the next production by looking at only the next token in the input string. Formally, grammar G is LL(1) if and only if For all productions A β†’ Ξ±1 | Ξ±2 | ... | Ξ±n, First(Ξ±i) ∩ First(Ξ±j) = βˆ…, 1 ≀ i,j ≀ n, i =ΜΈ j. For every non-terminal A such that First(A) contains Ξ΅, First(A) ∩ Follow(A) = βˆ… Source: https://s3-ap-southeast-1.amazonaws.com/erbuc/files/4147_870334aa-9922-4f78-9c2c-713e7a7f0d53.pdf PYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K 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.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0011:40 / 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-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 177, "s": 28, "text": "The grammar S β†’ aSa | bS | c is(A) LL(1) but not LR(1)(B) LR(1)but not LR(1)(C) Both LL(1)and LR(1)(D) Neither LL(1)nor LR(1)Answer: (C)Explanation:" }, { "code": null, "e": 475, "s": 177, "text": "First(aSa) = a\nFirst(bS) = b\nFirst(c) = c\nAll are mutually disjoint i.e no common terminal \nbetween them, the given grammar is LL(1).\n\nAs the grammar is LL(1) so it will also be LR(1) as LR parsers are\nmore powerful then LL(1) parsers. and all LL(1) grammar are also LR(1)\nSo option C is correct. " }, { "code": null, "e": 499, "s": 475, "text": "Below are more details." }, { "code": null, "e": 621, "s": 499, "text": "A grammar is LL(1) if it is possible to choose the next production by looking at only the next token in the input string." }, { "code": null, "e": 865, "s": 621, "text": "Formally, grammar G is LL(1) if and only if \n For all productions A β†’ Ξ±1 | Ξ±2 | ... | Ξ±n, \n First(Ξ±i) ∩ First(Ξ±j) = βˆ…, 1 ≀ i,j ≀ n, i =ΜΈ j.\n For every non-terminal A such that First(A) contains Ξ΅, \n First(A) ∩ Follow(A) = βˆ… " }, { "code": null, "e": 971, "s": 865, "text": "Source: https://s3-ap-southeast-1.amazonaws.com/erbuc/files/4147_870334aa-9922-4f78-9c2c-713e7a7f0d53.pdf" }, { "code": null, "e": 1971, "s": 971, "text": "PYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K 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.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0011:40 / 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": 1984, "s": 1971, "text": "GATE-CS-2010" }, { "code": null, "e": 2002, "s": 1984, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 2007, "s": 2002, "text": "GATE" }, { "code": null, "e": 2105, "s": 2007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2147, "s": 2105, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2209, "s": 2147, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2251, "s": 2209, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 2285, "s": 2251, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2327, "s": 2285, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2361, "s": 2327, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 2403, "s": 2361, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2445, "s": 2403, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 2479, "s": 2445, "text": "GATE | GATE CS 1996 | Question 63" } ]
GATE | GATE CS 2019 | Question 50
22 Jul, 2021 Consider the following four processes with arrival times (in milliseconds) and their length of CPU burst (in milliseconds) as shown below:These processes are run on a single processor using preemptive Shortest Remaining Time First scheduling algorithm. If the average waiting time of the processes is 1 millisecond, then the value of Z is __________. Note: This was Numerical Type question.(A) 2(B) 3(C) 1(D) 4Answer: (A)Explanation: Using shortest remaining time (SRTF) first CPU scheduling algorithm, Let Z = 1, then gantt chart will be, Average waiting time, = {(4-0-3) + (2-1-1) + (8-3-3) + (5-4-1)} / 4 = (1 + 0 + 2 + 0) / 4 = 3 / 4 = 0.75 Now, let Z = 2, then gantt chart will be, Average waiting time, = {(4-0-3) + (2-1-1) + (9-3-3) + (6-4-2)} / 4 = (1 + 0 + 3 + 0) / 4 = 4 / 4 = 1 So, answer is 2. Watch GeeksforGeeks Video explanation : CPU Scheduling GATE Previous Year Questions Part-II with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch 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 / 49:57β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" 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 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2008 | Question 40 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2015 (Set 2) | Question 55
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 379, "s": 28, "text": "Consider the following four processes with arrival times (in milliseconds) and their length of CPU burst (in milliseconds) as shown below:These processes are run on a single processor using preemptive Shortest Remaining Time First scheduling algorithm. If the average waiting time of the processes is 1 millisecond, then the value of Z is __________." }, { "code": null, "e": 531, "s": 379, "text": "Note: This was Numerical Type question.(A) 2(B) 3(C) 1(D) 4Answer: (A)Explanation: Using shortest remaining time (SRTF) first CPU scheduling algorithm," }, { "code": null, "e": 568, "s": 531, "text": "Let Z = 1, then gantt chart will be," }, { "code": null, "e": 590, "s": 568, "text": "Average waiting time," }, { "code": null, "e": 674, "s": 590, "text": "= {(4-0-3) + (2-1-1) + (8-3-3) + (5-4-1)} / 4\n= (1 + 0 + 2 + 0) / 4\n= 3 / 4\n= 0.75 " }, { "code": null, "e": 716, "s": 674, "text": "Now, let Z = 2, then gantt chart will be," }, { "code": null, "e": 738, "s": 716, "text": "Average waiting time," }, { "code": null, "e": 819, "s": 738, "text": "= {(4-0-3) + (2-1-1) + (9-3-3) + (6-4-2)} / 4\n= (1 + 0 + 3 + 0) / 4\n= 4 / 4\n= 1 " }, { "code": null, "e": 836, "s": 819, "text": "So, answer is 2." }, { "code": null, "e": 876, "s": 836, "text": "Watch GeeksforGeeks Video explanation :" }, { "code": null, "e": 1847, "s": 876, "text": "CPU Scheduling GATE Previous Year Questions Part-II with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch 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 / 49:57β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=maVQoJuMAlM\" 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": 1852, "s": 1847, "text": "GATE" }, { "code": null, "e": 1950, "s": 1852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1992, "s": 1950, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2054, "s": 1992, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2096, "s": 2054, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 2130, "s": 2096, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2172, "s": 2130, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2214, "s": 2172, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 2256, "s": 2214, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2290, "s": 2256, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 2324, "s": 2290, "text": "GATE | GATE CS 1996 | Question 63" } ]
How to Disable RecyclerView Scrolling in Android?
29 Jul, 2021 RecyclerView is a view group used for displaying data from arrays and databases. RecyclerView basically is a list of items from the data. RecyclerView is often referred to as a successor of GridView and ListView. More about RecyclerView could be found at RecyclerView in Android with Example. RecyclerView lets the users scroll up and down and left and right by setting appropriate orientation via attributes. Most of the applications that we use today prominently use RecyclerView to display or present the data. RecyclerView examples Through this article, we want to show you how you could disable the scrolling ability of the RecyclerView in Android. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Create this simple RecyclerView in the layout. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view_1" android:layout_width="match_parent" android:layout_height="match_parent"/> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Create a Card for the RecyclerView (card.xml) We need to create a layout for displaying our data. In our case, we have a list of cities. So each of such cards will display the city name in the TextView. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/place_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:layout_marginVertical="30sp" android:textSize="70sp"/> </RelativeLayout> Step 4: Create an Adapter for the RecyclerView (MyRecyclerViewAdapter.kt) We have to create an adapter to pass data (array of the city names) to the RecyclerView. Kotlin import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerView private val myItemList = arrayListOf("Delhi", "Mumbai", "Hyderabad", "Bangalore", "Chennai", "Kolkata") class MyRecyclerViewAdapter: RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>() { inner class ViewHolder(v: View): RecyclerView.ViewHolder(v), View.OnClickListener{ val tvPlaceName: TextView = v.findViewById(R.id.place_name) override fun onClick(v: View?) { TODO() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewAdapter.ViewHolder { return ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.card, parent, false)) } override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) { holder.tvPlaceName.text = myItemList[position] } override fun getItemCount(): Int { return myItemList.size }} Step 5: Link the RecyclerView and the Adapter in the Main code (MainActivity.kt) Refer to the comments inside the code. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the recycler view from the layout file val myRecyclerView = findViewById<RecyclerView>(R.id.recycler_view_1) // Declaring a variable for // Initializing Linear Layout Manager val myLinearLayoutManager = LinearLayoutManager(this) // Setting the layout manager of the // recycler view with the Initialized variable myRecyclerView.layoutManager = myLinearLayoutManager // Setting the adapter of the recycler view // with the adapter we created myRecyclerView.adapter = MyRecyclerViewAdapter() }} Output: Run the application You can see that we are able to scroll. Step 6: Edit the layout manager to disable the RecyclerView scrolling Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val myRecyclerView = findViewById<RecyclerView>(R.id.recycler_view_1) // Calling the override functions from // the Linear Layout Manager inner class val myLinearLayoutManager = object : LinearLayoutManager(this) { override fun canScrollVertically(): Boolean { return false } } myRecyclerView.layoutManager = myLinearLayoutManager myRecyclerView.adapter = MyRecyclerViewAdapter() }} Output: Now run the application Now, you can see that we are unable to scroll. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Add Views Dynamically and Store Data in Arraylist in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array How to Add Views Dynamically and Store Data in Arraylist in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 543, "s": 28, "text": "RecyclerView is a view group used for displaying data from arrays and databases. RecyclerView basically is a list of items from the data. RecyclerView is often referred to as a successor of GridView and ListView. More about RecyclerView could be found at RecyclerView in Android with Example. RecyclerView lets the users scroll up and down and left and right by setting appropriate orientation via attributes. Most of the applications that we use today prominently use RecyclerView to display or present the data. " }, { "code": null, "e": 565, "s": 543, "text": "RecyclerView examples" }, { "code": null, "e": 683, "s": 565, "text": "Through this article, we want to show you how you could disable the scrolling ability of the RecyclerView in Android." }, { "code": null, "e": 730, "s": 683, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 969, "s": 730, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 1017, "s": 969, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1206, "s": 1017, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Create this simple RecyclerView in the layout." }, { "code": null, "e": 1210, "s": 1206, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recycler_view_1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 1812, "s": 1210, "text": null }, { "code": null, "e": 1866, "s": 1812, "text": "Step 3: Create a Card for the RecyclerView (card.xml)" }, { "code": null, "e": 2023, "s": 1866, "text": "We need to create a layout for displaying our data. In our case, we have a list of cities. So each of such cards will display the city name in the TextView." }, { "code": null, "e": 2027, "s": 2023, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:id=\"@+id/place_name\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:layout_marginVertical=\"30sp\" android:textSize=\"70sp\"/> </RelativeLayout>", "e": 2490, "s": 2027, "text": null }, { "code": null, "e": 2564, "s": 2490, "text": "Step 4: Create an Adapter for the RecyclerView (MyRecyclerViewAdapter.kt)" }, { "code": null, "e": 2653, "s": 2564, "text": "We have to create an adapter to pass data (array of the city names) to the RecyclerView." }, { "code": null, "e": 2660, "s": 2653, "text": "Kotlin" }, { "code": "import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerView private val myItemList = arrayListOf(\"Delhi\", \"Mumbai\", \"Hyderabad\", \"Bangalore\", \"Chennai\", \"Kolkata\") class MyRecyclerViewAdapter: RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>() { inner class ViewHolder(v: View): RecyclerView.ViewHolder(v), View.OnClickListener{ val tvPlaceName: TextView = v.findViewById(R.id.place_name) override fun onClick(v: View?) { TODO() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewAdapter.ViewHolder { return ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.card, parent, false)) } override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) { holder.tvPlaceName.text = myItemList[position] } override fun getItemCount(): Int { return myItemList.size }}", "e": 3700, "s": 2660, "text": null }, { "code": null, "e": 3781, "s": 3700, "text": "Step 5: Link the RecyclerView and the Adapter in the Main code (MainActivity.kt)" }, { "code": null, "e": 3820, "s": 3781, "text": "Refer to the comments inside the code." }, { "code": null, "e": 3827, "s": 3820, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the recycler view from the layout file val myRecyclerView = findViewById<RecyclerView>(R.id.recycler_view_1) // Declaring a variable for // Initializing Linear Layout Manager val myLinearLayoutManager = LinearLayoutManager(this) // Setting the layout manager of the // recycler view with the Initialized variable myRecyclerView.layoutManager = myLinearLayoutManager // Setting the adapter of the recycler view // with the adapter we created myRecyclerView.adapter = MyRecyclerViewAdapter() }}", "e": 4787, "s": 3827, "text": null }, { "code": null, "e": 4815, "s": 4787, "text": "Output: Run the application" }, { "code": null, "e": 4855, "s": 4815, "text": "You can see that we are able to scroll." }, { "code": null, "e": 4925, "s": 4855, "text": "Step 6: Edit the layout manager to disable the RecyclerView scrolling" }, { "code": null, "e": 4932, "s": 4925, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val myRecyclerView = findViewById<RecyclerView>(R.id.recycler_view_1) // Calling the override functions from // the Linear Layout Manager inner class val myLinearLayoutManager = object : LinearLayoutManager(this) { override fun canScrollVertically(): Boolean { return false } } myRecyclerView.layoutManager = myLinearLayoutManager myRecyclerView.adapter = MyRecyclerViewAdapter() }}", "e": 5772, "s": 4932, "text": null }, { "code": null, "e": 5804, "s": 5772, "text": "Output: Now run the application" }, { "code": null, "e": 5851, "s": 5804, "text": "Now, you can see that we are unable to scroll." }, { "code": null, "e": 5859, "s": 5851, "text": "Android" }, { "code": null, "e": 5866, "s": 5859, "text": "Kotlin" }, { "code": null, "e": 5874, "s": 5866, "text": "Android" }, { "code": null, "e": 5972, "s": 5874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6004, "s": 5972, "text": "Android SDK and it's Components" }, { "code": null, "e": 6043, "s": 6004, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6112, "s": 6043, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6154, "s": 6112, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6205, "s": 6154, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 6224, "s": 6205, "text": "Android UI Layouts" }, { "code": null, "e": 6237, "s": 6224, "text": "Kotlin Array" }, { "code": null, "e": 6306, "s": 6237, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" } ]
Zoom Functionality in ElectronJS
28 Jun, 2022 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. All traditional web Browsers have Zoom functionality built into them. The user can simply zoom in/zoom out to increase/decrease the size of the contents of the web page respectively by scrolling the mouse wheel. By default, Electron does not enable Zoom functionality for its BrowserWindow Instances. However, Electron does provide a way by which we can add Zoom functionality to the contents of the page using the Instance methods, events, and properties of the built-in BrowserWindow object and the webContents property. The webContents property provides us with certain Instance events and methods by which we can set the default zoom of the web page, the maximum and minimum zoom of the web page and zoom in/zoom the contents of the web page using the mouse scroll. This tutorial will demonstrate Zoom functionality in Electron. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in Printing in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: { "name": "electron-zoom", "version": "1.0.0", "description": "Zoom in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following Output: Zoom Functionality in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. index.html: Add the following snippet in that file. html <h3>Zoom in Electron</h3><div>Ctrl+Scroll for Triggering Zoom Functionality</div> index.js: Add the following snippet in that file. javascript const electron = require("electron"); // Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;let win = BrowserWindow.getFocusedWindow(); // let win = BrowserWindow.getAllWindows()[0]; // If reduced below Minimum value// Error - 'zoomFactor' must be a double greater than 0.0win.webContents.setZoomFactor(1.0); // Upper Limit is working of 500 %win.webContents .setVisualZoomLevelLimits(1, 5) .then(console.log("Zoom Levels Have been Set between 100% and 500%")) .catch((err) => console.log(err)); win.webContents.on("zoom-changed", (event, zoomDirection) => { console.log(zoomDirection); var currentZoom = win.webContents.getZoomFactor(); console.log("Current Zoom Factor - ", currentZoom); // console.log('Current Zoom Level at - ' // , win.webContents.getZoomLevel()); console.log("Current Zoom Level at - ", win.webContents.zoomLevel); if (zoomDirection === "in") { // win.webContents.setZoomFactor(currentZoom + 0.20); win.webContents.zoomFactor = currentZoom + 0.2; console.log("Zoom Factor Increased to - " , win.webContents.zoomFactor * 100, "%"); } if (zoomDirection === "out") { // win.webContents.setZoomFactor(currentZoom - 0.20); win.webContents.zoomFactor = currentZoom - 0.2; console.log("Zoom Factor Decreased to - " , win.webContents.zoomFactor * 100, "%"); }}); A detailed Explanation of all the Instance Events, Methods, and Properties used in the code are given below: zoom-changed: Event This Instance Event of the webContents property is emitted when the user is requesting to change the Zoom level of the web page by scrolling the mouse wheel. On Windows, this is triggered by the Ctrl+Scroll key combination. By default, Electron does not have Zoom enabled and this Event needs to be explicitly added to know whether the change in Zoom level was triggered or not. This Event returns the following parameters.event: The global Event object.zoomDirection: String This parameter represents whether the Scroll on the mouse wheel was initiated upwards signifying Zoom-In or was initiated downwards signifying Zoom-Out. This parameter can only hold two values i.e. in or out respectively. event: The global Event object. zoomDirection: String This parameter represents whether the Scroll on the mouse wheel was initiated upwards signifying Zoom-In or was initiated downwards signifying Zoom-Out. This parameter can only hold two values i.e. in or out respectively. webContents.setZoomFactor(factor) This Instance Method of the webContents property changes the Zoom Factor of the web page to the specified factor. This Instance method determines by what factor the web page should be zoomed in or out. Zoom factor is Zoom percent divided by 100. Hence, If Zoom Percent is 100% then Zoom Factor – 1.0. It takes in the following parameters. In the above code, we are increasing/decreasing the Zoom Factor for every zoom-changed Instance Event emitted by 0.2 which means 20% zoom-in or zoom-out.factor: Double The double Zoom Factor. By default, value is set as 1.0. The factor value must always be greater than 0.0. In case during zoom operations, this value goes below 0.0, An Error is triggered and displayed in the Console and no further changes are made to the Zoom of the web page. factor: Double The double Zoom Factor. By default, value is set as 1.0. The factor value must always be greater than 0.0. In case during zoom operations, this value goes below 0.0, An Error is triggered and displayed in the Console and no further changes are made to the Zoom of the web page. webContents.getZoomFactor() This Instance method of the webContents property returns an Integer value stating the current Zoom Factor of the web page. The value returned will always be greater than 0.0.Note – Even though not specified in the Official Electron documentation, as of Electron 8.3.0, this method stands Deprecated. In case this method is used, it will display a warning message in the console even though it still works. We should use the webContents.zoomFactor Instance Property instead to fetch and manipulate the Zoom Factor of the web page. The same has been demonstrated in the code and explained below. webContents.setZoomLevel(level) This Instance method of the webContents property changes the Zoom level of the web page to the specified level. This Instance method determines by what level the web page should be zoomed in or out. According to Official Electron documentation, The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level. Note – This Instance method and the webContents.setZoomFactor() Instance method, both perform the same manipulations to the Zoom of the contents of the web page in Electron. These Instance methods simply take in different values based on the factor and level provided respectively. Also webContents.setZoomFactor() method is easier to manage and control. In the above code, we have displayed the Zoom Factor and the Zoom level every time the Instance Event is emitted. Also the Zoom Level of the web page can be a Negative value as well. Note – Even though not specified in the Official Electron documentation, as of Electron 8.3.0, this method stands Deprecated. In case this method is used, it will display a warning message in the console even though it still works. We should use the webContents.zoomLevel Instance Property instead to fetch and manipulate the Zoom Level of the web page. webContents.getZoomLevel() This Instance method of the webContents property returns an Integer value stating the current Zoom Level of the web page. The value returned can also be Negative value. Note – Even though not specified in the Official Electron documentation, as of Electron 8.3.0, this method stands Deprecated. In case this method is used, it will display a warning message in the console even though it still works. We should use the webContents.zoomLevel Instance Property instead to fetch and manipulate the Zoom Level of the web page. win.webContents.setVisualZoomLevelLimits(minimum, maximum) This Instance Method of the webContents property sets the minimum and maximum limit of the Zoom Level. As discussed above, Zoom functionality is disabled in Electron by default. To enable it, this Instance method is used. It returns a Promise and it is resolved when the minimum and the maximum Zoom for the web page have been set successfully. It takes in the following parameters.minimum: Integer Sets the Minimum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 100% translates to 1 which is set in this parameter.maximum: Integer Sets the Maximum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 500% translates to 5 which is set in this parameter. minimum: Integer Sets the Minimum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 100% translates to 1 which is set in this parameter. maximum: Integer Sets the Maximum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 500% translates to 5 which is set in this parameter. webContents.zoomFactor This Instance property of the webContents property changes the Zoom Factor of the web page to the specified factor. This Instance property determines by what factor the web page should be zoomed in or out. Zoom factor is Zoom percent divided by 100. In the above code, we are increasing/decreasing the Zoom Factor for every zoom-changed Instance Event emitted by 0.2 which means 20% zoom-in or zoom-out. webContents.zoomLevel This Instance property of the webContents property changes the Zoom Level of the web page to the specified level. This Instance property determines by what level the web page should be zoomed in or out. According to Official Electron documentation, The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level. To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code. BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. At this point, we should successfully be able to Zoom-In and Zoom-Out of the contents of the BrowserWindow in Electron. Output: arorakashish0911 nikhatkhan11 ElectronJS CSS HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 328, "s": 28, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 1161, "s": 328, "text": "All traditional web Browsers have Zoom functionality built into them. The user can simply zoom in/zoom out to increase/decrease the size of the contents of the web page respectively by scrolling the mouse wheel. By default, Electron does not enable Zoom functionality for its BrowserWindow Instances. However, Electron does provide a way by which we can add Zoom functionality to the contents of the page using the Instance methods, events, and properties of the built-in BrowserWindow object and the webContents property. The webContents property provides us with certain Instance events and methods by which we can set the default zoom of the web page, the maximum and minimum zoom of the web page and zoom in/zoom the contents of the web page using the mouse scroll. This tutorial will demonstrate Zoom functionality in Electron." }, { "code": null, "e": 1331, "s": 1161, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 1350, "s": 1331, "text": "Project Structure:" }, { "code": null, "e": 1814, "s": 1350, "text": "Example: Follow the Steps given in Printing in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: " }, { "code": null, "e": 2106, "s": 1814, "text": "{\n \"name\": \"electron-zoom\",\n \"version\": \"1.0.0\",\n \"description\": \"Zoom in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}" }, { "code": null, "e": 2241, "s": 2106, "text": "Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following Output: " }, { "code": null, "e": 2453, "s": 2241, "text": "Zoom Functionality in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module." }, { "code": null, "e": 2505, "s": 2453, "text": "index.html: Add the following snippet in that file." }, { "code": null, "e": 2510, "s": 2505, "text": "html" }, { "code": "<h3>Zoom in Electron</h3><div>Ctrl+Scroll for Triggering Zoom Functionality</div>", "e": 2592, "s": 2510, "text": null }, { "code": null, "e": 2642, "s": 2592, "text": "index.js: Add the following snippet in that file." }, { "code": null, "e": 2653, "s": 2642, "text": "javascript" }, { "code": "const electron = require(\"electron\"); // Import BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;let win = BrowserWindow.getFocusedWindow(); // let win = BrowserWindow.getAllWindows()[0]; // If reduced below Minimum value// Error - 'zoomFactor' must be a double greater than 0.0win.webContents.setZoomFactor(1.0); // Upper Limit is working of 500 %win.webContents .setVisualZoomLevelLimits(1, 5) .then(console.log(\"Zoom Levels Have been Set between 100% and 500%\")) .catch((err) => console.log(err)); win.webContents.on(\"zoom-changed\", (event, zoomDirection) => { console.log(zoomDirection); var currentZoom = win.webContents.getZoomFactor(); console.log(\"Current Zoom Factor - \", currentZoom); // console.log('Current Zoom Level at - ' // , win.webContents.getZoomLevel()); console.log(\"Current Zoom Level at - \", win.webContents.zoomLevel); if (zoomDirection === \"in\") { // win.webContents.setZoomFactor(currentZoom + 0.20); win.webContents.zoomFactor = currentZoom + 0.2; console.log(\"Zoom Factor Increased to - \" , win.webContents.zoomFactor * 100, \"%\"); } if (zoomDirection === \"out\") { // win.webContents.setZoomFactor(currentZoom - 0.20); win.webContents.zoomFactor = currentZoom - 0.2; console.log(\"Zoom Factor Decreased to - \" , win.webContents.zoomFactor * 100, \"%\"); }});", "e": 4110, "s": 2653, "text": null }, { "code": null, "e": 4220, "s": 4110, "text": "A detailed Explanation of all the Instance Events, Methods, and Properties used in the code are given below: " }, { "code": null, "e": 4938, "s": 4220, "text": "zoom-changed: Event This Instance Event of the webContents property is emitted when the user is requesting to change the Zoom level of the web page by scrolling the mouse wheel. On Windows, this is triggered by the Ctrl+Scroll key combination. By default, Electron does not have Zoom enabled and this Event needs to be explicitly added to know whether the change in Zoom level was triggered or not. This Event returns the following parameters.event: The global Event object.zoomDirection: String This parameter represents whether the Scroll on the mouse wheel was initiated upwards signifying Zoom-In or was initiated downwards signifying Zoom-Out. This parameter can only hold two values i.e. in or out respectively." }, { "code": null, "e": 4970, "s": 4938, "text": "event: The global Event object." }, { "code": null, "e": 5214, "s": 4970, "text": "zoomDirection: String This parameter represents whether the Scroll on the mouse wheel was initiated upwards signifying Zoom-In or was initiated downwards signifying Zoom-Out. This parameter can only hold two values i.e. in or out respectively." }, { "code": null, "e": 6033, "s": 5214, "text": "webContents.setZoomFactor(factor) This Instance Method of the webContents property changes the Zoom Factor of the web page to the specified factor. This Instance method determines by what factor the web page should be zoomed in or out. Zoom factor is Zoom percent divided by 100. Hence, If Zoom Percent is 100% then Zoom Factor – 1.0. It takes in the following parameters. In the above code, we are increasing/decreasing the Zoom Factor for every zoom-changed Instance Event emitted by 0.2 which means 20% zoom-in or zoom-out.factor: Double The double Zoom Factor. By default, value is set as 1.0. The factor value must always be greater than 0.0. In case during zoom operations, this value goes below 0.0, An Error is triggered and displayed in the Console and no further changes are made to the Zoom of the web page." }, { "code": null, "e": 6326, "s": 6033, "text": "factor: Double The double Zoom Factor. By default, value is set as 1.0. The factor value must always be greater than 0.0. In case during zoom operations, this value goes below 0.0, An Error is triggered and displayed in the Console and no further changes are made to the Zoom of the web page." }, { "code": null, "e": 6948, "s": 6326, "text": "webContents.getZoomFactor() This Instance method of the webContents property returns an Integer value stating the current Zoom Factor of the web page. The value returned will always be greater than 0.0.Note – Even though not specified in the Official Electron documentation, as of Electron 8.3.0, this method stands Deprecated. In case this method is used, it will display a warning message in the console even though it still works. We should use the webContents.zoomFactor Instance Property instead to fetch and manipulate the Zoom Factor of the web page. The same has been demonstrated in the code and explained below." }, { "code": null, "e": 8327, "s": 6948, "text": "webContents.setZoomLevel(level) This Instance method of the webContents property changes the Zoom level of the web page to the specified level. This Instance method determines by what level the web page should be zoomed in or out. According to Official Electron documentation, The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level. Note – This Instance method and the webContents.setZoomFactor() Instance method, both perform the same manipulations to the Zoom of the contents of the web page in Electron. These Instance methods simply take in different values based on the factor and level provided respectively. Also webContents.setZoomFactor() method is easier to manage and control. In the above code, we have displayed the Zoom Factor and the Zoom level every time the Instance Event is emitted. Also the Zoom Level of the web page can be a Negative value as well. Note – Even though not specified in the Official Electron documentation, as of Electron 8.3.0, this method stands Deprecated. In case this method is used, it will display a warning message in the console even though it still works. We should use the webContents.zoomLevel Instance Property instead to fetch and manipulate the Zoom Level of the web page." }, { "code": null, "e": 8877, "s": 8327, "text": "webContents.getZoomLevel() This Instance method of the webContents property returns an Integer value stating the current Zoom Level of the web page. The value returned can also be Negative value. Note – Even though not specified in the Official Electron documentation, as of Electron 8.3.0, this method stands Deprecated. In case this method is used, it will display a warning message in the console even though it still works. We should use the webContents.zoomLevel Instance Property instead to fetch and manipulate the Zoom Level of the web page." }, { "code": null, "e": 9689, "s": 8877, "text": "win.webContents.setVisualZoomLevelLimits(minimum, maximum) This Instance Method of the webContents property sets the minimum and maximum limit of the Zoom Level. As discussed above, Zoom functionality is disabled in Electron by default. To enable it, this Instance method is used. It returns a Promise and it is resolved when the minimum and the maximum Zoom for the web page have been set successfully. It takes in the following parameters.minimum: Integer Sets the Minimum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 100% translates to 1 which is set in this parameter.maximum: Integer Sets the Maximum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 500% translates to 5 which is set in this parameter." }, { "code": null, "e": 9875, "s": 9689, "text": "minimum: Integer Sets the Minimum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 100% translates to 1 which is set in this parameter." }, { "code": null, "e": 10061, "s": 9875, "text": "maximum: Integer Sets the Maximum Zoom allowed for the web page. This value is the Zoom percent divided by 100. Hence Zoom Percent – 500% translates to 5 which is set in this parameter." }, { "code": null, "e": 10488, "s": 10061, "text": "webContents.zoomFactor This Instance property of the webContents property changes the Zoom Factor of the web page to the specified factor. This Instance property determines by what factor the web page should be zoomed in or out. Zoom factor is Zoom percent divided by 100. In the above code, we are increasing/decreasing the Zoom Factor for every zoom-changed Instance Event emitted by 0.2 which means 20% zoom-in or zoom-out." }, { "code": null, "e": 10969, "s": 10488, "text": "webContents.zoomLevel This Instance property of the webContents property changes the Zoom Level of the web page to the specified level. This Instance property determines by what level the web page should be zoomed in or out. According to Official Electron documentation, The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level." }, { "code": null, "e": 11113, "s": 10969, "text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. " }, { "code": null, "e": 11352, "s": 11113, "text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code." }, { "code": null, "e": 11674, "s": 11352, "text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code." }, { "code": null, "e": 11803, "s": 11674, "text": "At this point, we should successfully be able to Zoom-In and Zoom-Out of the contents of the BrowserWindow in Electron. Output: " }, { "code": null, "e": 11820, "s": 11803, "text": "arorakashish0911" }, { "code": null, "e": 11833, "s": 11820, "text": "nikhatkhan11" }, { "code": null, "e": 11844, "s": 11833, "text": "ElectronJS" }, { "code": null, "e": 11848, "s": 11844, "text": "CSS" }, { "code": null, "e": 11853, "s": 11848, "text": "HTML" }, { "code": null, "e": 11864, "s": 11853, "text": "JavaScript" }, { "code": null, "e": 11872, "s": 11864, "text": "Node.js" }, { "code": null, "e": 11889, "s": 11872, "text": "Web Technologies" }, { "code": null, "e": 11894, "s": 11889, "text": "HTML" } ]
Python | Convert list of nested dictionary into Pandas dataframe
14 May, 2020 Given a list of nested dictionary, write a Python program to create a Pandas dataframe using it. Let’s understand stepwise procedure to create Pandas Dataframe using list of nested dictionary. Step #1: Creating a list of nested dictionary. # importing pandasimport pandas as pd # List of nested dictionary initializationlist = [ { "Student": [{"Exam": 90, "Grade": "a"}, {"Exam": 99, "Grade": "b"}, {"Exam": 97, "Grade": "c"}, ], "Name": "Paras Jain" }, { "Student": [{"Exam": 89, "Grade": "a"}, {"Exam": 80, "Grade": "b"} ], "Name": "Chunky Pandey" } ] #print(list) Output: Step #2: Adding dict values to rows. # rows list initializationrows = [] # appending rowsfor data in list: data_row = data['Student'] time = data['Name'] for row in data_row: row['Name']= time rows.append(row) # using data framedf = pd.DataFrame(rows) # print(df) Output: Step #3: Pivoting dataframe and assigning column names. # using pivot_tabledf = df.pivot_table(index ='Name', columns =['Grade'], values =['Exam']).reset_index() # Defining columnsdf.columns =['Name', 'Maths', 'Physics', 'Chemistry'] # print dataframeprint(df) Output: Below is the complete code: # Python program to convert list of nested # dictionary into Pandas dataframe # importing pandasimport pandas as pd # List of list of dictionary initializationlist = [ { "Student": [{"Exam": 90, "Grade": "a"}, {"Exam": 99, "Grade": "b"}, {"Exam": 97, "Grade": "c"}, ], "Name": "Paras Jain" }, { "Student": [{"Exam": 89, "Grade": "a"}, {"Exam": 80, "Grade": "b"} ], "Name": "Chunky Pandey" } ] # rows list initializationrows = [] # appending rowsfor data in list: data_row = data['Student'] time = data['Name'] for row in data_row: row['Name']= time rows.append(row) # using data framedf = pd.DataFrame(rows) # using pivot_tabledf = df.pivot_table(index ='Name', columns =['Grade'], values =['Exam']).reset_index() # Defining columnsdf.columns =['Name', 'Maths', 'Physics', 'Chemistry'] # print dataframeprint(df) Output: Name Maths Physics Chemistry 0 Chunky Pandey 89 80 NaN 1 Paras Jain 90 99 97 shubham_singh pandas-dataframe-program Python pandas-dataFrame Python-nested-dictionary Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n14 May, 2020" }, { "code": null, "e": 245, "s": 52, "text": "Given a list of nested dictionary, write a Python program to create a Pandas dataframe using it. Let’s understand stepwise procedure to create Pandas Dataframe using list of nested dictionary." }, { "code": null, "e": 292, "s": 245, "text": "Step #1: Creating a list of nested dictionary." }, { "code": "# importing pandasimport pandas as pd # List of nested dictionary initializationlist = [ { \"Student\": [{\"Exam\": 90, \"Grade\": \"a\"}, {\"Exam\": 99, \"Grade\": \"b\"}, {\"Exam\": 97, \"Grade\": \"c\"}, ], \"Name\": \"Paras Jain\" }, { \"Student\": [{\"Exam\": 89, \"Grade\": \"a\"}, {\"Exam\": 80, \"Grade\": \"b\"} ], \"Name\": \"Chunky Pandey\" } ] #print(list)", "e": 776, "s": 292, "text": null }, { "code": null, "e": 785, "s": 776, "text": "Output: " }, { "code": null, "e": 822, "s": 785, "text": "Step #2: Adding dict values to rows." }, { "code": "# rows list initializationrows = [] # appending rowsfor data in list: data_row = data['Student'] time = data['Name'] for row in data_row: row['Name']= time rows.append(row) # using data framedf = pd.DataFrame(rows) # print(df)", "e": 1081, "s": 822, "text": null }, { "code": null, "e": 1145, "s": 1081, "text": "Output: Step #3: Pivoting dataframe and assigning column names." }, { "code": "# using pivot_tabledf = df.pivot_table(index ='Name', columns =['Grade'], values =['Exam']).reset_index() # Defining columnsdf.columns =['Name', 'Maths', 'Physics', 'Chemistry'] # print dataframeprint(df)", "e": 1375, "s": 1145, "text": null }, { "code": null, "e": 1383, "s": 1375, "text": "Output:" }, { "code": null, "e": 1412, "s": 1383, "text": " Below is the complete code:" }, { "code": "# Python program to convert list of nested # dictionary into Pandas dataframe # importing pandasimport pandas as pd # List of list of dictionary initializationlist = [ { \"Student\": [{\"Exam\": 90, \"Grade\": \"a\"}, {\"Exam\": 99, \"Grade\": \"b\"}, {\"Exam\": 97, \"Grade\": \"c\"}, ], \"Name\": \"Paras Jain\" }, { \"Student\": [{\"Exam\": 89, \"Grade\": \"a\"}, {\"Exam\": 80, \"Grade\": \"b\"} ], \"Name\": \"Chunky Pandey\" } ] # rows list initializationrows = [] # appending rowsfor data in list: data_row = data['Student'] time = data['Name'] for row in data_row: row['Name']= time rows.append(row) # using data framedf = pd.DataFrame(rows) # using pivot_tabledf = df.pivot_table(index ='Name', columns =['Grade'], values =['Exam']).reset_index() # Defining columnsdf.columns =['Name', 'Maths', 'Physics', 'Chemistry'] # print dataframeprint(df)", "e": 2439, "s": 1412, "text": null }, { "code": null, "e": 2447, "s": 2439, "text": "Output:" }, { "code": null, "e": 2579, "s": 2447, "text": " Name Maths Physics Chemistry\n0 Chunky Pandey 89 80 NaN\n1 Paras Jain 90 99 97" }, { "code": null, "e": 2593, "s": 2579, "text": "shubham_singh" }, { "code": null, "e": 2618, "s": 2593, "text": "pandas-dataframe-program" }, { "code": null, "e": 2642, "s": 2618, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2667, "s": 2642, "text": "Python-nested-dictionary" }, { "code": null, "e": 2681, "s": 2667, "text": "Python-pandas" }, { "code": null, "e": 2688, "s": 2681, "text": "Python" }, { "code": null, "e": 2786, "s": 2688, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2804, "s": 2786, "text": "Python Dictionary" }, { "code": null, "e": 2846, "s": 2804, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2868, "s": 2846, "text": "Enumerate() in Python" }, { "code": null, "e": 2903, "s": 2868, "text": "Read a file line by line in Python" }, { "code": null, "e": 2935, "s": 2903, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2964, "s": 2935, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2991, "s": 2964, "text": "Python Classes and Objects" }, { "code": null, "e": 3012, "s": 2991, "text": "Python OOPs Concepts" }, { "code": null, "e": 3035, "s": 3012, "text": "Introduction To PYTHON" } ]
filepath.Clean() Function in Golang With Examples
10 May, 2020 In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Clean() function in Go language used to return the shortest path name equivalent to the specified path by purely lexical processing. Moreover, this function is defined under the path package. Here, you need to import the β€œpath/filepath” package in order to use these functions. This function applies the Below rules iteratively until no further processing can be done: It Replaces multiple Separator elements with a single one. If the specified path is an empty string, it returns the string β€œ.”. It eliminates each . path name element (the current directory). It eliminates each inner .. path name element (the parent directory) along with the non-.. element that precedes it. It eliminates .. elements that begin a rooted path: that is, replace β€œ/..” by β€œ/” at the beginning of a path, assuming Separator is β€˜/’. Syntax: func Clean(path string) string Here, β€˜path’ is the specified path. Return Value: It returns the shortest path name equivalent to the specified path by purely lexical processing. Example 1: // Golang program to illustrate the usage of// filepath.Clean() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Clean() function fmt.Println(filepath.Clean("/GFG/./../Geeks")) fmt.Println(filepath.Clean("GFG/../Geeks")) fmt.Println(filepath.Clean("..GFG/./../Geeks")) fmt.Println(filepath.Clean("gfg/../../../Geek/GFG"))} Output: /Geeks Geeks Geeks ../../Geek/GFG Example 2: // Golang program to illustrate the usage of// filepath.Clean() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Clean() function fmt.Println(filepath.Clean("")) fmt.Println(filepath.Clean(".")) fmt.Println(filepath.Clean("///")) fmt.Println(filepath.Clean("/.//")) fmt.Println(filepath.Clean("/./")) fmt.Println(filepath.Clean(":/"))} Output: . . / / / : Golang-filepath Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 423, "s": 28, "text": "In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Clean() function in Go language used to return the shortest path name equivalent to the specified path by purely lexical processing. Moreover, this function is defined under the path package. Here, you need to import the β€œpath/filepath” package in order to use these functions." }, { "code": null, "e": 514, "s": 423, "text": "This function applies the Below rules iteratively until no further processing can be done:" }, { "code": null, "e": 573, "s": 514, "text": "It Replaces multiple Separator elements with a single one." }, { "code": null, "e": 642, "s": 573, "text": "If the specified path is an empty string, it returns the string β€œ.”." }, { "code": null, "e": 706, "s": 642, "text": "It eliminates each . path name element (the current directory)." }, { "code": null, "e": 823, "s": 706, "text": "It eliminates each inner .. path name element (the parent directory) along with the non-.. element that precedes it." }, { "code": null, "e": 960, "s": 823, "text": "It eliminates .. elements that begin a rooted path: that is, replace β€œ/..” by β€œ/” at the beginning of a path, assuming Separator is β€˜/’." }, { "code": null, "e": 968, "s": 960, "text": "Syntax:" }, { "code": null, "e": 1000, "s": 968, "text": "func Clean(path string) string\n" }, { "code": null, "e": 1036, "s": 1000, "text": "Here, β€˜path’ is the specified path." }, { "code": null, "e": 1147, "s": 1036, "text": "Return Value: It returns the shortest path name equivalent to the specified path by purely lexical processing." }, { "code": null, "e": 1158, "s": 1147, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// filepath.Clean() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Clean() function fmt.Println(filepath.Clean(\"/GFG/./../Geeks\")) fmt.Println(filepath.Clean(\"GFG/../Geeks\")) fmt.Println(filepath.Clean(\"..GFG/./../Geeks\")) fmt.Println(filepath.Clean(\"gfg/../../../Geek/GFG\"))}", "e": 1619, "s": 1158, "text": null }, { "code": null, "e": 1627, "s": 1619, "text": "Output:" }, { "code": null, "e": 1662, "s": 1627, "text": "/Geeks\nGeeks\nGeeks\n../../Geek/GFG\n" }, { "code": null, "e": 1673, "s": 1662, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// filepath.Clean() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Clean() function fmt.Println(filepath.Clean(\"\")) fmt.Println(filepath.Clean(\".\")) fmt.Println(filepath.Clean(\"///\")) fmt.Println(filepath.Clean(\"/.//\")) fmt.Println(filepath.Clean(\"/./\")) fmt.Println(filepath.Clean(\":/\"))}", "e": 2153, "s": 1673, "text": null }, { "code": null, "e": 2161, "s": 2153, "text": "Output:" }, { "code": null, "e": 2174, "s": 2161, "text": ".\n.\n/\n/\n/\n:\n" }, { "code": null, "e": 2190, "s": 2174, "text": "Golang-filepath" }, { "code": null, "e": 2202, "s": 2190, "text": "Go Language" } ]
np.nanmax() in Python
29 Nov, 2018 numpy.nanmax()function is used to returns maximum value of an array or along any specific mentioned axis of the array, ignoring any Nan value. Syntax : numpy.nanmax(arr, axis=None, out=None, keepdims = no value) Parameters :arr : Input array.axis : Axis along which we want the max value. Otherwise, it will consider arr to be flattened(works on all the axis)axis = 0 means along the columnand axis = 1 means working along the row.out : Different array in which we want to place the result. The array must have same dimensions as expected output.keepdims : If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a. Return :maximum array value(a scalar value if axis is none)or array with maximum value along specified axis. Code #1 : Working # Python Program illustrating # numpy.nanmax() method import numpy as np # 1D array arr = [1, 2, 7, 0, np.nan]print("arr : ", arr) print("max of arr : ", np.amax(arr)) # nanmax ignores NaN values. print("nanmax of arr : ", np.nanmax(arr)) Output : arr : [1, 2, 7, 0, nan] max of arr : nan nanmax of arr : 7.0 Code #2 : import numpy as np # 2D array arr = [[np.nan, 17, 12, 33, 44], [15, 6, 27, 8, 19]] print("\narr : \n", arr) # maximum of the flattened array print("\nmax of arr, axis = None : ", np.nanmax(arr)) # maximum along the first axis # axis 0 means vertical print("max of arr, axis = 0 : ", np.nanmax(arr, axis = 0)) # maximum along the second axis # axis 1 means horizontal print("max of arr, axis = 1 : ", np.nanmax(arr, axis = 1)) Output : arr : [[nan, 17, 12, 33, 44], [15, 6, 27, 8, 19]] max of arr, axis = None : 44.0 max of arr, axis = 0 : [15. 17. 27. 33. 44.] max of arr, axis = 1 : [44. 27.] Code #3 : import numpy as np arr1 = np.arange(5) print("Initial arr1 : ", arr1) # using out parameternp.nanmax(arr, axis = 0, out = arr1) print("Changed arr1(having results) : ", arr1) Output : Initial arr1 : [0 1 2 3 4] Changed arr1(having results) : [15 17 27 33 44] Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 171, "s": 28, "text": "numpy.nanmax()function is used to returns maximum value of an array or along any specific mentioned axis of the array, ignoring any Nan value." }, { "code": null, "e": 240, "s": 171, "text": "Syntax : numpy.nanmax(arr, axis=None, out=None, keepdims = no value)" }, { "code": null, "e": 766, "s": 240, "text": "Parameters :arr : Input array.axis : Axis along which we want the max value. Otherwise, it will consider arr to be flattened(works on all the axis)axis = 0 means along the columnand axis = 1 means working along the row.out : Different array in which we want to place the result. The array must have same dimensions as expected output.keepdims : If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a." }, { "code": null, "e": 875, "s": 766, "text": "Return :maximum array value(a scalar value if axis is none)or array with maximum value along specified axis." }, { "code": null, "e": 893, "s": 875, "text": "Code #1 : Working" }, { "code": "# Python Program illustrating # numpy.nanmax() method import numpy as np # 1D array arr = [1, 2, 7, 0, np.nan]print(\"arr : \", arr) print(\"max of arr : \", np.amax(arr)) # nanmax ignores NaN values. print(\"nanmax of arr : \", np.nanmax(arr)) ", "e": 1142, "s": 893, "text": null }, { "code": null, "e": 1151, "s": 1142, "text": "Output :" }, { "code": null, "e": 1216, "s": 1151, "text": "arr : [1, 2, 7, 0, nan]\nmax of arr : nan\nnanmax of arr : 7.0\n" }, { "code": null, "e": 1227, "s": 1216, "text": " Code #2 :" }, { "code": "import numpy as np # 2D array arr = [[np.nan, 17, 12, 33, 44], [15, 6, 27, 8, 19]] print(\"\\narr : \\n\", arr) # maximum of the flattened array print(\"\\nmax of arr, axis = None : \", np.nanmax(arr)) # maximum along the first axis # axis 0 means vertical print(\"max of arr, axis = 0 : \", np.nanmax(arr, axis = 0)) # maximum along the second axis # axis 1 means horizontal print(\"max of arr, axis = 1 : \", np.nanmax(arr, axis = 1)) ", "e": 1678, "s": 1227, "text": null }, { "code": null, "e": 1687, "s": 1678, "text": "Output :" }, { "code": null, "e": 1853, "s": 1687, "text": "arr : \n [[nan, 17, 12, 33, 44], [15, 6, 27, 8, 19]]\n\nmax of arr, axis = None : 44.0\nmax of arr, axis = 0 : [15. 17. 27. 33. 44.]\nmax of arr, axis = 1 : [44. 27.]\n" }, { "code": null, "e": 1864, "s": 1853, "text": " Code #3 :" }, { "code": "import numpy as np arr1 = np.arange(5) print(\"Initial arr1 : \", arr1) # using out parameternp.nanmax(arr, axis = 0, out = arr1) print(\"Changed arr1(having results) : \", arr1) ", "e": 2046, "s": 1864, "text": null }, { "code": null, "e": 2055, "s": 2046, "text": "Output :" }, { "code": null, "e": 2133, "s": 2055, "text": "Initial arr1 : [0 1 2 3 4]\nChanged arr1(having results) : [15 17 27 33 44]\n" }, { "code": null, "e": 2167, "s": 2133, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 2180, "s": 2167, "text": "Python-numpy" }, { "code": null, "e": 2187, "s": 2180, "text": "Python" } ]
How to Remove Ticks from Matplotlib Plots?
24 Feb, 2021 Matplotlib is a Python library that offers us various functions using which we can plot our data and visualize it graphically. But often plotting a graph using the Matplotlib library, we get ticks in our plot which are marked by default on both sides of the plot on the x and y-axis. There can be cases when we don’t want to show these ticks in our plot. Matplotlib.pyplot library offers us a tick_params() method using which we can remove these ticks manually. The tick_params() function accepts some attributes that take Boolean values which can be used to remove ticks and labels on the plot. By default, the values in this attribute are set to True, Let’s understand this using an example: Python # importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint("Points on x-axis are: ",X_axis)print("Points on y-axis are: ",Y_axis) # Creating a default plotplt.figure(figsize=(8,6))plt.plot(X_axis,Y_axis)plt.scatter(X_axis,Y_axis)plt.show() Output: Points on x-axis are: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Points on y-axis are: [25, 45, 65, 85, 105, 125, 145, 165, 185, 205] default plot made using matplotlib including ticks By viewing the above image, we can observe by default Matplotlib marks ticks on the x and y-axis. Case 1.1: When we want to remove ticks on a single axis (here y-axis): To remove the ticks on the y-axis, tick_params() method has an attribute named left and we can set its value to False and pass it as a parameter inside the tick_params() function. It removes the tick on the y-axis. Python # importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint("Points on x-axis are: ", X_axis)print("Points on y-axis are: ", Y_axis) plt.figure(figsize = ( 8, 6))plt.tick_params(left = False)plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show() Output: plot made after using tick_params() method to remove ticks on y-axis Case 1.2: When we want to remove ticks on a single axis (here x-axis): To remove the ticks on the x-axis, tick_params() method accepts an attribute named bottom, and we can set its value to False and pass it as a parameter inside the tick_params() function. It removes the tick on the x-axis. Python # importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint("Points on x-axis are: ", X_axis)print("Points on y-axis are: ", Y_axis) plt.figure(figsize = (8, 6))plt.tick_params(bottom = False)plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show() Output: plot made after using tick_params() method to remove ticks on x-axis Case 2: Removing these ticks on both the axes using tick_params() method: To remove the ticks on both the x-axis and y-axis simultaneously, we can pass both left and right attributes simultaneously setting its value to False and pass it as a parameter inside the tick_params() function. It removes the ticks on both x-axis and the y-axis simultaneously. Python # importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint("Points on x-axis are: ", X_axis)print("Points on y-axis are: ", Y_axis) plt.figure(figsize = (8,6))plt.tick_params(left = False, bottom = False)plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show() Output: plot made after using tick_params() method to remove ticks on both x and y-axis Case 3: When we want to remove both ticks and labels from both the axes To remove both ticks and labels from both the axes simultaneously, apart from setting both left and right attributes to False, we will also use two additional attributes for labels which are- labelleft and labelbottom and we will set its value to False and pass it inside the tick_params() function. It will remove labels from both axes also. Python3 # importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint("Points on x-axis are: ", X_axis)print("Points on y-axis are: ", Y_axis) plt.figure(figsize = (8,6))plt.tick_params(left = False, right = False , labelleft = False , labelbottom = False, bottom = False) plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show() Output: plot made after using tick_params() method to remove ticks and labels on both x and y-axis Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Feb, 2021" }, { "code": null, "e": 515, "s": 53, "text": "Matplotlib is a Python library that offers us various functions using which we can plot our data and visualize it graphically. But often plotting a graph using the Matplotlib library, we get ticks in our plot which are marked by default on both sides of the plot on the x and y-axis. There can be cases when we don’t want to show these ticks in our plot. Matplotlib.pyplot library offers us a tick_params() method using which we can remove these ticks manually." }, { "code": null, "e": 708, "s": 515, "text": "The tick_params() function accepts some attributes that take Boolean values which can be used to remove ticks and labels on the plot. By default, the values in this attribute are set to True," }, { "code": null, "e": 748, "s": 708, "text": "Let’s understand this using an example:" }, { "code": null, "e": 755, "s": 748, "text": "Python" }, { "code": "# importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint(\"Points on x-axis are: \",X_axis)print(\"Points on y-axis are: \",Y_axis) # Creating a default plotplt.figure(figsize=(8,6))plt.plot(X_axis,Y_axis)plt.scatter(X_axis,Y_axis)plt.show()", "e": 1195, "s": 755, "text": null }, { "code": null, "e": 1203, "s": 1195, "text": "Output:" }, { "code": null, "e": 1268, "s": 1203, "text": "Points on x-axis are: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]" }, { "code": null, "e": 1338, "s": 1268, "text": "Points on y-axis are: [25, 45, 65, 85, 105, 125, 145, 165, 185, 205]" }, { "code": null, "e": 1389, "s": 1338, "text": "default plot made using matplotlib including ticks" }, { "code": null, "e": 1487, "s": 1389, "text": "By viewing the above image, we can observe by default Matplotlib marks ticks on the x and y-axis." }, { "code": null, "e": 1558, "s": 1487, "text": "Case 1.1: When we want to remove ticks on a single axis (here y-axis):" }, { "code": null, "e": 1773, "s": 1558, "text": "To remove the ticks on the y-axis, tick_params() method has an attribute named left and we can set its value to False and pass it as a parameter inside the tick_params() function. It removes the tick on the y-axis." }, { "code": null, "e": 1780, "s": 1773, "text": "Python" }, { "code": "# importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint(\"Points on x-axis are: \", X_axis)print(\"Points on y-axis are: \", Y_axis) plt.figure(figsize = ( 8, 6))plt.tick_params(left = False)plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show()", "e": 2232, "s": 1780, "text": null }, { "code": null, "e": 2240, "s": 2232, "text": "Output:" }, { "code": null, "e": 2309, "s": 2240, "text": "plot made after using tick_params() method to remove ticks on y-axis" }, { "code": null, "e": 2380, "s": 2309, "text": "Case 1.2: When we want to remove ticks on a single axis (here x-axis):" }, { "code": null, "e": 2602, "s": 2380, "text": "To remove the ticks on the x-axis, tick_params() method accepts an attribute named bottom, and we can set its value to False and pass it as a parameter inside the tick_params() function. It removes the tick on the x-axis." }, { "code": null, "e": 2609, "s": 2602, "text": "Python" }, { "code": "# importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint(\"Points on x-axis are: \", X_axis)print(\"Points on y-axis are: \", Y_axis) plt.figure(figsize = (8, 6))plt.tick_params(bottom = False)plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show()", "e": 3062, "s": 2609, "text": null }, { "code": null, "e": 3070, "s": 3062, "text": "Output:" }, { "code": null, "e": 3139, "s": 3070, "text": "plot made after using tick_params() method to remove ticks on x-axis" }, { "code": null, "e": 3213, "s": 3139, "text": "Case 2: Removing these ticks on both the axes using tick_params() method:" }, { "code": null, "e": 3493, "s": 3213, "text": "To remove the ticks on both the x-axis and y-axis simultaneously, we can pass both left and right attributes simultaneously setting its value to False and pass it as a parameter inside the tick_params() function. It removes the ticks on both x-axis and the y-axis simultaneously." }, { "code": null, "e": 3500, "s": 3493, "text": "Python" }, { "code": "# importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint(\"Points on x-axis are: \", X_axis)print(\"Points on y-axis are: \", Y_axis) plt.figure(figsize = (8,6))plt.tick_params(left = False, bottom = False)plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show()", "e": 3966, "s": 3500, "text": null }, { "code": null, "e": 3974, "s": 3966, "text": "Output:" }, { "code": null, "e": 4054, "s": 3974, "text": "plot made after using tick_params() method to remove ticks on both x and y-axis" }, { "code": null, "e": 4126, "s": 4054, "text": "Case 3: When we want to remove both ticks and labels from both the axes" }, { "code": null, "e": 4469, "s": 4126, "text": "To remove both ticks and labels from both the axes simultaneously, apart from setting both left and right attributes to False, we will also use two additional attributes for labels which are- labelleft and labelbottom and we will set its value to False and pass it inside the tick_params() function. It will remove labels from both axes also." }, { "code": null, "e": 4477, "s": 4469, "text": "Python3" }, { "code": "# importing matplotlib libraryimport matplotlib.pyplot as plt # making points to be plotted on x-axis and y-axisX_axis = [i for i in range (10, 110, 10)]Y_axis = [2*j+5 for j in range (10, 110, 10)] # printing points to be plotted on the x and y-axisprint(\"Points on x-axis are: \", X_axis)print(\"Points on y-axis are: \", Y_axis) plt.figure(figsize = (8,6))plt.tick_params(left = False, right = False , labelleft = False , labelbottom = False, bottom = False) plt.plot(X_axis, Y_axis)plt.scatter(X_axis, Y_axis)plt.show()", "e": 5017, "s": 4477, "text": null }, { "code": null, "e": 5025, "s": 5017, "text": "Output:" }, { "code": null, "e": 5117, "s": 5025, "text": "plot made after using tick_params() method to remove ticks and labels on both x and y-axis" }, { "code": null, "e": 5124, "s": 5117, "text": "Picked" }, { "code": null, "e": 5142, "s": 5124, "text": "Python-matplotlib" }, { "code": null, "e": 5149, "s": 5142, "text": "Python" }, { "code": null, "e": 5247, "s": 5149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5265, "s": 5247, "text": "Python Dictionary" }, { "code": null, "e": 5307, "s": 5265, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5329, "s": 5307, "text": "Enumerate() in Python" }, { "code": null, "e": 5364, "s": 5329, "text": "Read a file line by line in Python" }, { "code": null, "e": 5390, "s": 5364, "text": "Python String | replace()" }, { "code": null, "e": 5422, "s": 5390, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5451, "s": 5422, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5478, "s": 5451, "text": "Python Classes and Objects" }, { "code": null, "e": 5508, "s": 5478, "text": "Iterate over a list in Python" } ]
Send mail with attachment from your Gmail account using Python
In this article, we will see how we can send email with attachments using Python. To send mail, we do not need any external library. There is a module called SMTPlib, which comes with Python. It uses SMTP (Simple Mail Transfer Protocol) to send the mail. It creates SMTP client session objects for mailing. SMTP needs valid source and destination email ids, and port numbers. The port number varies for different sites. As an example, for google the port is 587. At first we need to import the module to send mail. import smtplib Here we are also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using MIME header, we can store the sender and receiver information and some other details. MIME is also needed to set the attachment with the mail. We are using Google's Gmail service to send mail. So we need some settings (if required) for google's security purposes. If those settings are not set up, then the following code may not work, if the google doesnot support the access from third-party app. To allow the access, we need to set 'Less Secure App Access' settings in the google account. If the two step verification is on, we cannot use the less secure access. To complete this setup, go to the Google's Admin Console, and search for the Less Secure App setup. Create MIME Add sender, receiver address into the MIME Add the mail title into the MIME Attach the body into the MIME Open the file as binary mode, which is going to be attached with the mail Read the byte stream and encode the attachment using base64 encoding scheme. Add header for the attachments Start the SMTP session with valid port number with proper security features. Login to the system. Send mail and exit import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders mail_content = '''Hello, This is a test mail. In this mail we are sending some attachments. The mail is sent using Python SMTP library. Thank You ''' #The mail addresses and password sender_address = 'sender123@gmail.com' sender_pass = 'xxxxxxxx' receiver_address = 'receiver567@gmail.com' #Setup the MIME message = MIMEMultipart() message['From'] = sender_address message['To'] = receiver_address message['Subject'] = 'A test mail sent by Python. It has an attachment.' #The subject line #The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) attach_file_name = 'TP_python_prev.pdf' attach_file = open(attach_file_name, 'rb') # Open the file as binary mode payload = MIMEBase('application', 'octate-stream') payload.set_payload((attach_file).read()) encoders.encode_base64(payload) #encode the attachment #add payload header with filename payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name) message.attach(payload) #Create SMTP session for sending the mail session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port session.starttls() #enable security session.login(sender_address, sender_pass) #login with mail_id and password text = message.as_string() session.sendmail(sender_address, receiver_address, text) session.quit() print('Mail Sent') D:\Python TP\Python 450\linux>python 327.Send_Mail.py Mail Sent
[ { "code": null, "e": 1494, "s": 1187, "text": "In this article, we will see how we can send email with attachments using Python. To send mail, we do not need any external library. There is a module called SMTPlib, which comes with Python. It uses SMTP (Simple Mail Transfer Protocol) to send the mail. It creates SMTP client session objects for mailing." }, { "code": null, "e": 1650, "s": 1494, "text": "SMTP needs valid source and destination email ids, and port numbers. The port number varies for different sites. As an example, for google the port is 587." }, { "code": null, "e": 1702, "s": 1650, "text": "At first we need to import the module to send mail." }, { "code": null, "e": 1718, "s": 1702, "text": "import smtplib\n" }, { "code": null, "e": 1971, "s": 1718, "text": "Here we are also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using MIME header, we can store the sender and receiver information and some other details. MIME is also needed to set the attachment with the mail." }, { "code": null, "e": 2227, "s": 1971, "text": "We are using Google's Gmail service to send mail. So we need some settings (if required) for google's security purposes. If those settings are not set up, then the following code may not work, if the google doesnot support the access from third-party app." }, { "code": null, "e": 2394, "s": 2227, "text": "To allow the access, we need to set 'Less Secure App Access' settings in the google account. If the two step verification is on, we cannot use the less secure access." }, { "code": null, "e": 2494, "s": 2394, "text": "To complete this setup, go to the Google's Admin Console, and search for the Less Secure App setup." }, { "code": null, "e": 2506, "s": 2494, "text": "Create MIME" }, { "code": null, "e": 2549, "s": 2506, "text": "Add sender, receiver address into the MIME" }, { "code": null, "e": 2582, "s": 2549, "text": "Add the mail title into the MIME" }, { "code": null, "e": 2612, "s": 2582, "text": "Attach the body into the MIME" }, { "code": null, "e": 2686, "s": 2612, "text": "Open the file as binary mode, which is going to be attached with the mail" }, { "code": null, "e": 2763, "s": 2686, "text": "Read the byte stream and encode the attachment using base64 encoding scheme." }, { "code": null, "e": 2794, "s": 2763, "text": "Add header for the attachments" }, { "code": null, "e": 2871, "s": 2794, "text": "Start the SMTP session with valid port number with proper security features." }, { "code": null, "e": 2892, "s": 2871, "text": "Login to the system." }, { "code": null, "e": 2911, "s": 2892, "text": "Send mail and exit" }, { "code": null, "e": 4398, "s": 2911, "text": "import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nmail_content = '''Hello,\nThis is a test mail.\nIn this mail we are sending some attachments.\nThe mail is sent using Python SMTP library.\nThank You\n'''\n#The mail addresses and password\nsender_address = 'sender123@gmail.com'\nsender_pass = 'xxxxxxxx'\nreceiver_address = 'receiver567@gmail.com'\n#Setup the MIME\nmessage = MIMEMultipart()\nmessage['From'] = sender_address\nmessage['To'] = receiver_address\nmessage['Subject'] = 'A test mail sent by Python. It has an attachment.'\n#The subject line\n#The body and the attachments for the mail\nmessage.attach(MIMEText(mail_content, 'plain'))\nattach_file_name = 'TP_python_prev.pdf'\nattach_file = open(attach_file_name, 'rb') # Open the file as binary mode\npayload = MIMEBase('application', 'octate-stream')\npayload.set_payload((attach_file).read())\nencoders.encode_base64(payload) #encode the attachment\n#add payload header with filename\npayload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)\nmessage.attach(payload)\n#Create SMTP session for sending the mail\nsession = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port\nsession.starttls() #enable security\nsession.login(sender_address, sender_pass) #login with mail_id and password\ntext = message.as_string()\nsession.sendmail(sender_address, receiver_address, text)\nsession.quit()\nprint('Mail Sent')" }, { "code": null, "e": 4463, "s": 4398, "text": "D:\\Python TP\\Python 450\\linux>python 327.Send_Mail.py\nMail Sent\n" } ]
Reading contents of a Text File in R Programming – read.table() Function
19 Jun, 2020 read.table() function in R Language is used to read data from a text file. It returns the data in the form of a table. Syntax:read.table(filename, header = FALSE, sep = β€œβ€) Parameters:header: represents if the file contains header row or notsep: represents the delimiter value used in file Example 1: Reading data from same directory # R program to read a text file # Get content into a data frame data <- read.table("TextFileExample.txt", header = FALSE, sep = " ") # Printing content of Text File print(data) Output: V1 V2 V3 1 100 A a 2 200 B b 3 300 C c 4 400 D d 5 500 E e 6 600 F f Example 2: Reading data from different directory # R program to read a text file # Reading data from another directory x<-read.table("D://Data//myfile.txt", header = FALSE) # print x print(x) Output: V1 V2 V3 1 100 a1 b1 2 200 a2 b2 3 300 a3 b3 R-FileHandling R-Functions 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 How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jun, 2020" }, { "code": null, "e": 147, "s": 28, "text": "read.table() function in R Language is used to read data from a text file. It returns the data in the form of a table." }, { "code": null, "e": 201, "s": 147, "text": "Syntax:read.table(filename, header = FALSE, sep = β€œβ€)" }, { "code": null, "e": 318, "s": 201, "text": "Parameters:header: represents if the file contains header row or notsep: represents the delimiter value used in file" }, { "code": null, "e": 362, "s": 318, "text": "Example 1: Reading data from same directory" }, { "code": "# R program to read a text file # Get content into a data frame data <- read.table(\"TextFileExample.txt\", header = FALSE, sep = \" \") # Printing content of Text File print(data) ", "e": 566, "s": 362, "text": null }, { "code": null, "e": 574, "s": 566, "text": "Output:" }, { "code": null, "e": 659, "s": 574, "text": " V1 V2 V3\n1 100 A a\n2 200 B b\n3 300 C c\n4 400 D d\n5 500 E e\n6 600 F f\n" }, { "code": null, "e": 708, "s": 659, "text": "Example 2: Reading data from different directory" }, { "code": "# R program to read a text file # Reading data from another directory x<-read.table(\"D://Data//myfile.txt\", header = FALSE) # print x print(x) ", "e": 857, "s": 708, "text": null }, { "code": null, "e": 865, "s": 857, "text": "Output:" }, { "code": null, "e": 914, "s": 865, "text": " V1 V2 V3\n1 100 a1 b1\n2 200 a2 b2\n3 300 a3 b3\n" }, { "code": null, "e": 929, "s": 914, "text": "R-FileHandling" }, { "code": null, "e": 941, "s": 929, "text": "R-Functions" }, { "code": null, "e": 952, "s": 941, "text": "R Language" }, { "code": null, "e": 1050, "s": 952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1102, "s": 1050, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1160, "s": 1102, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1195, "s": 1160, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1233, "s": 1195, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1250, "s": 1233, "text": "R - if statement" }, { "code": null, "e": 1287, "s": 1250, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1336, "s": 1287, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1379, "s": 1336, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1416, "s": 1379, "text": "How to import an Excel File into R ?" } ]
How to Create Large Music Datasets Using Spotipy | by Max Hilsdorf | Towards Data Science
Are you a music lover or a programmer? Chances are, you’re both, just like me! When I started using Spotipy, I had little programming experience and wanted to explore computational audio analysis. Now, as I’m knee-deep into programming and Data Science, I’m starting to appreciate Spotipy for creating amazing datasets for my data science projects. you are a data scientist or programmer wanting to generate interesting datasets for machine learning you are a musician/musicologist wanting to learn programming or data analysis Spotipy is a Python library that makes it easier for users to access the Spotify Web API and retrieve all kinds of music data from it. When I started using Spotipy, it was the first time I ever got in touch with an API. Therefore, if you have never used API’s, don’t worry. You can do it! Work with your own user data (create or edit your playlists, find your favorite tracks etc.)Get data for every track, album, and artist on Spotify Work with your own user data (create or edit your playlists, find your favorite tracks etc.) Get data for every track, album, and artist on Spotify In this guide, we’ll explore the possibilities of the latter application. I’m going to show you how to use this data to create amazing datasets for statistical analyses or machine learning projects. As Spotify has over 50 Million songs, the possibilities to create large datasets are endless. On top, you’ll be able to retrieve the data very quickly, once you’ve set up the basics.In the domain of music, there are so many amazing applications of machine learning that you can explore. Has predicing Titanic survivors gotten boring? How about you build a genre classifier, a recommender system, or a hit song predictor? To my ear, that sounds much cooler. As Spotify has over 50 Million songs, the possibilities to create large datasets are endless. On top, you’ll be able to retrieve the data very quickly, once you’ve set up the basics. In the domain of music, there are so many amazing applications of machine learning that you can explore. Has predicing Titanic survivors gotten boring? How about you build a genre classifier, a recommender system, or a hit song predictor? To my ear, that sounds much cooler. Caught your interest? Great! After reading this story, you are able to create your first music dataset with a huge sample size (1k, 10k, 100k? You decide!). To make this easy for you, I’ll guide you through the 3 steps you need to take to get there. This is the hard part, but stick with me. We’ll be coding soon! In order to use the Spotify Web API, you’ll need to register an application at https://developer.spotify.com/. It doesn’t matter if you are actually building an application or just exploring the API. These are your 3 steps to success: Login with your Spotify account or register one for free at https://developer.spotify.com/dashboard/loginGo to your Dashboard and click β€œCreate a Client ID” Login with your Spotify account or register one for free at https://developer.spotify.com/dashboard/login Go to your Dashboard and click β€œCreate a Client ID” Here, you come up with an application name (it doesn’t matter what you call it) and a description for it. When I created mine, I was just being honest and wrote that I just wanted to explore the API with my app. It worked for me. 3. Open your app view and click β€œEdit Settings”. Enter http://localhost/ in the Redirect URLs field. 4. Go back to your app view and click β€œShow Client Secret” just under your Client ID. 5. Store the Client ID and the Client Secret ID in a text file or something to quickly access them later. We’ll need them for the authorization in Spotipy. In case my way of explaining wasn’t helpful to you, I recommend you check out different resources for this part. A great introduction is this article by Max Tingle. In case the last part was a bit confusing or annoying for you, be sure that you’ll be through the boring part in just a handful lines of code. First, you’ll need to make two imports. Install spotipy using the command β€œpip install spotipy” first, if you haven’t already. First, you’ll need to make two imports. Install spotipy using the command β€œpip install spotipy” first, if you haven’t already. import spotipyimport spotipy.util as util 2. Next, assign your Client and Secret ID to variables. CLIENT_ID = "YourClientID"CLIENT_SECRET = "YourSecretID" 3. I won’t go through the next lines of code in detail. I suggest you copy-paste them and learn more later. token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)cache_token = token.get_access_token()sp = spotipy.Spotify(cache_token) Great! Now, you’ll get started with analyzing some actual music in step 2. Now that the Spotify API lies at your feet, what are you gonna do with it? As suggested earlier, analyzing a big number of tracks makes for a great dataset. However, hand selecting every single track would be painful. You’ll need some collection or list of tracks. Two options that proved useful in my personal experience are searching for tracks by playlist or artist. Both have their pros and cons which I will go over quickly before we get into the real analysis. How big do playlists get? This beauty above has 10,000 songs, which seems like the maximum playlist size Spotify allows for. Maybe you want to use the β€œBiggest Playlist Ever” playlist with 5,000 songs , too. Look around and you’ll find many of these large playlists which you can use to build a large dataset quickly. However, you’ve got to ask yourself what your actual research interest is. Will this collection of 15,000 be of any use to anyone? Maybe you want to use such a dataset to investigate how some audio features are distributed on Spotify? Another way would be to choose playlists based on a theme. You could take the first 20 search results for playlists with the word β€œsleep” in their title. Maybe you want to compare the songs in β€œsleep” playlists to songs in β€œconcentration” playlists to find out in which ways they differ. I have used this approach before to analyze whether romance and heartbreak songs differ musically (which they don’t, surprisingly). If you have selected the playlists that are interesting to you, make sure to store their creators username as well as the playlist id. You can retrieve the ID from the url as seen below. Another way to select music would be through their artist. I’ve used this approach before to build a machine learning model that assigned the music from the newly released Tool album β€œFear Inoculum” to the correct band out of 6 progressive metal/rock bands. In that case, you’re dealing with low sample sizes, however. There are few artists with multiple hundreds of songs available, not to mention thousands. Spotify has a β€œrecommended artists” feature, however. You might want to use it to increase your sample sizes while still using similar music. Once you’ve chosen a couple of artists, store their artist ID in the same way you did with the playlist ID before. For step 3, I’m going to show you how you could go about analyzing music from playlists. You are encouraged to try out how to do this via artist yourself. Feel free to ask me any questions, as well. Let’s get into some actual coding. The basic Spotipy function to retrieve information for every track in a playlist is: sp.user_playlist_tracks("username", "playlist_id") Let’s use the β€œWarum Fuzzy Feeling” Playlist by Spotify for this example. Taking the ID from the url, we can now apply the function. sp.user_playlist_tracks("spotify", "37i9dQZF1DX5IDTimEWoTd") The output is overwhelming and, at first glance, totally uncomprehensible for anyone not used to dealing with APIs. This is some of the output. While I highly encourage you to explore the output yourself, I won’t go in depth on this here and simply show you which features you want and where you can find them. If you do want to explore the output yourself, it’s useful to treat it like a collection of multiple dictionaries nested inside each other. These are the kinds of features we can extract from the output. Metainformation (Artist, Album, Track Name, Track ID)Acoustic Parameters (Loudness, Key, Mode, Tempo)Psychoacoustic Parameters (Danceability, Energy, Instrumentalness, Liveness, Valence) Metainformation (Artist, Album, Track Name, Track ID) Acoustic Parameters (Loudness, Key, Mode, Tempo) Psychoacoustic Parameters (Danceability, Energy, Instrumentalness, Liveness, Valence) Spotify has some great resources for finding out more about the features we can extract (see figure below). Learn more here. Because this is an introductory article, I am going to show you the extraction function with only brief explanations of how exactly it works. Create an empty dataframe with all relevant columnsStore sp.user_playlist_tracks(β€œusername”, β€œplaylist_id”) to a β€œplaylist” variableLoop through every track in the playlistCreate an empty dict to fill with track informationExtract metadata directlyExtract audio features through sp.audio_features(track_id)Concatenate the track_dict onto the existing dataframeReturn the final dataframe Create an empty dataframe with all relevant columns Store sp.user_playlist_tracks(β€œusername”, β€œplaylist_id”) to a β€œplaylist” variable Loop through every track in the playlist Create an empty dict to fill with track information Extract metadata directly Extract audio features through sp.audio_features(track_id) Concatenate the track_dict onto the existing dataframe Return the final dataframe Here is the function as pure code. You can find the entire code from this tutorial in a more appealing format in this github repository. def analyze_playlist(creator, playlist_id): # Create empty dataframe playlist_features_list = ["artist","album","track_name", "track_id","danceability","energy","key","loudness","mode", "speechiness","instrumentalness","liveness","valence","tempo", "duration_ms","time_signature"] playlist_df = pd.DataFrame(columns = playlist_features_list) # Loop through every track in the playlist, extract features and append the features to the playlist df playlist = sp.user_playlist_tracks(creator, playlist_id)["items"] for track in playlist: # Create empty dict playlist_features = {} # Get metadata playlist_features["artist"] = track["track"]["album"]["artists"][0]["name"] playlist_features["album"] = track["track"]["album"]["name"] playlist_features["track_name"] = track["track"]["name"] playlist_features["track_id"] = track["track"]["id"] # Get audio features audio_features = sp.audio_features(playlist_features["track_id"])[0] for feature in playlist_features_list[4:]: playlist_features[feature] = audio_features[feature] # Concat the dfs track_df = pd.DataFrame(playlist_features, index = [0]) playlist_df = pd.concat([playlist_df, track_df], ignore_index = True) return playlist_df At this point, you can copy my function, edit it, or explore the API youself. In any case, the function above returns a dataframe, which can easily be converted into any data format you want. # csvdf.to_csv("dataframe.csv", index = False)# exceldf.to_excel("dataframe.xlsx", index = False) Lastly, I’m going to show you how you can create a dataframe containing multiple playlists. You can use the following function for this task. It analyzes every single playlist, adds a β€œplaylist” column with the playlist name. Lastly, the function concatenates the old and new dataframe. def analyze_playlist_dict(playlist_dict): # Loop through every playlist in the dict and analyze it for i, (key, val) in enumerate(playlist_dict.items()): playlist_df = analyze_playlist(*val) # Add a playlist column so that we can see which playlist a track belongs too playlist_df["playlist"] = key # Create or concat df if i == 0: playlist_dict_df = playlist_df else: playlist_dict_df = pd.concat([playlist_dict_df, playlist_df], ignore_index = True) return playlist_dict_df However, you’ll need to organize your playlists in a certain format in order for the function to work. As you can see below, you’ll need to store the playlists in a dictionary with the playlist names as keys and their creator and playlist id as values in the form of a tuple. playlist_dict = { β€œwarm_fuzzy_feeling” : (β€œspotify”, β€œ37i9dQZF1DX5IDTimEWoTd”), β€œlove_songs_heart” : (β€œindiemono”, β€œ5KbTzqKBqxQRD8OBtJTZrS”), β€œromance_songs” : (β€œSusan Doles”, β€œ7sAUK3XK8NHH1s5vGcTBkF”)} Let’s see what happens if we run the function. multiple_playlist_df = analyze_playlist_dict(playlist_dict)multiple_playlist_df["playlist"].value_counts() Output: love_songs_heart 100romance_songs 77warm_fuzzy_feeling 70Name: playlist, dtype: int64 As you can see, using this method, you can easily analyze 20 large playlists and get multiple thousands of track analyses. Keep in mind, however, that you’ll need to do some data cleaning. Especially, checking for duplicates will be an important step to take. You’ve got your first music dataset now, but what to do next? Here are some ideas: Analyze playlists for different genres, moods, or activities. Store each groups playlist (f.e. β€œSad” vs. β€œHappy”) in a separate dataframe. Then, use logistic regression, decision trees, or deep learning approaches like neural networks or random forests to build a classification algorithm. Analyze music based on different artists instead of based on playlists. You’ll find the following two functions useful for this: sp.audio_analysis(track_id)sp.audio_features(track_id) Build a recommender system that recommends a user music based on a genre, mood, or activity input. Thank you for reading this article! If anything is missing or doesn’t work for you, feel free to message me.
[ { "code": null, "e": 521, "s": 172, "text": "Are you a music lover or a programmer? Chances are, you’re both, just like me! When I started using Spotipy, I had little programming experience and wanted to explore computational audio analysis. Now, as I’m knee-deep into programming and Data Science, I’m starting to appreciate Spotipy for creating amazing datasets for my data science projects." }, { "code": null, "e": 622, "s": 521, "text": "you are a data scientist or programmer wanting to generate interesting datasets for machine learning" }, { "code": null, "e": 700, "s": 622, "text": "you are a musician/musicologist wanting to learn programming or data analysis" }, { "code": null, "e": 989, "s": 700, "text": "Spotipy is a Python library that makes it easier for users to access the Spotify Web API and retrieve all kinds of music data from it. When I started using Spotipy, it was the first time I ever got in touch with an API. Therefore, if you have never used API’s, don’t worry. You can do it!" }, { "code": null, "e": 1136, "s": 989, "text": "Work with your own user data (create or edit your playlists, find your favorite tracks etc.)Get data for every track, album, and artist on Spotify" }, { "code": null, "e": 1229, "s": 1136, "text": "Work with your own user data (create or edit your playlists, find your favorite tracks etc.)" }, { "code": null, "e": 1284, "s": 1229, "text": "Get data for every track, album, and artist on Spotify" }, { "code": null, "e": 1483, "s": 1284, "text": "In this guide, we’ll explore the possibilities of the latter application. I’m going to show you how to use this data to create amazing datasets for statistical analyses or machine learning projects." }, { "code": null, "e": 1940, "s": 1483, "text": "As Spotify has over 50 Million songs, the possibilities to create large datasets are endless. On top, you’ll be able to retrieve the data very quickly, once you’ve set up the basics.In the domain of music, there are so many amazing applications of machine learning that you can explore. Has predicing Titanic survivors gotten boring? How about you build a genre classifier, a recommender system, or a hit song predictor? To my ear, that sounds much cooler." }, { "code": null, "e": 2123, "s": 1940, "text": "As Spotify has over 50 Million songs, the possibilities to create large datasets are endless. On top, you’ll be able to retrieve the data very quickly, once you’ve set up the basics." }, { "code": null, "e": 2398, "s": 2123, "text": "In the domain of music, there are so many amazing applications of machine learning that you can explore. Has predicing Titanic survivors gotten boring? How about you build a genre classifier, a recommender system, or a hit song predictor? To my ear, that sounds much cooler." }, { "code": null, "e": 2648, "s": 2398, "text": "Caught your interest? Great! After reading this story, you are able to create your first music dataset with a huge sample size (1k, 10k, 100k? You decide!). To make this easy for you, I’ll guide you through the 3 steps you need to take to get there." }, { "code": null, "e": 2947, "s": 2648, "text": "This is the hard part, but stick with me. We’ll be coding soon! In order to use the Spotify Web API, you’ll need to register an application at https://developer.spotify.com/. It doesn’t matter if you are actually building an application or just exploring the API. These are your 3 steps to success:" }, { "code": null, "e": 3104, "s": 2947, "text": "Login with your Spotify account or register one for free at https://developer.spotify.com/dashboard/loginGo to your Dashboard and click β€œCreate a Client ID”" }, { "code": null, "e": 3210, "s": 3104, "text": "Login with your Spotify account or register one for free at https://developer.spotify.com/dashboard/login" }, { "code": null, "e": 3262, "s": 3210, "text": "Go to your Dashboard and click β€œCreate a Client ID”" }, { "code": null, "e": 3492, "s": 3262, "text": "Here, you come up with an application name (it doesn’t matter what you call it) and a description for it. When I created mine, I was just being honest and wrote that I just wanted to explore the API with my app. It worked for me." }, { "code": null, "e": 3593, "s": 3492, "text": "3. Open your app view and click β€œEdit Settings”. Enter http://localhost/ in the Redirect URLs field." }, { "code": null, "e": 3679, "s": 3593, "text": "4. Go back to your app view and click β€œShow Client Secret” just under your Client ID." }, { "code": null, "e": 3835, "s": 3679, "text": "5. Store the Client ID and the Client Secret ID in a text file or something to quickly access them later. We’ll need them for the authorization in Spotipy." }, { "code": null, "e": 4000, "s": 3835, "text": "In case my way of explaining wasn’t helpful to you, I recommend you check out different resources for this part. A great introduction is this article by Max Tingle." }, { "code": null, "e": 4143, "s": 4000, "text": "In case the last part was a bit confusing or annoying for you, be sure that you’ll be through the boring part in just a handful lines of code." }, { "code": null, "e": 4270, "s": 4143, "text": "First, you’ll need to make two imports. Install spotipy using the command β€œpip install spotipy” first, if you haven’t already." }, { "code": null, "e": 4397, "s": 4270, "text": "First, you’ll need to make two imports. Install spotipy using the command β€œpip install spotipy” first, if you haven’t already." }, { "code": null, "e": 4439, "s": 4397, "text": "import spotipyimport spotipy.util as util" }, { "code": null, "e": 4495, "s": 4439, "text": "2. Next, assign your Client and Secret ID to variables." }, { "code": null, "e": 4552, "s": 4495, "text": "CLIENT_ID = \"YourClientID\"CLIENT_SECRET = \"YourSecretID\"" }, { "code": null, "e": 4660, "s": 4552, "text": "3. I won’t go through the next lines of code in detail. I suggest you copy-paste them and learn more later." }, { "code": null, "e": 4826, "s": 4660, "text": "token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)cache_token = token.get_access_token()sp = spotipy.Spotify(cache_token)" }, { "code": null, "e": 4901, "s": 4826, "text": "Great! Now, you’ll get started with analyzing some actual music in step 2." }, { "code": null, "e": 5368, "s": 4901, "text": "Now that the Spotify API lies at your feet, what are you gonna do with it? As suggested earlier, analyzing a big number of tracks makes for a great dataset. However, hand selecting every single track would be painful. You’ll need some collection or list of tracks. Two options that proved useful in my personal experience are searching for tracks by playlist or artist. Both have their pros and cons which I will go over quickly before we get into the real analysis." }, { "code": null, "e": 5921, "s": 5368, "text": "How big do playlists get? This beauty above has 10,000 songs, which seems like the maximum playlist size Spotify allows for. Maybe you want to use the β€œBiggest Playlist Ever” playlist with 5,000 songs , too. Look around and you’ll find many of these large playlists which you can use to build a large dataset quickly. However, you’ve got to ask yourself what your actual research interest is. Will this collection of 15,000 be of any use to anyone? Maybe you want to use such a dataset to investigate how some audio features are distributed on Spotify?" }, { "code": null, "e": 6341, "s": 5921, "text": "Another way would be to choose playlists based on a theme. You could take the first 20 search results for playlists with the word β€œsleep” in their title. Maybe you want to compare the songs in β€œsleep” playlists to songs in β€œconcentration” playlists to find out in which ways they differ. I have used this approach before to analyze whether romance and heartbreak songs differ musically (which they don’t, surprisingly)." }, { "code": null, "e": 6528, "s": 6341, "text": "If you have selected the playlists that are interesting to you, make sure to store their creators username as well as the playlist id. You can retrieve the ID from the url as seen below." }, { "code": null, "e": 7080, "s": 6528, "text": "Another way to select music would be through their artist. I’ve used this approach before to build a machine learning model that assigned the music from the newly released Tool album β€œFear Inoculum” to the correct band out of 6 progressive metal/rock bands. In that case, you’re dealing with low sample sizes, however. There are few artists with multiple hundreds of songs available, not to mention thousands. Spotify has a β€œrecommended artists” feature, however. You might want to use it to increase your sample sizes while still using similar music." }, { "code": null, "e": 7195, "s": 7080, "text": "Once you’ve chosen a couple of artists, store their artist ID in the same way you did with the playlist ID before." }, { "code": null, "e": 7394, "s": 7195, "text": "For step 3, I’m going to show you how you could go about analyzing music from playlists. You are encouraged to try out how to do this via artist yourself. Feel free to ask me any questions, as well." }, { "code": null, "e": 7514, "s": 7394, "text": "Let’s get into some actual coding. The basic Spotipy function to retrieve information for every track in a playlist is:" }, { "code": null, "e": 7565, "s": 7514, "text": "sp.user_playlist_tracks(\"username\", \"playlist_id\")" }, { "code": null, "e": 7639, "s": 7565, "text": "Let’s use the β€œWarum Fuzzy Feeling” Playlist by Spotify for this example." }, { "code": null, "e": 7698, "s": 7639, "text": "Taking the ID from the url, we can now apply the function." }, { "code": null, "e": 7759, "s": 7698, "text": "sp.user_playlist_tracks(\"spotify\", \"37i9dQZF1DX5IDTimEWoTd\")" }, { "code": null, "e": 7903, "s": 7759, "text": "The output is overwhelming and, at first glance, totally uncomprehensible for anyone not used to dealing with APIs. This is some of the output." }, { "code": null, "e": 8210, "s": 7903, "text": "While I highly encourage you to explore the output yourself, I won’t go in depth on this here and simply show you which features you want and where you can find them. If you do want to explore the output yourself, it’s useful to treat it like a collection of multiple dictionaries nested inside each other." }, { "code": null, "e": 8274, "s": 8210, "text": "These are the kinds of features we can extract from the output." }, { "code": null, "e": 8461, "s": 8274, "text": "Metainformation (Artist, Album, Track Name, Track ID)Acoustic Parameters (Loudness, Key, Mode, Tempo)Psychoacoustic Parameters (Danceability, Energy, Instrumentalness, Liveness, Valence)" }, { "code": null, "e": 8515, "s": 8461, "text": "Metainformation (Artist, Album, Track Name, Track ID)" }, { "code": null, "e": 8564, "s": 8515, "text": "Acoustic Parameters (Loudness, Key, Mode, Tempo)" }, { "code": null, "e": 8650, "s": 8564, "text": "Psychoacoustic Parameters (Danceability, Energy, Instrumentalness, Liveness, Valence)" }, { "code": null, "e": 8775, "s": 8650, "text": "Spotify has some great resources for finding out more about the features we can extract (see figure below). Learn more here." }, { "code": null, "e": 8917, "s": 8775, "text": "Because this is an introductory article, I am going to show you the extraction function with only brief explanations of how exactly it works." }, { "code": null, "e": 9304, "s": 8917, "text": "Create an empty dataframe with all relevant columnsStore sp.user_playlist_tracks(β€œusername”, β€œplaylist_id”) to a β€œplaylist” variableLoop through every track in the playlistCreate an empty dict to fill with track informationExtract metadata directlyExtract audio features through sp.audio_features(track_id)Concatenate the track_dict onto the existing dataframeReturn the final dataframe" }, { "code": null, "e": 9356, "s": 9304, "text": "Create an empty dataframe with all relevant columns" }, { "code": null, "e": 9438, "s": 9356, "text": "Store sp.user_playlist_tracks(β€œusername”, β€œplaylist_id”) to a β€œplaylist” variable" }, { "code": null, "e": 9479, "s": 9438, "text": "Loop through every track in the playlist" }, { "code": null, "e": 9531, "s": 9479, "text": "Create an empty dict to fill with track information" }, { "code": null, "e": 9557, "s": 9531, "text": "Extract metadata directly" }, { "code": null, "e": 9616, "s": 9557, "text": "Extract audio features through sp.audio_features(track_id)" }, { "code": null, "e": 9671, "s": 9616, "text": "Concatenate the track_dict onto the existing dataframe" }, { "code": null, "e": 9698, "s": 9671, "text": "Return the final dataframe" }, { "code": null, "e": 9835, "s": 9698, "text": "Here is the function as pure code. You can find the entire code from this tutorial in a more appealing format in this github repository." }, { "code": null, "e": 11187, "s": 9835, "text": "def analyze_playlist(creator, playlist_id): # Create empty dataframe playlist_features_list = [\"artist\",\"album\",\"track_name\", \"track_id\",\"danceability\",\"energy\",\"key\",\"loudness\",\"mode\", \"speechiness\",\"instrumentalness\",\"liveness\",\"valence\",\"tempo\", \"duration_ms\",\"time_signature\"] playlist_df = pd.DataFrame(columns = playlist_features_list) # Loop through every track in the playlist, extract features and append the features to the playlist df playlist = sp.user_playlist_tracks(creator, playlist_id)[\"items\"] for track in playlist: # Create empty dict playlist_features = {} # Get metadata playlist_features[\"artist\"] = track[\"track\"][\"album\"][\"artists\"][0][\"name\"] playlist_features[\"album\"] = track[\"track\"][\"album\"][\"name\"] playlist_features[\"track_name\"] = track[\"track\"][\"name\"] playlist_features[\"track_id\"] = track[\"track\"][\"id\"] # Get audio features audio_features = sp.audio_features(playlist_features[\"track_id\"])[0] for feature in playlist_features_list[4:]: playlist_features[feature] = audio_features[feature] # Concat the dfs track_df = pd.DataFrame(playlist_features, index = [0]) playlist_df = pd.concat([playlist_df, track_df], ignore_index = True) return playlist_df" }, { "code": null, "e": 11379, "s": 11187, "text": "At this point, you can copy my function, edit it, or explore the API youself. In any case, the function above returns a dataframe, which can easily be converted into any data format you want." }, { "code": null, "e": 11477, "s": 11379, "text": "# csvdf.to_csv(\"dataframe.csv\", index = False)# exceldf.to_excel(\"dataframe.xlsx\", index = False)" }, { "code": null, "e": 11569, "s": 11477, "text": "Lastly, I’m going to show you how you can create a dataframe containing multiple playlists." }, { "code": null, "e": 11764, "s": 11569, "text": "You can use the following function for this task. It analyzes every single playlist, adds a β€œplaylist” column with the playlist name. Lastly, the function concatenates the old and new dataframe." }, { "code": null, "e": 12329, "s": 11764, "text": "def analyze_playlist_dict(playlist_dict): # Loop through every playlist in the dict and analyze it for i, (key, val) in enumerate(playlist_dict.items()): playlist_df = analyze_playlist(*val) # Add a playlist column so that we can see which playlist a track belongs too playlist_df[\"playlist\"] = key # Create or concat df if i == 0: playlist_dict_df = playlist_df else: playlist_dict_df = pd.concat([playlist_dict_df, playlist_df], ignore_index = True) return playlist_dict_df" }, { "code": null, "e": 12605, "s": 12329, "text": "However, you’ll need to organize your playlists in a certain format in order for the function to work. As you can see below, you’ll need to store the playlists in a dictionary with the playlist names as keys and their creator and playlist id as values in the form of a tuple." }, { "code": null, "e": 12809, "s": 12605, "text": "playlist_dict = { β€œwarm_fuzzy_feeling” : (β€œspotify”, β€œ37i9dQZF1DX5IDTimEWoTd”), β€œlove_songs_heart” : (β€œindiemono”, β€œ5KbTzqKBqxQRD8OBtJTZrS”), β€œromance_songs” : (β€œSusan Doles”, β€œ7sAUK3XK8NHH1s5vGcTBkF”)}" }, { "code": null, "e": 12856, "s": 12809, "text": "Let’s see what happens if we run the function." }, { "code": null, "e": 12963, "s": 12856, "text": "multiple_playlist_df = analyze_playlist_dict(playlist_dict)multiple_playlist_df[\"playlist\"].value_counts()" }, { "code": null, "e": 12971, "s": 12963, "text": "Output:" }, { "code": null, "e": 13075, "s": 12971, "text": "love_songs_heart 100romance_songs 77warm_fuzzy_feeling 70Name: playlist, dtype: int64" }, { "code": null, "e": 13335, "s": 13075, "text": "As you can see, using this method, you can easily analyze 20 large playlists and get multiple thousands of track analyses. Keep in mind, however, that you’ll need to do some data cleaning. Especially, checking for duplicates will be an important step to take." }, { "code": null, "e": 13418, "s": 13335, "text": "You’ve got your first music dataset now, but what to do next? Here are some ideas:" }, { "code": null, "e": 13708, "s": 13418, "text": "Analyze playlists for different genres, moods, or activities. Store each groups playlist (f.e. β€œSad” vs. β€œHappy”) in a separate dataframe. Then, use logistic regression, decision trees, or deep learning approaches like neural networks or random forests to build a classification algorithm." }, { "code": null, "e": 13837, "s": 13708, "text": "Analyze music based on different artists instead of based on playlists. You’ll find the following two functions useful for this:" }, { "code": null, "e": 13892, "s": 13837, "text": "sp.audio_analysis(track_id)sp.audio_features(track_id)" }, { "code": null, "e": 13991, "s": 13892, "text": "Build a recommender system that recommends a user music based on a genre, mood, or activity input." } ]
Download All Free Textbooks from Springer using Python | by Joe T. Santhanavanich | Towards Data Science
Good news to all data scientists and researchersπŸŽ‰πŸŽ‰ Springer has announced to give hundreds of expensive books on Science and technology worth thousands of dollars available for free download during this COVID-19 lockdown. Over more than 500 textbooks are available! If you are interested only in some of these books, you may download them one by one. But this chance won’t happen often, what about getting them all?😊 Download manually yourself would be boring and tiresome. Why don’t let Python do this job for you?πŸ€” According to this post, these Spring textbooks are only available until the end of July. The golden time might be extended according to the pandemic situation... This article will show you how to automatically download all Springer textbooks from the list table using Python with a step-by-step guide. So, no worry if you are new to programming or Python. Proof: As you can see, only 11 lines of Python script can download all these textbooks for you in some minutes. After you read this article, you will able to do this process yourself and able to apply this technique to download a list of any items or files in the future too. ✌ The coronavirus outbreak is having an unprecedented impact on education, putting particular strain on academics and their students. In the midst of much uncertainty and rapidly changing information, we know many educators are working to make the transition to a virtual classroom environment, finding ways to engage with students online and make sure they have the resources they need to continue their studies. To try and ease the tremendous pressure which is being put on academia right now, Springer Nature has made a range of essential textbooks from all disciplines freely available to help support students and instructors worldwide. [1] Niels Peter Thomas, Managing Director Springer Nature Books, said: β€œAs the global impact of the crisis intensifies, remote access to educational resources has become essential. We want to support lecturers, teachers and students during this challenging period and hope that this initiative, which will see over 500 key textbooks available for free online, will go some way to help.” [2] Now, let’s take a look at how we can use Python to do this job! First, let’s prepare all requirements for your python. If you don't have Python in your PC yet, you may download it at the official site here. Please, prepare Python libraries using pipby opening your command line and using the following commands: $ pip install pandas$ pip install wget$ pip install requests$ pip install xlrd After the installation is done, create a project folder and download an excel list of the available free textbooks from Springer (Free+English+textbooks.xlsx) here. The link URL may change over time and you can find an updated version of this excel sheet at this page and click the link β€œFree English textbook titles” as a figure below. Then, create a Python file download_textbooks.py and prepare the folder named download inside the project folder. Inside our project folder will look like this: Then, edit the download_textbook.py using the editor you like and adding the following lines to import Python modules and to load Springer textbook excel into the pandas dataframe. And let’s explore it by using df.head(10)command to check the first 10 rows of dataframe. import requestsimport wgetimport pandas as pddf = pd.read_excel("Free+English+textbooks.xlsx")print(df.head(10)) In this dataframe, the main columns we need at the moment are β€œBook Title” and β€œEdition” for forming a filename, and β€œOpenURL” to get a download link. So our plan now is to loop through the excel list in each row using for loop. What shall we do for each loop: Create a filename variable for each book by β€œBook Title” and β€œEdition” column. Please note that we can use any mixture of columns to generate the file name. Download a book using wget command and give a name with filename variable. So we can convert this plan to Python Script: for index, row in df.iterrows(): file_name = f"{row.loc['Book Title']}_{row.loc['Edition']}" url = f"{row.loc['OpenURL']}" wget.download(download_url, f"./download/{file_name}.pdf") Looks good, right? However, this method would not work because the β€œOpenURL” column does not directly represent the final URL for downloading PDF files yet. So, we need to change this OpenURL to the correct endpoint URL. For example, if we open the link of one textbook from β€œOpenURL” column on our web browser: 1.http://link.springer.com/openurl?genre=book&isbn=978-0-306-48048-5 Oh, it is redirected! 🀨 It is automatically redirected to 2.https://link.springer.com/book/10.1007%2Fb100747 Then if we click on the download PDF button in the website, the real endpoint PDF file will be: 3.https://link.springer.com/content/pdf/10.1007%2F0-387-36274-6.pdf That means we should convert from 1. to 3. first in each loop! So, additional steps we should do in the for loop are Open the link from the β€œOpenURL” column. Get the redirected URL: I found the simplest to do this is to use request module. Reformat the structure of the URL string to be the endpoint URL for downloading the PDF file. We can do it using str.replace(old,new) . Download a book using wget as planned. Then, the overall Python codes would look like this: After you run the Python script with python download_textbooks.py , you would get all the textbooks in your download folder. So, that’s about it. I hope you enjoy this article and able to apply this idea to automate some of your workflows in the future. Please, note that there are several ways to do this with Python as several modules can get the job done. Feel free to share with me if you have some questions, comments, or suggestions. Be Safe and Healthy! Thank you for Reading. πŸ‘‹πŸ˜„ [1] Lucy Frisch, Here’s how you can access textbooks for free during the coronavirus lockdown (Apr 16, 2020), Springer Nature [2] Felicitas Behrendt, Springer Nature Group, Springer Nature makes key textbooks freely accessible for educators, students and academics affected by coronavirus lockdown (2020), Springer Nature
[ { "code": null, "e": 438, "s": 172, "text": "Good news to all data scientists and researchersπŸŽ‰πŸŽ‰ Springer has announced to give hundreds of expensive books on Science and technology worth thousands of dollars available for free download during this COVID-19 lockdown. Over more than 500 textbooks are available!" }, { "code": null, "e": 851, "s": 438, "text": "If you are interested only in some of these books, you may download them one by one. But this chance won’t happen often, what about getting them all?😊 Download manually yourself would be boring and tiresome. Why don’t let Python do this job for you?πŸ€” According to this post, these Spring textbooks are only available until the end of July. The golden time might be extended according to the pandemic situation..." }, { "code": null, "e": 1045, "s": 851, "text": "This article will show you how to automatically download all Springer textbooks from the list table using Python with a step-by-step guide. So, no worry if you are new to programming or Python." }, { "code": null, "e": 1052, "s": 1045, "text": "Proof:" }, { "code": null, "e": 1323, "s": 1052, "text": "As you can see, only 11 lines of Python script can download all these textbooks for you in some minutes. After you read this article, you will able to do this process yourself and able to apply this technique to download a list of any items or files in the future too. ✌" }, { "code": null, "e": 1967, "s": 1323, "text": "The coronavirus outbreak is having an unprecedented impact on education, putting particular strain on academics and their students. In the midst of much uncertainty and rapidly changing information, we know many educators are working to make the transition to a virtual classroom environment, finding ways to engage with students online and make sure they have the resources they need to continue their studies. To try and ease the tremendous pressure which is being put on academia right now, Springer Nature has made a range of essential textbooks from all disciplines freely available to help support students and instructors worldwide. [1]" }, { "code": null, "e": 2354, "s": 1967, "text": "Niels Peter Thomas, Managing Director Springer Nature Books, said: β€œAs the global impact of the crisis intensifies, remote access to educational resources has become essential. We want to support lecturers, teachers and students during this challenging period and hope that this initiative, which will see over 500 key textbooks available for free online, will go some way to help.” [2]" }, { "code": null, "e": 2418, "s": 2354, "text": "Now, let’s take a look at how we can use Python to do this job!" }, { "code": null, "e": 2561, "s": 2418, "text": "First, let’s prepare all requirements for your python. If you don't have Python in your PC yet, you may download it at the official site here." }, { "code": null, "e": 2666, "s": 2561, "text": "Please, prepare Python libraries using pipby opening your command line and using the following commands:" }, { "code": null, "e": 2745, "s": 2666, "text": "$ pip install pandas$ pip install wget$ pip install requests$ pip install xlrd" }, { "code": null, "e": 2910, "s": 2745, "text": "After the installation is done, create a project folder and download an excel list of the available free textbooks from Springer (Free+English+textbooks.xlsx) here." }, { "code": null, "e": 3082, "s": 2910, "text": "The link URL may change over time and you can find an updated version of this excel sheet at this page and click the link β€œFree English textbook titles” as a figure below." }, { "code": null, "e": 3243, "s": 3082, "text": "Then, create a Python file download_textbooks.py and prepare the folder named download inside the project folder. Inside our project folder will look like this:" }, { "code": null, "e": 3514, "s": 3243, "text": "Then, edit the download_textbook.py using the editor you like and adding the following lines to import Python modules and to load Springer textbook excel into the pandas dataframe. And let’s explore it by using df.head(10)command to check the first 10 rows of dataframe." }, { "code": null, "e": 3627, "s": 3514, "text": "import requestsimport wgetimport pandas as pddf = pd.read_excel(\"Free+English+textbooks.xlsx\")print(df.head(10))" }, { "code": null, "e": 3856, "s": 3627, "text": "In this dataframe, the main columns we need at the moment are β€œBook Title” and β€œEdition” for forming a filename, and β€œOpenURL” to get a download link. So our plan now is to loop through the excel list in each row using for loop." }, { "code": null, "e": 3888, "s": 3856, "text": "What shall we do for each loop:" }, { "code": null, "e": 4045, "s": 3888, "text": "Create a filename variable for each book by β€œBook Title” and β€œEdition” column. Please note that we can use any mixture of columns to generate the file name." }, { "code": null, "e": 4120, "s": 4045, "text": "Download a book using wget command and give a name with filename variable." }, { "code": null, "e": 4166, "s": 4120, "text": "So we can convert this plan to Python Script:" }, { "code": null, "e": 4357, "s": 4166, "text": "for index, row in df.iterrows(): file_name = f\"{row.loc['Book Title']}_{row.loc['Edition']}\" url = f\"{row.loc['OpenURL']}\" wget.download(download_url, f\"./download/{file_name}.pdf\")" }, { "code": null, "e": 4669, "s": 4357, "text": "Looks good, right? However, this method would not work because the β€œOpenURL” column does not directly represent the final URL for downloading PDF files yet. So, we need to change this OpenURL to the correct endpoint URL. For example, if we open the link of one textbook from β€œOpenURL” column on our web browser:" }, { "code": null, "e": 4738, "s": 4669, "text": "1.http://link.springer.com/openurl?genre=book&isbn=978-0-306-48048-5" }, { "code": null, "e": 4796, "s": 4738, "text": "Oh, it is redirected! 🀨 It is automatically redirected to" }, { "code": null, "e": 4847, "s": 4796, "text": "2.https://link.springer.com/book/10.1007%2Fb100747" }, { "code": null, "e": 4943, "s": 4847, "text": "Then if we click on the download PDF button in the website, the real endpoint PDF file will be:" }, { "code": null, "e": 5011, "s": 4943, "text": "3.https://link.springer.com/content/pdf/10.1007%2F0-387-36274-6.pdf" }, { "code": null, "e": 5128, "s": 5011, "text": "That means we should convert from 1. to 3. first in each loop! So, additional steps we should do in the for loop are" }, { "code": null, "e": 5169, "s": 5128, "text": "Open the link from the β€œOpenURL” column." }, { "code": null, "e": 5251, "s": 5169, "text": "Get the redirected URL: I found the simplest to do this is to use request module." }, { "code": null, "e": 5387, "s": 5251, "text": "Reformat the structure of the URL string to be the endpoint URL for downloading the PDF file. We can do it using str.replace(old,new) ." }, { "code": null, "e": 5426, "s": 5387, "text": "Download a book using wget as planned." }, { "code": null, "e": 5479, "s": 5426, "text": "Then, the overall Python codes would look like this:" }, { "code": null, "e": 5604, "s": 5479, "text": "After you run the Python script with python download_textbooks.py , you would get all the textbooks in your download folder." }, { "code": null, "e": 5919, "s": 5604, "text": "So, that’s about it. I hope you enjoy this article and able to apply this idea to automate some of your workflows in the future. Please, note that there are several ways to do this with Python as several modules can get the job done. Feel free to share with me if you have some questions, comments, or suggestions." }, { "code": null, "e": 5940, "s": 5919, "text": "Be Safe and Healthy!" }, { "code": null, "e": 5966, "s": 5940, "text": "Thank you for Reading. πŸ‘‹πŸ˜„" }, { "code": null, "e": 6092, "s": 5966, "text": "[1] Lucy Frisch, Here’s how you can access textbooks for free during the coronavirus lockdown (Apr 16, 2020), Springer Nature" } ]
jQuery - siblings( [selector] ) Method
The siblings( [selector] ) method gets a set of elements containing all of the unique siblings of each of the matched set of elements. Here is the simple syntax to use this method βˆ’ selector.siblings( [selector] ) Here is the description of all the parameters used by this method βˆ’ selector βˆ’ This is optional selector to filter the sibling Elements with. selector βˆ’ This is optional selector to filter the sibling Elements with. Following is a simple example a simple showing the usage of this method βˆ’ <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function(){ $("p").siblings('.selected').addClass("hilight"); }); </script> <style> .hilight { background:yellow; } </style> </head> <body> <div><span>Hello</span></div> <p class = "selected">Hello Again</p> <p>And Again</p> </body> </html> This will produce following result βˆ’ Hello Again And Again Following is a simple example a simple showing the usage of this method βˆ’ <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function(){ $("p").siblings('.selected').addClass("hilight"); }); </script> <style> .hilight { background:yellow; } </style> </head> <body> <div><span>Hello</span></div> <p class = "hilight">Hello Again</p> <p>And Again</p> </body> </html> This will produce following result βˆ’ Hello Again And Again 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2457, "s": 2322, "text": "The siblings( [selector] ) method gets a set of elements containing all of the unique siblings of each of the matched set of elements." }, { "code": null, "e": 2504, "s": 2457, "text": "Here is the simple syntax to use this method βˆ’" }, { "code": null, "e": 2537, "s": 2504, "text": "selector.siblings( [selector] )\n" }, { "code": null, "e": 2605, "s": 2537, "text": "Here is the description of all the parameters used by this method βˆ’" }, { "code": null, "e": 2679, "s": 2605, "text": "selector βˆ’ This is optional selector to filter the sibling Elements with." }, { "code": null, "e": 2753, "s": 2679, "text": "selector βˆ’ This is optional selector to filter the sibling Elements with." }, { "code": null, "e": 2827, "s": 2753, "text": "Following is a simple example a simple showing the usage of this method βˆ’" }, { "code": null, "e": 3438, "s": 2827, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function(){\n $(\"p\").siblings('.selected').addClass(\"hilight\");\n });\n </script>\n\t\t\n <style>\n .hilight { background:yellow; }\n </style>\n </head>\n\t\n <body>\n <div><span>Hello</span></div>\n <p class = \"selected\">Hello Again</p>\n <p>And Again</p>\n </body>\n</html>" }, { "code": null, "e": 3475, "s": 3438, "text": "This will produce following result βˆ’" }, { "code": null, "e": 3487, "s": 3475, "text": "Hello Again" }, { "code": null, "e": 3497, "s": 3487, "text": "And Again" }, { "code": null, "e": 3571, "s": 3497, "text": "Following is a simple example a simple showing the usage of this method βˆ’" }, { "code": null, "e": 4181, "s": 3571, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function(){\n $(\"p\").siblings('.selected').addClass(\"hilight\");\n });\n </script>\n\t\t\n <style>\n .hilight { background:yellow; }\n </style>\n </head>\n\t\n <body>\n <div><span>Hello</span></div>\n <p class = \"hilight\">Hello Again</p>\n <p>And Again</p>\n </body>\n</html>" }, { "code": null, "e": 4218, "s": 4181, "text": "This will produce following result βˆ’" }, { "code": null, "e": 4230, "s": 4218, "text": "Hello Again" }, { "code": null, "e": 4240, "s": 4230, "text": "And Again" }, { "code": null, "e": 4273, "s": 4240, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4287, "s": 4273, "text": " Mahesh Kumar" }, { "code": null, "e": 4322, "s": 4287, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4336, "s": 4322, "text": " Pratik Singh" }, { "code": null, "e": 4371, "s": 4336, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4388, "s": 4371, "text": " Frahaan Hussain" }, { "code": null, "e": 4421, "s": 4388, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4449, "s": 4421, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4482, "s": 4449, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4503, "s": 4482, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4535, "s": 4503, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4552, "s": 4535, "text": " Laurence Svekis" }, { "code": null, "e": 4559, "s": 4552, "text": " Print" }, { "code": null, "e": 4570, "s": 4559, "text": " Add Notes" } ]
Find the Maximum Flow | Practice | GeeksforGeeks
Given a graph which represents a flow network with N vertices numbered 1 to N and M edges.Find the maximum flow from vertex numbered 1 to vertex numbered N. In a flow network,every edge has a flow capacity and the maximum flow of a path can't exceed the flow-capacity of an edge in the path. Example 1: Input: N = 5, M = 4 Edges[]= {{1,2,1},{3,2,2},{4,2,3},{2,5,5}} Output: 1 Explanation: 1 - 2 - 3 / \ 4 5 1 unit can flow from 1 -> 2 - >5 Example 2: Input: N = 4, M = 4 Edges[] = {{1,2,8},{1,3,10},{4,2,2},{3,4,3}} Output: 5 Explanation: 1 - 2 | | 3 - 4 3 unit can flow from 1 -> 3 -> 4 2 unit can flow from 1 -> 2 -> 4 Total max flow from 1 to N = 3+2=5 Your Task: You don't need to read input or print anything. Your task is to complete the function solve() which takes the N (the number of vertices) ,M (the number of Edges) and the array Edges[] (Where Edges[i] denoting an undirected edge between Edges[i][0] and Edges[i][1] with a flow capacity of Edges[i][2]), and returns the integer denoting the maximum flow from 1 to N. Expected Time Complexity: O(max_flow*M) Expected Auxiliary Space: O(N+M) Where max_flow is the maximum flow from 1 to N Constraints: 1 <= N,M,Edges[i][2] <= 1000 1 <= Edges[i][0],Edges[i][1] <= N 0 vinaykumarjonnada1 week ago ALERT , THERE MIGHT BE DIFFERENT WEIGHTS BETWEEN THE SAME EDGES, SO ADD ALL THE WEIGHTS 1β†’6 WEIGHT = 9 AND THEY ALSO GIVEN 6β†’1 WEIGHT = 7 6 101 6 9 3 2 7 6 1 7 5 1 2 5 3 2 5 4 5 3 2 8 2 2 8 3 5 9 2 3 3 +1 dipeshmishra6261 week ago what is wrong with gfg? u don't know how to describe a question? how can sm1 solve a question by knowing half question? I have seen maxm hard problems in graphs on gfg are half explained . it is not necessary to give 1000s of ques on a topic but when u post a ques make sure it is posted with good description.Thank u. +2 akshitasinghal44443 weeks ago C++ int bfs(int source,int sink,vector<vector<int>> &g,int n,vector<int> &parent) { queue<pair<int,int>> q; vector<bool> vis(n,0); q.push({source, INT_MAX}); vis[source]=1; while(!q.empty()) { source=q.front().first; int cap=q.front().second; q.pop(); for(int i=0;i<n;i++) { if(g[source][i] && !vis[i]) { parent[i]=source; if(i==sink) return min(cap,g[source][i]); q.push({i,min(cap,g[source][i])}); vis[i]=1; } } } return 0; } int ford_fulkerson(int source,int sink,vector<vector<int>> &g,int n) { int flow=0; vector<int> parent(n,-1); int min_cap; while(min_cap=bfs(source,sink,g,n,parent)) { flow+=min_cap; int u,v=sink; while(v!=source) { u=parent[v]; g[u][v]-=min_cap; g[v][u]+=min_cap; v=u; } } return flow; } int solve(int n,int m,vector<vector<int>> e) { vector<vector<int>> g(n+1,vector<int>(n+1,0)); int i; for(i=0;i<m;i++) { g[e[i][0]][e[i][1]]+=e[i][2]; g[e[i][1]][e[i][0]]+=e[i][2]; } return ford_fulkerson(1,n,g,n+1); } +2 pyatasandeep3 weeks ago Worst ever question explanation I've ever seen :/ 0 wjyjobs3 weeks ago class Solution: def solve(self, N, M, Edges): # graph is matrix: dim is the name of node and val is the capacity graph = [[0]*N for _ in range(N)] for (frm, to, flow) in Edges: graph[frm-1][to-1] += flow graph[to-1][frm-1] += flow def bfs(s, t, parent): q = [(s, float('inf'))] while q: cur, flow = q.pop(0) for nxt, capacity in enumerate(graph[cur]): if parent[nxt] is None and capacity > 0: # not visited and has capactiy parent[nxt] = cur new_flow = min(flow, capacity) if nxt == t: # find the destination return new_flow q.append((nxt, new_flow)) return 0 def maxflow(s, t): flow = 0 while True: parent = [None]*N parent[s] = -1 # to mark the start node has been visited. new_flow = bfs(s, t, parent) if new_flow == 0: break flow += new_flow # backtrack the path and update the flow graph cur = t while cur != s: prev = parent[cur] graph[prev][cur] -= new_flow graph[cur][prev] += new_flow cur = prev return flow return maxflow(0, N-1) +6 srimadhan113 weeks ago In the question, it is mentioned that the edges are undirected. But the following is one of the hidden testcase, where we can see the edges β€œ1 β†’ 6” (with flow capacity 9) and β€œ6 β†’ 1” (with flow capacity 7) are given. 6 10 1 6 9 3 2 7 6 1 7 5 1 2 5 3 2 5 4 5 3 2 8 2 2 8 3 5 9 2 3 3 Please fix the ambiguity in the question's description, or correct the testcases. -1 ravi145773 weeks ago the complete solution int BFS(vector<vector<int>> &graph,vector<int> &parent,int source,int sink,int N) { int min_cap=INT_MAX; fill(parent.begin(), parent.end(), -1); vector<bool> visited(N,false); queue<int> q; q.push(source); visited[source]=true; parent[source]=-1; while(q.empty()==false) { auto u=q.front(); q.pop(); //adjacents for(int v=0;v<N;v++) { if(visited[v]==false && graph[u][v]!=0) { if(v==sink) { parent[v]=u; min_cap=min(min_cap,graph[u][v]); return min_cap; } q.push(v); visited[v]=true; min_cap=min(min_cap,graph[u][v]); parent[v]=u; } } } return 0; } int fordFulkerson(vector<vector<int>> &graph,int source,int sink,int N) { vector<int> parent(N,-1); int res=0; while(BFS(graph,parent,source,sink,N)!=0) { int min_cap=BFS(graph,parent,source,sink,N); res+=min_cap; //considering all the edged in this path. int v=sink; while(v!=source) { int u=parent[v]; graph[u][v]-=min_cap; graph[v][u]+=min_cap; v=parent[v]; } } return res; } +4 shivambadrigupta3 weeks ago Post by @pritamkr212 NOT my post but just saving for myself so it will not get deleted REALLY GFG I WANT THE REASON WHY MY COMMENT GOT DELETED IM DOING FOR COMMUNITY AND YOU ARE DOING PARTIALITY NO WORRIES I WILL DO IT AGAIN OKAY TO SOLVED THIS QUESTION I TAKE ALMOST 3.5+HR .BECAUSE I MIGHT BE THE SLOW CODER ,SO FOR THE TIME SAVING FOR U FELLOWS JUST FOLLOW MY STEPS TO GET THIS HARD ALGO . I KNOW THIS WILL TAKE TIME BUT ATLAST YOU GOT SOMETING TO LEARN 1-β†’ https://youtu.be/NwenwITjMys WATCH AT 1.25X SPEED 2-β†’ https://youtu.be/KChvn4SNE4g WATCH AT 1.25-1.5X SPEED (WATCH LAST 4 MIN CAREFULLY) 3-β†’ https://youtu.be/w0-c8io12yY WATCH AT 1.25X SPEED 4-β†’ https://youtu.be/_aWooet7O_4 WATCH AT 1.25-1.5X SPEED (WATCH LAST 10MIN CAREFULLY) 5-β†’ AT LAST JUST GO THROUGH THE https://cp-algorithms.com/graph/edmonds_karp.html OTHER DOCUMENTATION https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ ,,,https://www.geeksforgeeks.org/max-flow-problem-introduction/ HOPE THIS COMMET DO NOT GET DELETED AGAIN class Solution { int solve(int n, int m, ArrayList<ArrayList<Integer>> edges) { int g[][] = new int[n][n]; for(int i=0;i<edges.size();i++){ int u = edges.get(i).get(0)-1; int v = edges.get(i).get(1)-1; int w = edges.get(i).get(2); g[u][v]+=w; g[v][u]+=w; } return fordfulkerson(g,0,n-1,n); } static int fordfulkerson(int[][]graph,int source,int sink,int n){ int[]parent=new int[n]; Arrays.fill(parent,-1); int res=0; while(bfs(graph,parent,source,sink,n)!=0){ int min=bfs(graph,parent,source,sink,n); res+=min; int v=sink; while(v!=source){ int u=parent[v]; graph[u][v]-=min; graph[v][u]+=min; v=u; } } return res; } static int bfs(int[][]graph,int[] parent,int source,int sink,int n){ int min=Integer.MAX_VALUE; Arrays.fill(parent,-1); parent[source]=-2; boolean[]vis=new boolean[n]; Queue<pair>q=new LinkedList<>(); q.add(new pair(source,min)); while(!q.isEmpty()){ pair curr=q.poll(); int node =curr.x; int flow=curr.y; for(int i=0;i<n;i++){ if(graph[node][i]!=0){ if(parent[i]==-1){ parent[i]=node; int new_flow=Math.min(flow,graph[node][i]); if(i==sink)return new_flow; q.add(new pair(i,new_flow)); } } } } return 0; } } class pair{ int x,y; public pair(int x,int y){ this.x=x; this.y=y; } } +7 pritamkr2123 weeks ago REALLY GFG I WANT THE REASON WHY MY COMMENT GOT DELETED IM DOING FOR COMMUNITY AND YOU ARE DOING PARTIALITY NO WORRIES I WILL DO IT AGAIN OKAY TO SOLVED THIS QUESTION I TAKE ALMOST 3.5+HR .BECAUSE I MIGHT BE THE SLOW CODER ,SO FOR THE TIME SAVING FOR U FELLOWS JUST FOLLOW MY STEPS TO GET THIS HARD ALGO . I KNOW THIS WILL TAKE TIME BUT ATLAST YOU GOT SOMETING TO LEARN 1-β†’ https://youtu.be/NwenwITjMys WATCH AT 1.25X SPEED 2-β†’ https://youtu.be/KChvn4SNE4g WATCH AT 1.25-1.5X SPEED (WATCH LAST 4 MIN CAREFULLY) 3-β†’ https://youtu.be/w0-c8io12yY WATCH AT 1.25X SPEED 4-β†’ https://youtu.be/_aWooet7O_4 WATCH AT 1.25-1.5X SPEED (WATCH LAST 10MIN CAREFULLY) 5-β†’ AT LAST JUST GO THROUGH THE https://cp-algorithms.com/graph/edmonds_karp.html OTHER DOCUMENTATION https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ ,,,https://www.geeksforgeeks.org/max-flow-problem-introduction/ HOPE THIS COMMET DO NOT GET DELETED AGAIN class Solution { int solve(int n, int m, ArrayList<ArrayList<Integer>> edges) { int g[][] = new int[n][n]; for(int i=0;i<edges.size();i++){ int u = edges.get(i).get(0)-1; int v = edges.get(i).get(1)-1; int w = edges.get(i).get(2); g[u][v]+=w; g[v][u]+=w; } return fordfulkerson(g,0,n-1,n); } static int fordfulkerson(int[][]graph,int source,int sink,int n){ int[]parent=new int[n]; Arrays.fill(parent,-1); int res=0; while(bfs(graph,parent,source,sink,n)!=0){ int min=bfs(graph,parent,source,sink,n); res+=min; int v=sink; while(v!=source){ int u=parent[v]; graph[u][v]-=min; graph[v][u]+=min; v=u; } } return res; } static int bfs(int[][]graph,int[] parent,int source,int sink,int n){ int min=Integer.MAX_VALUE; Arrays.fill(parent,-1); parent[source]=-2; boolean[]vis=new boolean[n]; Queue<pair>q=new LinkedList<>(); q.add(new pair(source,min)); while(!q.isEmpty()){ pair curr=q.poll(); int node =curr.x; int flow=curr.y; for(int i=0;i<n;i++){ if(graph[node][i]!=0){ if(parent[i]==-1){ parent[i]=node; int new_flow=Math.min(flow,graph[node][i]); if(i==sink)return new_flow; q.add(new pair(i,new_flow)); } } } } return 0; } } class pair{ int x,y; public pair(int x,int y){ this.x=x; this.y=y; } } +1 pritamkr212 This comment was deleted. 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": 395, "s": 238, "text": "Given a graph which represents a flow network with N vertices numbered 1 to N and M edges.Find the maximum flow from vertex numbered 1 to vertex numbered N." }, { "code": null, "e": 542, "s": 395, "text": "In a flow network,every edge has a flow capacity and the maximum flow of a path can't exceed the flow-capacity of an edge in the path.\n\nExample 1:" }, { "code": null, "e": 692, "s": 542, "text": "Input:\nN = 5, M = 4\nEdges[]= {{1,2,1},{3,2,2},{4,2,3},{2,5,5}}\nOutput: 1 \nExplanation: \n1 - 2 - 3\n / \\\n 4 5 \n1 unit can flow from 1 -> 2 - >5 \n" }, { "code": null, "e": 705, "s": 694, "text": "Example 2:" }, { "code": null, "e": 920, "s": 705, "text": "Input:\nN = 4, M = 4\nEdges[] = {{1,2,8},{1,3,10},{4,2,2},{3,4,3}}\nOutput: 5 \nExplanation:\n 1 - 2 \n | |\n 3 - 4\n3 unit can flow from 1 -> 3 -> 4\n2 unit can flow from 1 -> 2 -> 4\nTotal max flow from 1 to N = 3+2=5" }, { "code": null, "e": 1297, "s": 920, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function solve() which takes the N (the number of vertices) ,M (the number of Edges) and the array Edges[] (Where Edges[i] denoting an undirected edge between Edges[i][0] and Edges[i][1] with a flow capacity of Edges[i][2]), and returns the integer denoting the maximum flow from 1 to N." }, { "code": null, "e": 1370, "s": 1297, "text": "Expected Time Complexity: O(max_flow*M)\nExpected Auxiliary Space: O(N+M)" }, { "code": null, "e": 1417, "s": 1370, "text": "Where max_flow is the maximum flow from 1 to N" }, { "code": null, "e": 1493, "s": 1417, "text": "Constraints:\n1 <= N,M,Edges[i][2] <= 1000\n1 <= Edges[i][0],Edges[i][1] <= N" }, { "code": null, "e": 1495, "s": 1493, "text": "0" }, { "code": null, "e": 1523, "s": 1495, "text": "vinaykumarjonnada1 week ago" }, { "code": null, "e": 1611, "s": 1523, "text": "ALERT , THERE MIGHT BE DIFFERENT WEIGHTS BETWEEN THE SAME EDGES, SO ADD ALL THE WEIGHTS" }, { "code": null, "e": 1661, "s": 1611, "text": "1β†’6 WEIGHT = 9 AND THEY ALSO GIVEN 6β†’1 WEIGHT = 7" }, { "code": null, "e": 1725, "s": 1661, "text": "6 101 6 9 3 2 7 6 1 7 5 1 2 5 3 2 5 4 5 3 2 8 2 2 8 3 5 9 2 3 3" }, { "code": null, "e": 1728, "s": 1725, "text": "+1" }, { "code": null, "e": 1754, "s": 1728, "text": "dipeshmishra6261 week ago" }, { "code": null, "e": 2073, "s": 1754, "text": "what is wrong with gfg? u don't know how to describe a question? how can sm1 solve a question by knowing half question? I have seen maxm hard problems in graphs on gfg are half explained . it is not necessary to give 1000s of ques on a topic but when u post a ques make sure it is posted with good description.Thank u." }, { "code": null, "e": 2078, "s": 2075, "text": "+2" }, { "code": null, "e": 2108, "s": 2078, "text": "akshitasinghal44443 weeks ago" }, { "code": null, "e": 2112, "s": 2108, "text": "C++" }, { "code": null, "e": 3737, "s": 2112, "text": "int bfs(int source,int sink,vector<vector<int>> &g,int n,vector<int> &parent)\n {\n queue<pair<int,int>> q;\n vector<bool> vis(n,0);\n q.push({source, INT_MAX});\n vis[source]=1;\n \n while(!q.empty())\n {\n source=q.front().first;\n int cap=q.front().second;\n q.pop();\n \n for(int i=0;i<n;i++)\n {\n if(g[source][i] && !vis[i])\n {\n parent[i]=source;\n \n if(i==sink)\n return min(cap,g[source][i]);\n \n q.push({i,min(cap,g[source][i])});\n vis[i]=1;\n }\n }\n }\n return 0;\n }\n \nint ford_fulkerson(int source,int sink,vector<vector<int>> &g,int n)\n {\n int flow=0;\n vector<int> parent(n,-1);\n \n int min_cap;\n while(min_cap=bfs(source,sink,g,n,parent))\n {\n flow+=min_cap;\n \n int u,v=sink;\n while(v!=source)\n {\n u=parent[v];\n g[u][v]-=min_cap;\n g[v][u]+=min_cap;\n v=u;\n }\n }\n \n return flow;\n }\n \n int solve(int n,int m,vector<vector<int>> e)\n {\n vector<vector<int>> g(n+1,vector<int>(n+1,0));\n int i;\n \n for(i=0;i<m;i++)\n {\n g[e[i][0]][e[i][1]]+=e[i][2];\n g[e[i][1]][e[i][0]]+=e[i][2];\n }\n \n return ford_fulkerson(1,n,g,n+1);\n }" }, { "code": null, "e": 3740, "s": 3737, "text": "+2" }, { "code": null, "e": 3764, "s": 3740, "text": "pyatasandeep3 weeks ago" }, { "code": null, "e": 3814, "s": 3764, "text": "Worst ever question explanation I've ever seen :/" }, { "code": null, "e": 3816, "s": 3814, "text": "0" }, { "code": null, "e": 3835, "s": 3816, "text": "wjyjobs3 weeks ago" }, { "code": null, "e": 5438, "s": 3835, "text": "class Solution:\n def solve(self, N, M, Edges): \n\n # graph is matrix: dim is the name of node and val is the capacity\n graph = [[0]*N for _ in range(N)]\n for (frm, to, flow) in Edges:\n graph[frm-1][to-1] += flow\n graph[to-1][frm-1] += flow\n \n \n def bfs(s, t, parent):\n q = [(s, float('inf'))]\n \n while q:\n cur, flow = q.pop(0)\n for nxt, capacity in enumerate(graph[cur]):\n if parent[nxt] is None and capacity > 0: # not visited and has capactiy\n parent[nxt] = cur\n new_flow = min(flow, capacity)\n if nxt == t: # find the destination\n return new_flow \n q.append((nxt, new_flow))\n \n return 0\n \n def maxflow(s, t):\n flow = 0\n while True:\n parent = [None]*N\n parent[s] = -1 # to mark the start node has been visited.\n new_flow = bfs(s, t, parent)\n if new_flow == 0:\n break\n flow += new_flow\n # backtrack the path and update the flow graph\n \n cur = t\n while cur != s:\n prev = parent[cur]\n graph[prev][cur] -= new_flow\n graph[cur][prev] += new_flow\n cur = prev\n \n return flow\n \n return maxflow(0, N-1)" }, { "code": null, "e": 5441, "s": 5438, "text": "+6" }, { "code": null, "e": 5464, "s": 5441, "text": "srimadhan113 weeks ago" }, { "code": null, "e": 5681, "s": 5464, "text": "In the question, it is mentioned that the edges are undirected. But the following is one of the hidden testcase, where we can see the edges β€œ1 β†’ 6” (with flow capacity 9) and β€œ6 β†’ 1” (with flow capacity 7) are given." }, { "code": null, "e": 5746, "s": 5681, "text": "6 10\n1 6 9 3 2 7 6 1 7 5 1 2 5 3 2 5 4 5 3 2 8 2 2 8 3 5 9 2 3 3" }, { "code": null, "e": 5828, "s": 5746, "text": "Please fix the ambiguity in the question's description, or correct the testcases." }, { "code": null, "e": 5831, "s": 5828, "text": "-1" }, { "code": null, "e": 5852, "s": 5831, "text": "ravi145773 weeks ago" }, { "code": null, "e": 5875, "s": 5852, "text": "the complete solution " }, { "code": null, "e": 7454, "s": 5875, "text": "int BFS(vector<vector<int>> &graph,vector<int> &parent,int source,int sink,int N) { int min_cap=INT_MAX; fill(parent.begin(), parent.end(), -1); vector<bool> visited(N,false); queue<int> q; q.push(source); visited[source]=true; parent[source]=-1; while(q.empty()==false) { auto u=q.front(); q.pop(); //adjacents for(int v=0;v<N;v++) { if(visited[v]==false && graph[u][v]!=0) { if(v==sink) { parent[v]=u; min_cap=min(min_cap,graph[u][v]); return min_cap; } q.push(v); visited[v]=true; min_cap=min(min_cap,graph[u][v]); parent[v]=u; } } } return 0; } int fordFulkerson(vector<vector<int>> &graph,int source,int sink,int N) { vector<int> parent(N,-1); int res=0; while(BFS(graph,parent,source,sink,N)!=0) { int min_cap=BFS(graph,parent,source,sink,N); res+=min_cap; //considering all the edged in this path. int v=sink; while(v!=source) { int u=parent[v]; graph[u][v]-=min_cap; graph[v][u]+=min_cap; v=parent[v]; } } return res; }" }, { "code": null, "e": 7457, "s": 7454, "text": "+4" }, { "code": null, "e": 7485, "s": 7457, "text": "shivambadrigupta3 weeks ago" }, { "code": null, "e": 7507, "s": 7485, "text": "Post by @pritamkr212 " }, { "code": null, "e": 7573, "s": 7507, "text": "NOT my post but just saving for myself so it will not get deleted" }, { "code": null, "e": 7631, "s": 7575, "text": "REALLY GFG I WANT THE REASON WHY MY COMMENT GOT DELETED" }, { "code": null, "e": 7684, "s": 7631, "text": "IM DOING FOR COMMUNITY AND YOU ARE DOING PARTIALITY " }, { "code": null, "e": 7714, "s": 7684, "text": "NO WORRIES I WILL DO IT AGAIN" }, { "code": null, "e": 7949, "s": 7716, "text": "OKAY TO SOLVED THIS QUESTION I TAKE ALMOST 3.5+HR .BECAUSE I MIGHT BE THE SLOW CODER ,SO FOR THE TIME SAVING FOR U FELLOWS JUST FOLLOW MY STEPS TO GET THIS HARD ALGO . I KNOW THIS WILL TAKE TIME BUT ATLAST YOU GOT SOMETING TO LEARN" }, { "code": null, "e": 8005, "s": 7951, "text": "1-β†’ https://youtu.be/NwenwITjMys WATCH AT 1.25X SPEED" }, { "code": null, "e": 8092, "s": 8005, "text": "2-β†’ https://youtu.be/KChvn4SNE4g WATCH AT 1.25-1.5X SPEED (WATCH LAST 4 MIN CAREFULLY)" }, { "code": null, "e": 8148, "s": 8092, "text": "3-β†’ https://youtu.be/w0-c8io12yY WATCH AT 1.25X SPEED " }, { "code": null, "e": 8235, "s": 8148, "text": "4-β†’ https://youtu.be/_aWooet7O_4 WATCH AT 1.25-1.5X SPEED (WATCH LAST 10MIN CAREFULLY)" }, { "code": null, "e": 8319, "s": 8237, "text": "5-β†’ AT LAST JUST GO THROUGH THE https://cp-algorithms.com/graph/edmonds_karp.html" }, { "code": null, "e": 8486, "s": 8321, "text": "OTHER DOCUMENTATION https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ ,,,https://www.geeksforgeeks.org/max-flow-problem-introduction/" }, { "code": null, "e": 8530, "s": 8488, "text": "HOPE THIS COMMET DO NOT GET DELETED AGAIN" }, { "code": null, "e": 10355, "s": 8532, "text": "class Solution \n{ \n int solve(int n, int m, ArrayList<ArrayList<Integer>> edges) \n { \n int g[][] = new int[n][n];\n for(int i=0;i<edges.size();i++){\n int u = edges.get(i).get(0)-1;\n int v = edges.get(i).get(1)-1;\n int w = edges.get(i).get(2);\n g[u][v]+=w;\n g[v][u]+=w;\n }\n return fordfulkerson(g,0,n-1,n);\n }\n static int fordfulkerson(int[][]graph,int source,int sink,int n){\n int[]parent=new int[n];\n Arrays.fill(parent,-1);\n int res=0;\n while(bfs(graph,parent,source,sink,n)!=0){\n int min=bfs(graph,parent,source,sink,n);\n res+=min;\n int v=sink;\n while(v!=source){\n int u=parent[v];\n graph[u][v]-=min;\n graph[v][u]+=min;\n v=u;\n }\n }\n return res;\n }\n static int bfs(int[][]graph,int[] parent,int source,int sink,int n){\n int min=Integer.MAX_VALUE;\n Arrays.fill(parent,-1);\n parent[source]=-2;\n boolean[]vis=new boolean[n];\n Queue<pair>q=new LinkedList<>();\n q.add(new pair(source,min));\n while(!q.isEmpty()){\n pair curr=q.poll();\n int node =curr.x;\n int flow=curr.y;\n for(int i=0;i<n;i++){\n if(graph[node][i]!=0){\n if(parent[i]==-1){\n parent[i]=node;\n int new_flow=Math.min(flow,graph[node][i]);\n if(i==sink)return new_flow;\n q.add(new pair(i,new_flow));\n }\n }\n }\n }\n return 0;\n }\n}\n\n\nclass pair{\n int x,y;\n public pair(int x,int y){\n this.x=x;\n this.y=y;\n }\n}" }, { "code": null, "e": 10358, "s": 10355, "text": "+7" }, { "code": null, "e": 10381, "s": 10358, "text": "pritamkr2123 weeks ago" }, { "code": null, "e": 10437, "s": 10381, "text": "REALLY GFG I WANT THE REASON WHY MY COMMENT GOT DELETED" }, { "code": null, "e": 10490, "s": 10437, "text": "IM DOING FOR COMMUNITY AND YOU ARE DOING PARTIALITY " }, { "code": null, "e": 10520, "s": 10490, "text": "NO WORRIES I WILL DO IT AGAIN" }, { "code": null, "e": 10755, "s": 10522, "text": "OKAY TO SOLVED THIS QUESTION I TAKE ALMOST 3.5+HR .BECAUSE I MIGHT BE THE SLOW CODER ,SO FOR THE TIME SAVING FOR U FELLOWS JUST FOLLOW MY STEPS TO GET THIS HARD ALGO . I KNOW THIS WILL TAKE TIME BUT ATLAST YOU GOT SOMETING TO LEARN" }, { "code": null, "e": 10811, "s": 10757, "text": "1-β†’ https://youtu.be/NwenwITjMys WATCH AT 1.25X SPEED" }, { "code": null, "e": 10898, "s": 10811, "text": "2-β†’ https://youtu.be/KChvn4SNE4g WATCH AT 1.25-1.5X SPEED (WATCH LAST 4 MIN CAREFULLY)" }, { "code": null, "e": 10954, "s": 10898, "text": "3-β†’ https://youtu.be/w0-c8io12yY WATCH AT 1.25X SPEED " }, { "code": null, "e": 11041, "s": 10954, "text": "4-β†’ https://youtu.be/_aWooet7O_4 WATCH AT 1.25-1.5X SPEED (WATCH LAST 10MIN CAREFULLY)" }, { "code": null, "e": 11125, "s": 11043, "text": "5-β†’ AT LAST JUST GO THROUGH THE https://cp-algorithms.com/graph/edmonds_karp.html" }, { "code": null, "e": 11292, "s": 11127, "text": "OTHER DOCUMENTATION https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ ,,,https://www.geeksforgeeks.org/max-flow-problem-introduction/" }, { "code": null, "e": 11336, "s": 11294, "text": "HOPE THIS COMMET DO NOT GET DELETED AGAIN" }, { "code": null, "e": 13162, "s": 11338, "text": "class Solution \n{ \n int solve(int n, int m, ArrayList<ArrayList<Integer>> edges) \n { \n int g[][] = new int[n][n];\n for(int i=0;i<edges.size();i++){\n int u = edges.get(i).get(0)-1;\n int v = edges.get(i).get(1)-1;\n int w = edges.get(i).get(2);\n g[u][v]+=w;\n g[v][u]+=w;\n }\n return fordfulkerson(g,0,n-1,n);\n }\n static int fordfulkerson(int[][]graph,int source,int sink,int n){\n int[]parent=new int[n];\n Arrays.fill(parent,-1);\n int res=0;\n while(bfs(graph,parent,source,sink,n)!=0){\n int min=bfs(graph,parent,source,sink,n);\n res+=min;\n int v=sink;\n while(v!=source){\n int u=parent[v];\n graph[u][v]-=min;\n graph[v][u]+=min;\n v=u;\n }\n }\n return res;\n }\n static int bfs(int[][]graph,int[] parent,int source,int sink,int n){\n int min=Integer.MAX_VALUE;\n Arrays.fill(parent,-1);\n parent[source]=-2;\n boolean[]vis=new boolean[n];\n Queue<pair>q=new LinkedList<>();\n q.add(new pair(source,min));\n while(!q.isEmpty()){\n pair curr=q.poll();\n int node =curr.x;\n int flow=curr.y;\n for(int i=0;i<n;i++){\n if(graph[node][i]!=0){\n if(parent[i]==-1){\n parent[i]=node;\n int new_flow=Math.min(flow,graph[node][i]);\n if(i==sink)return new_flow;\n q.add(new pair(i,new_flow));\n }\n }\n }\n }\n return 0;\n }\n}\n\n\nclass pair{\n int x,y;\n public pair(int x,int y){\n this.x=x;\n this.y=y;\n }\n}\n" }, { "code": null, "e": 13165, "s": 13162, "text": "+1" }, { "code": null, "e": 13177, "s": 13165, "text": "pritamkr212" }, { "code": null, "e": 13203, "s": 13177, "text": "This comment was deleted." }, { "code": null, "e": 13349, "s": 13203, "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": 13385, "s": 13349, "text": " Login to access your submissions. " }, { "code": null, "e": 13395, "s": 13385, "text": "\nProblem\n" }, { "code": null, "e": 13405, "s": 13395, "text": "\nContest\n" }, { "code": null, "e": 13468, "s": 13405, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 13616, "s": 13468, "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": 13824, "s": 13616, "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": 13930, "s": 13824, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Laravel - Response
A web application responds to a user’s request in many ways depending on many parameters. This chapter explains you in detail about responses in Laravel web applications. Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response. Step 1 βˆ’ Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get('/basic_response', function () { return 'Hello World'; }); Step 2 βˆ’ Visit the following URL to test the basic response. http://localhost:8000/basic_response Step 3 βˆ’ The output will appear as shown in the following image. The response can be attached to headers using the header() method. We can also attach the series of headers as shown in the below sample code. return response($content,$status) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value'); Observe the following example to understand more about Response βˆ’ Step 1 βˆ’ Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get('/header',function() { return response("Hello", 200)->header('Content-Type', 'text/html'); }); Step 2 βˆ’ Visit the following URL to test the basic response. http://localhost:8000/header Step 3 βˆ’ The output will appear as shown in the following image. The withcookie() helper method is used to attach cookies. The cookie generated with this method can be attached by calling withcookie() method with response instance. By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. Observe the following example to understand more about attaching cookies βˆ’ Step 1 βˆ’ Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get('/cookie',function() { return response("Hello", 200)->header('Content-Type', 'text/html') ->withcookie('name','Virat Gandhi'); }); Step 2 βˆ’ Visit the following URL to test the basic response. http://localhost:8000/cookie Step 3 βˆ’ The output will appear as shown in the following image. JSON response can be sent using the json method. This method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response. Observe the following example to understand more about JSON Response βˆ’ Step 1 βˆ’ Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get('json',function() { return response()->json(['name' => 'Virat Gandhi', 'state' => 'Gujarat']); }); Step 2 βˆ’ Visit the following URL to test the json response. http://localhost:8000/json Step 3 βˆ’ The output will appear as shown in the following image. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2643, "s": 2472, "text": "A web application responds to a user’s request in many ways depending on many parameters. This chapter explains you in detail about responses in Laravel web applications." }, { "code": null, "e": 2924, "s": 2643, "text": "Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response." }, { "code": null, "e": 2985, "s": 2924, "text": "Step 1 βˆ’ Add the following code to app/Http/routes.php file." }, { "code": null, "e": 3005, "s": 2985, "text": "app/Http/routes.php" }, { "code": null, "e": 3079, "s": 3005, "text": "Route::get('/basic_response', function () {\n return 'Hello World';\n});\n" }, { "code": null, "e": 3140, "s": 3079, "text": "Step 2 βˆ’ Visit the following URL to test the basic response." }, { "code": null, "e": 3178, "s": 3140, "text": "http://localhost:8000/basic_response\n" }, { "code": null, "e": 3243, "s": 3178, "text": "Step 3 βˆ’ The output will appear as shown in the following image." }, { "code": null, "e": 3386, "s": 3243, "text": "The response can be attached to headers using the header() method. We can also attach the series of headers as shown in the below sample code." }, { "code": null, "e": 3544, "s": 3386, "text": "return response($content,$status)\n ->header('Content-Type', $type)\n ->header('X-Header-One', 'Header Value')\n ->header('X-Header-Two', 'Header Value');" }, { "code": null, "e": 3610, "s": 3544, "text": "Observe the following example to understand more about Response βˆ’" }, { "code": null, "e": 3671, "s": 3610, "text": "Step 1 βˆ’ Add the following code to app/Http/routes.php file." }, { "code": null, "e": 3691, "s": 3671, "text": "app/Http/routes.php" }, { "code": null, "e": 3800, "s": 3691, "text": "Route::get('/header',function() {\n return response(\"Hello\", 200)->header('Content-Type', 'text/html');\n});" }, { "code": null, "e": 3861, "s": 3800, "text": "Step 2 βˆ’ Visit the following URL to test the basic response." }, { "code": null, "e": 3891, "s": 3861, "text": "http://localhost:8000/header\n" }, { "code": null, "e": 3956, "s": 3891, "text": "Step 3 βˆ’ The output will appear as shown in the following image." }, { "code": null, "e": 4247, "s": 3956, "text": "The withcookie() helper method is used to attach cookies. The cookie generated with this method can be attached by calling withcookie() method with response instance. By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client." }, { "code": null, "e": 4322, "s": 4247, "text": "Observe the following example to understand more about attaching cookies βˆ’" }, { "code": null, "e": 4383, "s": 4322, "text": "Step 1 βˆ’ Add the following code to app/Http/routes.php file." }, { "code": null, "e": 4403, "s": 4383, "text": "app/Http/routes.php" }, { "code": null, "e": 4554, "s": 4403, "text": "Route::get('/cookie',function() {\n return response(\"Hello\", 200)->header('Content-Type', 'text/html')\n ->withcookie('name','Virat Gandhi');\n});" }, { "code": null, "e": 4615, "s": 4554, "text": "Step 2 βˆ’ Visit the following URL to test the basic response." }, { "code": null, "e": 4645, "s": 4615, "text": "http://localhost:8000/cookie\n" }, { "code": null, "e": 4710, "s": 4645, "text": "Step 3 βˆ’ The output will appear as shown in the following image." }, { "code": null, "e": 4924, "s": 4710, "text": "JSON response can be sent using the json method. This method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response." }, { "code": null, "e": 4995, "s": 4924, "text": "Observe the following example to understand more about JSON Response βˆ’" }, { "code": null, "e": 5056, "s": 4995, "text": "Step 1 βˆ’ Add the following line in app/Http/routes.php file." }, { "code": null, "e": 5076, "s": 5056, "text": "app/Http/routes.php" }, { "code": null, "e": 5189, "s": 5076, "text": "Route::get('json',function() {\n return response()->json(['name' => 'Virat Gandhi', 'state' => 'Gujarat']);\n});" }, { "code": null, "e": 5249, "s": 5189, "text": "Step 2 βˆ’ Visit the following URL to test the json response." }, { "code": null, "e": 5277, "s": 5249, "text": "http://localhost:8000/json\n" }, { "code": null, "e": 5342, "s": 5277, "text": "Step 3 βˆ’ The output will appear as shown in the following image." }, { "code": null, "e": 5375, "s": 5342, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 5395, "s": 5375, "text": " Sebastian Sulinski" }, { "code": null, "e": 5430, "s": 5395, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5444, "s": 5430, "text": " Antonio Papa" }, { "code": null, "e": 5478, "s": 5444, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5498, "s": 5478, "text": " Sebastian Sulinski" }, { "code": null, "e": 5531, "s": 5498, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 5551, "s": 5531, "text": " Skillbakerystudios" }, { "code": null, "e": 5586, "s": 5551, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5609, "s": 5586, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5644, "s": 5609, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 5664, "s": 5644, "text": " Hafizullah Masoudi" }, { "code": null, "e": 5671, "s": 5664, "text": " Print" }, { "code": null, "e": 5682, "s": 5671, "text": " Add Notes" } ]
Converting a 10 digit phone number to US format using Regex in Python - GeeksforGeeks
29 Dec, 2020 Text preprocessing is one of the most important tasks in Natural Language Processing. You may want to extract number from a string. Writing a manual script for such processing task requires a lot of effort and at most times it is prone to errors. Keeping in view the importance of these preprocessing tasks, the concept of Regular Expression have been developed in different programming languages in order to ease these text processing tasks. To implement Regular Expression, the python re package can be used and to be used it can be easily imported like any other inbuilt python module. Steps for converting a 10-digit phone number to its corresponding US number format: Import the python re package. Write a function that takes the phone number to be formatted as argument and processes it. Now simply call the function and pass the value. Example: Python3 import re def convert_phone_number(phone): # actual pattern which only change this line num = re.sub(r'(?<!\S)(\d{3})-', r'(\1) ', phone) return num # Driver code print(convert_phone_number("Call geek 321-963-0612")) Output: Call geek (321) 963-0612 Python Regex-programs python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n29 Dec, 2020" }, { "code": null, "e": 24655, "s": 24212, "text": "Text preprocessing is one of the most important tasks in Natural Language Processing. You may want to extract number from a string. Writing a manual script for such processing task requires a lot of effort and at most times it is prone to errors. Keeping in view the importance of these preprocessing tasks, the concept of Regular Expression have been developed in different programming languages in order to ease these text processing tasks." }, { "code": null, "e": 24801, "s": 24655, "text": "To implement Regular Expression, the python re package can be used and to be used it can be easily imported like any other inbuilt python module." }, { "code": null, "e": 24885, "s": 24801, "text": "Steps for converting a 10-digit phone number to its corresponding US number format:" }, { "code": null, "e": 24915, "s": 24885, "text": "Import the python re package." }, { "code": null, "e": 25007, "s": 24915, "text": "Write a function that takes the phone number to be formatted as argument and processes it. " }, { "code": null, "e": 25057, "s": 25007, "text": "Now simply call the function and pass the value. " }, { "code": null, "e": 25066, "s": 25057, "text": "Example:" }, { "code": null, "e": 25074, "s": 25066, "text": "Python3" }, { "code": "import re def convert_phone_number(phone): # actual pattern which only change this line num = re.sub(r'(?<!\\S)(\\d{3})-', r'(\\1) ', phone) return num # Driver code print(convert_phone_number(\"Call geek 321-963-0612\"))", "e": 25300, "s": 25074, "text": null }, { "code": null, "e": 25308, "s": 25300, "text": "Output:" }, { "code": null, "e": 25333, "s": 25308, "text": "Call geek (321) 963-0612" }, { "code": null, "e": 25355, "s": 25333, "text": "Python Regex-programs" }, { "code": null, "e": 25368, "s": 25355, "text": "python-regex" }, { "code": null, "e": 25375, "s": 25368, "text": "Python" }, { "code": null, "e": 25473, "s": 25375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25482, "s": 25473, "text": "Comments" }, { "code": null, "e": 25495, "s": 25482, "text": "Old Comments" }, { "code": null, "e": 25527, "s": 25495, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25582, "s": 25527, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25638, "s": 25582, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25677, "s": 25638, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25719, "s": 25677, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25761, "s": 25719, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25783, "s": 25761, "text": "Defaultdict in Python" }, { "code": null, "e": 25814, "s": 25783, "text": "Python | os.path.join() method" }, { "code": null, "e": 25843, "s": 25814, "text": "Create a directory in Python" } ]
How to Use the JavaScript Fetch API to Get Data? - GeeksforGeeks
20 Jul, 2021 The Task here is to show how the Fetch API can be used to get data from an API. I will be taking a fake API which will contain employee details as an example and from that API. I will show to get data by fetch() API method. fetch() method: The fetch() method is modern and versatile and is very well supported among the modern browsers. It can send network requests to the server and load new information whenever it’s needed, without reloading the browser. Syntax: The fetch() method only has one mandatory argument, which is the URL of the resource you wish to fetch.let response = fetch(api_url, [other params]) let response = fetch(api_url, [other params]) Async Await: In this example, we will be using Async Await method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers. Syntax:async function funcName(url){ const response = await fetch(url); var data = await response.json(); } async function funcName(url){ const response = await fetch(url); var data = await response.json(); } Prerequisite: Here, you will need an API for performing fetch() operation to get data from that API. You can also create an API or can take free mock APIs. Here the API I used is: This API contains employee details in the form of key : value pair.https://employeedetails.free.beeceptor.com/my/api/path Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method. Define a constant data and store the data in JSON form by await response.json() method. Now we got the data from API by fetch() method in data variable. Pass this data variable to function which will show the data fetched. Function show takes the data variable and by applying for loop on data.list and getting all the rows to show, it stores all the data to tab variable which set the innerHTML property for the class employees in HTML file. I have also added a loader which loads till response comes. JavaScript file:JavascriptJavascript// api urlconst api_url = "https://employeedetails.free.beeceptor.com/my/api/path"; // Defining async functionasync function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var data = await response.json(); console.log(data); if (response) { hideloader(); } show(data);}// Calling that async functiongetapi(api_url); // Function to hide the loaderfunction hideloader() { document.getElementById('loading').style.display = 'none';}// Function to define innerHTML for HTML tablefunction show(data) { let tab = `<tr> <th>Name</th> <th>Office</th> <th>Position</th> <th>Salary</th> </tr>`; // Loop to access all rows for (let r of data.list) { tab += `<tr> <td>${r.name} </td> <td>${r.office}</td> <td>${r.position}</td> <td>${r.salary}</td> </tr>`; } // Setting innerHTML as tab variable document.getElementById("employees").innerHTML = tab;} Javascript // api urlconst api_url = "https://employeedetails.free.beeceptor.com/my/api/path"; // Defining async functionasync function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var data = await response.json(); console.log(data); if (response) { hideloader(); } show(data);}// Calling that async functiongetapi(api_url); // Function to hide the loaderfunction hideloader() { document.getElementById('loading').style.display = 'none';}// Function to define innerHTML for HTML tablefunction show(data) { let tab = `<tr> <th>Name</th> <th>Office</th> <th>Position</th> <th>Salary</th> </tr>`; // Loop to access all rows for (let r of data.list) { tab += `<tr> <td>${r.name} </td> <td>${r.office}</td> <td>${r.position}</td> <td>${r.salary}</td> </tr>`; } // Setting innerHTML as tab variable document.getElementById("employees").innerHTML = tab;} HTML file:HTMLHTML<!DOCTYPE html><html lang="en"> <head> <script src="script.js"></script> <link rel="stylesheet" href="style.css" /> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <!-- Here a loader is created which loads till response comes --> <div class="d-flex justify-content-center"> <div class="spinner-border" role="status" id="loading"> <span class="sr-only">Loading...</span> </div> </div> <h1>Registered Employees</h1> <!-- table for showing data --> <table id="employees"></table> </body></html> HTML <!DOCTYPE html><html lang="en"> <head> <script src="script.js"></script> <link rel="stylesheet" href="style.css" /> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <!-- Here a loader is created which loads till response comes --> <div class="d-flex justify-content-center"> <div class="spinner-border" role="status" id="loading"> <span class="sr-only">Loading...</span> </div> </div> <h1>Registered Employees</h1> <!-- table for showing data --> <table id="employees"></table> </body></html> Output: In console ,data in JSON will look like this. HTML output. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. Picked Web-API JavaScript 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 append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples How to read a local text file using JavaScript? Node.js | fs.writeFileSync() Method
[ { "code": null, "e": 24792, "s": 24764, "text": "\n20 Jul, 2021" }, { "code": null, "e": 25017, "s": 24792, "text": "The Task here is to show how the Fetch API can be used to get data from an API. I will be taking a fake API which will contain employee details as an example and from that API. I will show to get data by fetch() API method. " }, { "code": null, "e": 25251, "s": 25017, "text": "fetch() method: The fetch() method is modern and versatile and is very well supported among the modern browsers. It can send network requests to the server and load new information whenever it’s needed, without reloading the browser." }, { "code": null, "e": 25408, "s": 25251, "text": "Syntax: The fetch() method only has one mandatory argument, which is the URL of the resource you wish to fetch.let response = fetch(api_url, [other params])" }, { "code": null, "e": 25454, "s": 25408, "text": "let response = fetch(api_url, [other params])" }, { "code": null, "e": 25634, "s": 25454, "text": "Async Await: In this example, we will be using Async Await method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers." }, { "code": null, "e": 25755, "s": 25634, "text": "Syntax:async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }\n" }, { "code": null, "e": 25869, "s": 25755, "text": "async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }\n" }, { "code": null, "e": 26025, "s": 25869, "text": "Prerequisite: Here, you will need an API for performing fetch() operation to get data from that API. You can also create an API or can take free mock APIs." }, { "code": null, "e": 26171, "s": 26025, "text": "Here the API I used is: This API contains employee details in the form of key : value pair.https://employeedetails.free.beeceptor.com/my/api/path" }, { "code": null, "e": 26957, "s": 26171, "text": "Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method. Define a constant data and store the data in JSON form by await response.json() method. Now we got the data from API by fetch() method in data variable. Pass this data variable to function which will show the data fetched. Function show takes the data variable and by applying for loop on data.list and getting all the rows to show, it stores all the data to tab variable which set the innerHTML property for the class employees in HTML file. I have also added a loader which loads till response comes." }, { "code": null, "e": 28041, "s": 26957, "text": "JavaScript file:JavascriptJavascript// api urlconst api_url = \"https://employeedetails.free.beeceptor.com/my/api/path\"; // Defining async functionasync function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var data = await response.json(); console.log(data); if (response) { hideloader(); } show(data);}// Calling that async functiongetapi(api_url); // Function to hide the loaderfunction hideloader() { document.getElementById('loading').style.display = 'none';}// Function to define innerHTML for HTML tablefunction show(data) { let tab = `<tr> <th>Name</th> <th>Office</th> <th>Position</th> <th>Salary</th> </tr>`; // Loop to access all rows for (let r of data.list) { tab += `<tr> <td>${r.name} </td> <td>${r.office}</td> <td>${r.position}</td> <td>${r.salary}</td> </tr>`; } // Setting innerHTML as tab variable document.getElementById(\"employees\").innerHTML = tab;}" }, { "code": null, "e": 28052, "s": 28041, "text": "Javascript" }, { "code": "// api urlconst api_url = \"https://employeedetails.free.beeceptor.com/my/api/path\"; // Defining async functionasync function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var data = await response.json(); console.log(data); if (response) { hideloader(); } show(data);}// Calling that async functiongetapi(api_url); // Function to hide the loaderfunction hideloader() { document.getElementById('loading').style.display = 'none';}// Function to define innerHTML for HTML tablefunction show(data) { let tab = `<tr> <th>Name</th> <th>Office</th> <th>Position</th> <th>Salary</th> </tr>`; // Loop to access all rows for (let r of data.list) { tab += `<tr> <td>${r.name} </td> <td>${r.office}</td> <td>${r.position}</td> <td>${r.salary}</td> </tr>`; } // Setting innerHTML as tab variable document.getElementById(\"employees\").innerHTML = tab;}", "e": 29100, "s": 28052, "text": null }, { "code": null, "e": 29869, "s": 29100, "text": "HTML file:HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"script.js\"></script> <link rel=\"stylesheet\" href=\"style.css\" /> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> </head> <body> <!-- Here a loader is created which loads till response comes --> <div class=\"d-flex justify-content-center\"> <div class=\"spinner-border\" role=\"status\" id=\"loading\"> <span class=\"sr-only\">Loading...</span> </div> </div> <h1>Registered Employees</h1> <!-- table for showing data --> <table id=\"employees\"></table> </body></html>" }, { "code": null, "e": 29874, "s": 29869, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"script.js\"></script> <link rel=\"stylesheet\" href=\"style.css\" /> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> </head> <body> <!-- Here a loader is created which loads till response comes --> <div class=\"d-flex justify-content-center\"> <div class=\"spinner-border\" role=\"status\" id=\"loading\"> <span class=\"sr-only\">Loading...</span> </div> </div> <h1>Registered Employees</h1> <!-- table for showing data --> <table id=\"employees\"></table> </body></html>", "e": 30625, "s": 29874, "text": null }, { "code": null, "e": 30633, "s": 30625, "text": "Output:" }, { "code": null, "e": 30679, "s": 30633, "text": "In console ,data in JSON will look like this." }, { "code": null, "e": 30692, "s": 30679, "text": "HTML output." }, { "code": null, "e": 30911, "s": 30692, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 30918, "s": 30911, "text": "Picked" }, { "code": null, "e": 30926, "s": 30918, "text": "Web-API" }, { "code": null, "e": 30937, "s": 30926, "text": "JavaScript" }, { "code": null, "e": 31035, "s": 30937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31075, "s": 31035, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31120, "s": 31075, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31181, "s": 31120, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31253, "s": 31181, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31305, "s": 31253, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31351, "s": 31305, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31392, "s": 31351, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31433, "s": 31392, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 31481, "s": 31433, "text": "How to read a local text file using JavaScript?" } ]
Movie Recommender System: Part 1. Learn how to build a Recommender system... | by Diven Sambhwani | Towards Data Science
All entertainment websites or online stores have millions/billions of items. It becomes challenging for the customer to select the right one. At this place, recommender systems come into the picture and help the user to find the right item by minimizing the options. What are recommender systems? It helps the user to select the right item by suggesting a presumable list of items and so it has become an integral part of e-commerce, movie and music rendering sites and the list goes on. They are becoming one of the most popular applications of machine learning which has gained importance in recent years. The two most popular ways it can be approached/built are: 1- Content-based Filtering 2- Collaborative Filtering In this post, we will be focusing on the Matrix Factorization which is a method of Collaborative filtering. Matrix Factorization In collaborative filtering, matrix factorization is the state-of-the-art solution for sparse data problems, although it has become widely known since Netflix Prize Challenge. β€œIn the case of collaborative filtering, matrix factorization algorithms work by decomposing the user-item interaction matrix into the product of two lower dimensionality rectangular matrices. One matrix can be seen as the user matrix where rows represent users and columns are latent factors. The other matrix is the item matrix where rows are latent factors and columns represent items.”- Wikipedia We will be working with MoiveLens Dataset, a movie rating dataset, to develop a recommendation system using the Surprise library β€œA Python scikit for recommender systems”. Let’s get started! ratings = pd.read_csv('data/ratings.csv')ratings.head() To load a data set from the above pandas data frame, we will use the load_from_df() method, we will also need a Reader object, and the rating_scale parameter must be specified. The data frame must have three columns, corresponding to the user ids, the item ids, and the ratings in this order. reader = Reader(rating_scale=(0.5, 5.0))data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']], reader) Rating Distribution Rating Distribution by Item Rating Distribution by User Surprise is a Python scikit building and analyzing recommender systems that deal with explicit rating data. Maintained by Nicolas Hug. With pip (you’ll need NumPy, and a C compiler. Windows users might prefer to use conda): !pip install numpy!pip install scikit-surprise#For Windows usersconda install -c conda-forge scikit-surprise We will use RMSE as our accuracy metric for the predictions. We will be comparing SVD, NMF, Normal Predictor, KNN Basic and will be using the one which will have the least RMSE value. Some understanding of the algorithms before we start applying. 1: Normal Predictor: It predicts a random rating based on the distribution of the training set, which is assumed to be normal. It’s a basic algorithm that does not do much work but that is still useful for comparing accuracies. 2: SVD: It got popularized by Simon Funk during the Netflix prize and is a Matrix Factorized algorithm. If baselines are not used, it is equivalent to PMF. 3: NMF: It is based on Non-negative matrix factorization and is similar to SVD. 4: KNN Basic: This is a basic collaborative filtering algorithm method. benchmark = []# Iterate over all algorithmsfor algorithm in [SVD(), NMF(), NormalPredictor(), KNNBasic()]:# Perform cross validationresults = cross_validate(algorithm, data, measures=['RMSE'], cv=3, verbose=False)# Get results & append algorithm nametmp = pd.DataFrame.from_dict(results).mean(axis=0)tmp = tmp.append(pd.Series([str(algorithm).split(' ')[0].split('.')[-1]],index=['Algorithm']))benchmark.append(tmp) As SVD has the least RMSE value we will tune the hyper-parameters of SVD. Tuning algorithm parameters with GridSearchCV to find the best parameters for the algorithm. Default values of SVD are : n_factors β€” 100 | n_epochs β€” 20 | lr_all β€” 0.005 | reg_all β€” 0.02 param_grid = {'n_factors': [25, 30, 35, 40, 100], 'n_epochs': [15, 20, 25], 'lr_all': [0.001, 0.003, 0.005, 0.008], 'reg_all': [0.08, 0.1, 0.15, 0.02]}gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)gs.fit(data) algo = gs.best_estimator['rmse']print(gs.best_score['rmse']) print(gs.best_params['rmse'])#Assigning valuest = gs.best_params factors = t['rmse']['n_factors']epochs = t['rmse']['n_epochs'] lr_value = t['rmse']['lr_all']reg_value = t['rmse']['reg_all'] Output: 0.8682 {β€˜n_factors’: 35, β€˜n_epochs’: 25, β€˜lr_all’: 0.008, β€˜reg_all’: 0.08} Now as we have the right set of values for our hyper-parameters, Let’s split the data into train:test and fit the model. trainset, testset = train_test_split(data, test_size=0.25)algo = SVD(n_factors=factors, n_epochs=epochs, lr_all=lr_value, reg_all=reg_value)predictions = algo.fit(trainset).test(testset)accuracy.rmse(predictions) Output: RMSE: 0.8662 The following function will create a pandas data frame which will consist of these columns: UID: user-id iid: item id Rui: the rating given by the user est: rating estimated by the model Iu: No of items rated by the user UI: number of users that have rated this item err: abs difference between predicted rating and the actual rating. def get_Iu(uid):"""args: uid: the id of the userreturns:the number of items rated by the user"""try: return len(trainset.ur[trainset.to_inner_uid(uid)])except ValueError: # user was not part of the trainset return 0def get_Ui(iid):"""args:iid: the raw id of the itemreturns:the number of users that have rated the item."""try: return len(trainset.ir[trainset.to_inner_iid(iid)])except ValueError: return 0df_predictions = pd.DataFrame(predictions, columns=['uid', 'iid', 'rui', 'est', 'details'])df_predictions['Iu'] = df_predictions.uid.apply(get_Iu)df_predictions['Ui'] = df_predictions.iid.apply(get_Ui)df_predictions['err'] = abs(df_predictions.est - df_predictions.rui) Best Predictions: best_predictions = df_predictions.sort_values(by='err')[:10] Worst predictions: worst_predictions = df_predictions.sort_values(by='err')[-10:] The worst predictions look pretty surprising. Let’s look in more details of item β€œ3996”, rated 0.5, our SVD algorithm predicts 4.4 df.loc[df['itemID'] == 3996]['rating'].describe()temp = df.loc[df['itemID'] == 3996]['rating']# Create tracetrace = go.Histogram(x = temp.values, name = 'Ratings', xbins = dict(start = 0, end = 5, size=.3))# Create layoutlayout = go.Layout(title = 'Number of ratings item 3996 has received', xaxis = dict(title = 'Number of Ratings Per Item'), yaxis = dict(title = 'Count'), bargap = 0.2)# Create plotfig = go.Figure(data=[trace], layout=layout)iplot(fig) It turns out, most of the ratings this Item received between β€œ3 and 5”, only 1% of the users rated β€œ0.5” and one β€œ2.5” below 3. It seems that for each prediction, the users are some kind of outliers and the item has been rated very few times. Looks like you’re enjoying the post! You have just read Part 1 which covered how to build a model on explicit data using Surprise library. Part 2 will cover how many movies we should recommend by calculating precision and recall at K and then recommending K movies. For the complete code, you can find the Jupyter notebook here. If you have any thoughts or suggestions please feel free to comment. You can also reach me through LinkedIn
[ { "code": null, "e": 439, "s": 172, "text": "All entertainment websites or online stores have millions/billions of items. It becomes challenging for the customer to select the right one. At this place, recommender systems come into the picture and help the user to find the right item by minimizing the options." }, { "code": null, "e": 469, "s": 439, "text": "What are recommender systems?" }, { "code": null, "e": 838, "s": 469, "text": "It helps the user to select the right item by suggesting a presumable list of items and so it has become an integral part of e-commerce, movie and music rendering sites and the list goes on. They are becoming one of the most popular applications of machine learning which has gained importance in recent years. The two most popular ways it can be approached/built are:" }, { "code": null, "e": 865, "s": 838, "text": "1- Content-based Filtering" }, { "code": null, "e": 892, "s": 865, "text": "2- Collaborative Filtering" }, { "code": null, "e": 1000, "s": 892, "text": "In this post, we will be focusing on the Matrix Factorization which is a method of Collaborative filtering." }, { "code": null, "e": 1021, "s": 1000, "text": "Matrix Factorization" }, { "code": null, "e": 1196, "s": 1021, "text": "In collaborative filtering, matrix factorization is the state-of-the-art solution for sparse data problems, although it has become widely known since Netflix Prize Challenge." }, { "code": null, "e": 1597, "s": 1196, "text": "β€œIn the case of collaborative filtering, matrix factorization algorithms work by decomposing the user-item interaction matrix into the product of two lower dimensionality rectangular matrices. One matrix can be seen as the user matrix where rows represent users and columns are latent factors. The other matrix is the item matrix where rows are latent factors and columns represent items.”- Wikipedia" }, { "code": null, "e": 1788, "s": 1597, "text": "We will be working with MoiveLens Dataset, a movie rating dataset, to develop a recommendation system using the Surprise library β€œA Python scikit for recommender systems”. Let’s get started!" }, { "code": null, "e": 1844, "s": 1788, "text": "ratings = pd.read_csv('data/ratings.csv')ratings.head()" }, { "code": null, "e": 2021, "s": 1844, "text": "To load a data set from the above pandas data frame, we will use the load_from_df() method, we will also need a Reader object, and the rating_scale parameter must be specified." }, { "code": null, "e": 2137, "s": 2021, "text": "The data frame must have three columns, corresponding to the user ids, the item ids, and the ratings in this order." }, { "code": null, "e": 2249, "s": 2137, "text": "reader = Reader(rating_scale=(0.5, 5.0))data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']], reader)" }, { "code": null, "e": 2269, "s": 2249, "text": "Rating Distribution" }, { "code": null, "e": 2297, "s": 2269, "text": "Rating Distribution by Item" }, { "code": null, "e": 2325, "s": 2297, "text": "Rating Distribution by User" }, { "code": null, "e": 2460, "s": 2325, "text": "Surprise is a Python scikit building and analyzing recommender systems that deal with explicit rating data. Maintained by Nicolas Hug." }, { "code": null, "e": 2549, "s": 2460, "text": "With pip (you’ll need NumPy, and a C compiler. Windows users might prefer to use conda):" }, { "code": null, "e": 2658, "s": 2549, "text": "!pip install numpy!pip install scikit-surprise#For Windows usersconda install -c conda-forge scikit-surprise" }, { "code": null, "e": 2719, "s": 2658, "text": "We will use RMSE as our accuracy metric for the predictions." }, { "code": null, "e": 2842, "s": 2719, "text": "We will be comparing SVD, NMF, Normal Predictor, KNN Basic and will be using the one which will have the least RMSE value." }, { "code": null, "e": 2905, "s": 2842, "text": "Some understanding of the algorithms before we start applying." }, { "code": null, "e": 3133, "s": 2905, "text": "1: Normal Predictor: It predicts a random rating based on the distribution of the training set, which is assumed to be normal. It’s a basic algorithm that does not do much work but that is still useful for comparing accuracies." }, { "code": null, "e": 3289, "s": 3133, "text": "2: SVD: It got popularized by Simon Funk during the Netflix prize and is a Matrix Factorized algorithm. If baselines are not used, it is equivalent to PMF." }, { "code": null, "e": 3369, "s": 3289, "text": "3: NMF: It is based on Non-negative matrix factorization and is similar to SVD." }, { "code": null, "e": 3441, "s": 3369, "text": "4: KNN Basic: This is a basic collaborative filtering algorithm method." }, { "code": null, "e": 3857, "s": 3441, "text": "benchmark = []# Iterate over all algorithmsfor algorithm in [SVD(), NMF(), NormalPredictor(), KNNBasic()]:# Perform cross validationresults = cross_validate(algorithm, data, measures=['RMSE'], cv=3, verbose=False)# Get results & append algorithm nametmp = pd.DataFrame.from_dict(results).mean(axis=0)tmp = tmp.append(pd.Series([str(algorithm).split(' ')[0].split('.')[-1]],index=['Algorithm']))benchmark.append(tmp)" }, { "code": null, "e": 3931, "s": 3857, "text": "As SVD has the least RMSE value we will tune the hyper-parameters of SVD." }, { "code": null, "e": 4024, "s": 3931, "text": "Tuning algorithm parameters with GridSearchCV to find the best parameters for the algorithm." }, { "code": null, "e": 4052, "s": 4024, "text": "Default values of SVD are :" }, { "code": null, "e": 4118, "s": 4052, "text": "n_factors β€” 100 | n_epochs β€” 20 | lr_all β€” 0.005 | reg_all β€” 0.02" }, { "code": null, "e": 4614, "s": 4118, "text": "param_grid = {'n_factors': [25, 30, 35, 40, 100], 'n_epochs': [15, 20, 25], 'lr_all': [0.001, 0.003, 0.005, 0.008], 'reg_all': [0.08, 0.1, 0.15, 0.02]}gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)gs.fit(data) algo = gs.best_estimator['rmse']print(gs.best_score['rmse']) print(gs.best_params['rmse'])#Assigning valuest = gs.best_params factors = t['rmse']['n_factors']epochs = t['rmse']['n_epochs'] lr_value = t['rmse']['lr_all']reg_value = t['rmse']['reg_all']" }, { "code": null, "e": 4697, "s": 4614, "text": "Output: 0.8682 {β€˜n_factors’: 35, β€˜n_epochs’: 25, β€˜lr_all’: 0.008, β€˜reg_all’: 0.08}" }, { "code": null, "e": 4818, "s": 4697, "text": "Now as we have the right set of values for our hyper-parameters, Let’s split the data into train:test and fit the model." }, { "code": null, "e": 5031, "s": 4818, "text": "trainset, testset = train_test_split(data, test_size=0.25)algo = SVD(n_factors=factors, n_epochs=epochs, lr_all=lr_value, reg_all=reg_value)predictions = algo.fit(trainset).test(testset)accuracy.rmse(predictions)" }, { "code": null, "e": 5052, "s": 5031, "text": "Output: RMSE: 0.8662" }, { "code": null, "e": 5144, "s": 5052, "text": "The following function will create a pandas data frame which will consist of these columns:" }, { "code": null, "e": 5157, "s": 5144, "text": "UID: user-id" }, { "code": null, "e": 5170, "s": 5157, "text": "iid: item id" }, { "code": null, "e": 5204, "s": 5170, "text": "Rui: the rating given by the user" }, { "code": null, "e": 5239, "s": 5204, "text": "est: rating estimated by the model" }, { "code": null, "e": 5273, "s": 5239, "text": "Iu: No of items rated by the user" }, { "code": null, "e": 5319, "s": 5273, "text": "UI: number of users that have rated this item" }, { "code": null, "e": 5387, "s": 5319, "text": "err: abs difference between predicted rating and the actual rating." }, { "code": null, "e": 6072, "s": 5387, "text": "def get_Iu(uid):\"\"\"args: uid: the id of the userreturns:the number of items rated by the user\"\"\"try: return len(trainset.ur[trainset.to_inner_uid(uid)])except ValueError: # user was not part of the trainset return 0def get_Ui(iid):\"\"\"args:iid: the raw id of the itemreturns:the number of users that have rated the item.\"\"\"try: return len(trainset.ir[trainset.to_inner_iid(iid)])except ValueError: return 0df_predictions = pd.DataFrame(predictions, columns=['uid', 'iid', 'rui', 'est', 'details'])df_predictions['Iu'] = df_predictions.uid.apply(get_Iu)df_predictions['Ui'] = df_predictions.iid.apply(get_Ui)df_predictions['err'] = abs(df_predictions.est - df_predictions.rui)" }, { "code": null, "e": 6090, "s": 6072, "text": "Best Predictions:" }, { "code": null, "e": 6151, "s": 6090, "text": "best_predictions = df_predictions.sort_values(by='err')[:10]" }, { "code": null, "e": 6170, "s": 6151, "text": "Worst predictions:" }, { "code": null, "e": 6233, "s": 6170, "text": "worst_predictions = df_predictions.sort_values(by='err')[-10:]" }, { "code": null, "e": 6364, "s": 6233, "text": "The worst predictions look pretty surprising. Let’s look in more details of item β€œ3996”, rated 0.5, our SVD algorithm predicts 4.4" }, { "code": null, "e": 6820, "s": 6364, "text": "df.loc[df['itemID'] == 3996]['rating'].describe()temp = df.loc[df['itemID'] == 3996]['rating']# Create tracetrace = go.Histogram(x = temp.values, name = 'Ratings', xbins = dict(start = 0, end = 5, size=.3))# Create layoutlayout = go.Layout(title = 'Number of ratings item 3996 has received', xaxis = dict(title = 'Number of Ratings Per Item'), yaxis = dict(title = 'Count'), bargap = 0.2)# Create plotfig = go.Figure(data=[trace], layout=layout)iplot(fig)" }, { "code": null, "e": 7063, "s": 6820, "text": "It turns out, most of the ratings this Item received between β€œ3 and 5”, only 1% of the users rated β€œ0.5” and one β€œ2.5” below 3. It seems that for each prediction, the users are some kind of outliers and the item has been rated very few times." }, { "code": null, "e": 7100, "s": 7063, "text": "Looks like you’re enjoying the post!" }, { "code": null, "e": 7202, "s": 7100, "text": "You have just read Part 1 which covered how to build a model on explicit data using Surprise library." }, { "code": null, "e": 7329, "s": 7202, "text": "Part 2 will cover how many movies we should recommend by calculating precision and recall at K and then recommending K movies." }, { "code": null, "e": 7392, "s": 7329, "text": "For the complete code, you can find the Jupyter notebook here." } ]
6 amateur mistakes I’ve made working with train-test splits | by Gonzalo Ferreiro Volpi | Towards Data Science
In the last weeks he went together into a journey about Recommendation Systems. We saw a gentle introduction to the topic and also an introduction to the most important similarity measures around it (remember that the whole repository about recommendation system and other projects are always available on my GitHub profile). And yes, I know, there’s sooo much else around the topic, so we will come back to it in brief. But this week I decided to make an impasse to talk about a very basic topic in Data Science, that brought me some good headaches when I just started to work with modelling and Machine Learning: train-test splits. Nobody is born knowing, so don’t worry if you don’t know yet what train-test splits are. However, it is a fundamental concept in the field, so in this article, I’ll try to briefly introduce the topic, and tell you some mistakes I personally made when I started working with train-test splits. Hopefully, you’ll learn something from my time-consuming-amateur-mistakes :) To get into what a train-test split is, we need to first understand what is a β€˜test group’ and why the hell do we need one when doing ML modelling. In short, when we’re trying to predict any kind of output, we will be β€˜training’ a machine learning model using a dataset. This model will try to learn as much from the data as possible in order to make accurate predictions. As much, that perhaps our model will learn too much from it, up to a point where it will be only useful to predict that bunch of data we gave him to work with, but failing to make predictions with any other. This potential problem or risk is the kick-starter point to several tools and concepts we usually apply in machine learning: The bias-variance trade-off, that, in a nutshell, it’s just about how much should our model learns from our training data. If it learns too much, we’d say it has β€˜high variance’ and it would be β€˜overfitting’ our data. On the contrary, if it learns too little, it would have β€˜high bias’ and the model would be β€˜underfitting’ our training data. The concept of regularization also comes in handy when talking about all this, since it’s a technique that allows us to control how much do we allow our model to learn from our data. The concept is not that simple but can be easily applied with Python. If you’re fancy in learning more about, I highly recommend this and this basic videos from StatQuest with Josh Starmer. Apart from any kind of technique to control how much is our model learning from the data, a well-established practice is to split our data to evaluate our model, so we can be sure it performs well on different elements. Here’s where the concept of test split finally appears! The idea is that we’ll like to divide our original data into two groups: the training group will be used, not surprisingly, to train our model. While we’ll leave apart a bunch of data, so once we have already trained our model and we are happy with its performance, we can evaluate it with a completely new bunch of data, to check if the model is consistent. This will be our test group. And if we obtain a much worse score on our test set, than in our train group, then probably we’re overfitting our training data. Usually a 80–20 or 70–30% train-test split is considered reasonable. Finally, we could also talk about the concept of doing cross-validation when evaluating the performance of our model, but that will have to wait till another article :) As usually, Sklearn makes it all so easy for us, and it has a beautiful life-saving library, that comes really in handy to perform a train-test split: from sklearn.model_selection import train_test_split The documentation is pretty clear, but let’s go over a simple example anyway: X_train, X_test, y_train, y_test = train_test_split(your_data, y, test_size=0.2, random_state=123) Now, the next step will be...oh, wait, that’s all! There’s really not much about how to implement this library. Is very straightforward, and now you’ll have 4 different bunches of data: X_train: this will be your training groupX_test: this will be your test groupY_train: this will be your target for your training groupY_test: as you can imagine, this will be your target for your test group X_train: this will be your training group X_test: this will be your test group Y_train: this will be your target for your training group Y_test: as you can imagine, this will be your target for your test group However, as easy as it sounds, there are a few risks or problems you might face if your first time working with the library, and even if you have already used it several times. Let’s see them, so you don’t go down the rabbit hole as it happened to me before. Write in disorder your train-test split code Write in disorder your train-test split code Yes, as silly as it sounds, it has the potential to be a huge headache. Picture this, it’s early in the morning and you have been all night working on a dataset. Cleaning, merging data, doing some feature engineering...the usual. It’s time for you to make the train-test split so you can try a simple model before going to bed. You write your code, but instead of writing: X_train, X_test, y_train, y_test You write, for example: X_test, X_train, y_test, y_train Sounds silly? One of the most important rules in Data Science is that you shouldn’t reveal your test score until you’re satisfied with your training/cross-validated score. But remember, you wrote in disorder your train-test split code, so the score you’re getting is not your training, but instead it’s your test score. You may spend hours trying to understand why you’re getting such low values on your training data. Or even worse, you may discard your project because of having such a bad performance. In any case, it’s a mistake that once it’s done, it’s hard to find and it may lead to hours of deep diving into your code trying so solve this silly mistake. 2. Mistype the size of the test group One of the parameters you should specify is either β€˜train_size’ or β€˜test_size’. You should use only one of them, but even more important, be sure not to confuse them. Otherwise, you could be setting a train set with only 20–30%. This could lead to several problems. From not having enough data to train a proper model, to obtaining too good, or too bad results that may lead you into some time-consuming further analysis. 3. Normalize your test group apart from your train data Normalization is the process of adjusting values measured on different scales to a common scale. Suppose you’re trying to predict whether a person is male or female, given a set of features such as height, weight and heart rate. In this case, all features are in different scales. For example, height could be in centimetres, while weight may be in kilos. In cases like this, is highly recommended to normalize the data to express it all in a common scale. Sklearn offers a very friendly library to do it calling: from sklearn.preprocessing import StandardScaler The process of normalizing takes the Mean and Standard Deviation of each feature and adjusted their scale in order to be in between -1 and 1 with a Mean of 0. Once we imported the library, we can create an object StandardScaler, to proceed with the normalization: scaler = StandardScaler() However, if we are splitting our data into train and test groups, we should fit our StandardScaler object first using our train group and then transform our test group using that same object. For example: scaler.fit(X_train)X_train = scaler.transform(X_train)X_test = scaler.transform(X_test) Why do we have to normalize data this way? Remember that we’ll use our data to train our model, so we’ll want our StandardScaler object to register and proceed with the Mean and Standard Deviation of our train set and transform our test group using it. Otherwise, we would be doing two different transformations, taking two different Means and two different Standard Deviations. Treating as different data that’s supposed to be the same. 4. Not shuffle your data when needed or vice-versa Another parameter from our Sklearn train_test_split is β€˜shuffle’. Let’s keep the previous example and let’s suppose that our dataset is composed of 1000 elements, of which the first 500 correspond to males, and the last 500 correspond to females. The default value for this parameter is β€˜True’, but if by mistake or ignorance we set it to β€˜False’ and we split our data 80–20, we’ll end up training our model with a dataset with 500 males and 300 females, and testing it with a dataset only containing 200 females within it. Take into account that the default value is β€˜True’, so if it comes a time when you don’t want to shuffle your data, don’t forget to specify it ;) 5. Not wisely use the β€˜stratify’ parameter The β€˜stratify’ parameter comes into handy so that the proportion of values in the sample produced in our test group will be the same as the proportion of values provided to parameter stratify. This results especially useful when working around classification problems, since if we don’t provide this parameter with an array-like object, we may end with a non-representative distribution of our target classes in our test group. Usually, this parameter is used by passing the target variable like this: X_train, X_test, y_train, y_test = train_test_split(your_data, y, test_size=0.2, stratify=y, random_state=123, shuffle=True) 6. Forget of setting theβ€˜random_state’ parameter Finally, this is something we can find in several tools from Sklearn, and the documentation is pretty clear about how it works: 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. In other words: if you don’t specify a number or RandomState object instance, each iteration of the train_test_split will give you different groups, since the seed used to proceed with the randomness around the split would be different. This may lead to confusion if for any reason we have to run our code, and we start obtaining different results. This, my fellow friends, are the 6 mistakes I’ve made working with train-test splits that led me to hours and hours of decoding and debugging, due to amateur errors. If you have been unlucky enough to face some other, I’d love to hear about it. And as always, any constructive critic or suggestion is welcome through the comments sections :) Also, don’t forget to check out my last article about Web scraping in 5 minutes and more in my writer profile in Towards Data Science. And if you liked this article, don’t forget to follow me, and if you want to receive my latest articles directly on your email, just subscribe to my newsletter :) Thanks for reading!
[ { "code": null, "e": 805, "s": 171, "text": "In the last weeks he went together into a journey about Recommendation Systems. We saw a gentle introduction to the topic and also an introduction to the most important similarity measures around it (remember that the whole repository about recommendation system and other projects are always available on my GitHub profile). And yes, I know, there’s sooo much else around the topic, so we will come back to it in brief. But this week I decided to make an impasse to talk about a very basic topic in Data Science, that brought me some good headaches when I just started to work with modelling and Machine Learning: train-test splits." }, { "code": null, "e": 1175, "s": 805, "text": "Nobody is born knowing, so don’t worry if you don’t know yet what train-test splits are. However, it is a fundamental concept in the field, so in this article, I’ll try to briefly introduce the topic, and tell you some mistakes I personally made when I started working with train-test splits. Hopefully, you’ll learn something from my time-consuming-amateur-mistakes :)" }, { "code": null, "e": 1323, "s": 1175, "text": "To get into what a train-test split is, we need to first understand what is a β€˜test group’ and why the hell do we need one when doing ML modelling." }, { "code": null, "e": 1756, "s": 1323, "text": "In short, when we’re trying to predict any kind of output, we will be β€˜training’ a machine learning model using a dataset. This model will try to learn as much from the data as possible in order to make accurate predictions. As much, that perhaps our model will learn too much from it, up to a point where it will be only useful to predict that bunch of data we gave him to work with, but failing to make predictions with any other." }, { "code": null, "e": 1881, "s": 1756, "text": "This potential problem or risk is the kick-starter point to several tools and concepts we usually apply in machine learning:" }, { "code": null, "e": 2224, "s": 1881, "text": "The bias-variance trade-off, that, in a nutshell, it’s just about how much should our model learns from our training data. If it learns too much, we’d say it has β€˜high variance’ and it would be β€˜overfitting’ our data. On the contrary, if it learns too little, it would have β€˜high bias’ and the model would be β€˜underfitting’ our training data." }, { "code": null, "e": 2597, "s": 2224, "text": "The concept of regularization also comes in handy when talking about all this, since it’s a technique that allows us to control how much do we allow our model to learn from our data. The concept is not that simple but can be easily applied with Python. If you’re fancy in learning more about, I highly recommend this and this basic videos from StatQuest with Josh Starmer." }, { "code": null, "e": 3459, "s": 2597, "text": "Apart from any kind of technique to control how much is our model learning from the data, a well-established practice is to split our data to evaluate our model, so we can be sure it performs well on different elements. Here’s where the concept of test split finally appears! The idea is that we’ll like to divide our original data into two groups: the training group will be used, not surprisingly, to train our model. While we’ll leave apart a bunch of data, so once we have already trained our model and we are happy with its performance, we can evaluate it with a completely new bunch of data, to check if the model is consistent. This will be our test group. And if we obtain a much worse score on our test set, than in our train group, then probably we’re overfitting our training data. Usually a 80–20 or 70–30% train-test split is considered reasonable." }, { "code": null, "e": 3628, "s": 3459, "text": "Finally, we could also talk about the concept of doing cross-validation when evaluating the performance of our model, but that will have to wait till another article :)" }, { "code": null, "e": 3779, "s": 3628, "text": "As usually, Sklearn makes it all so easy for us, and it has a beautiful life-saving library, that comes really in handy to perform a train-test split:" }, { "code": null, "e": 3832, "s": 3779, "text": "from sklearn.model_selection import train_test_split" }, { "code": null, "e": 3910, "s": 3832, "text": "The documentation is pretty clear, but let’s go over a simple example anyway:" }, { "code": null, "e": 4009, "s": 3910, "text": "X_train, X_test, y_train, y_test = train_test_split(your_data, y, test_size=0.2, random_state=123)" }, { "code": null, "e": 4060, "s": 4009, "text": "Now, the next step will be...oh, wait, that’s all!" }, { "code": null, "e": 4195, "s": 4060, "text": "There’s really not much about how to implement this library. Is very straightforward, and now you’ll have 4 different bunches of data:" }, { "code": null, "e": 4402, "s": 4195, "text": "X_train: this will be your training groupX_test: this will be your test groupY_train: this will be your target for your training groupY_test: as you can imagine, this will be your target for your test group" }, { "code": null, "e": 4444, "s": 4402, "text": "X_train: this will be your training group" }, { "code": null, "e": 4481, "s": 4444, "text": "X_test: this will be your test group" }, { "code": null, "e": 4539, "s": 4481, "text": "Y_train: this will be your target for your training group" }, { "code": null, "e": 4612, "s": 4539, "text": "Y_test: as you can imagine, this will be your target for your test group" }, { "code": null, "e": 4871, "s": 4612, "text": "However, as easy as it sounds, there are a few risks or problems you might face if your first time working with the library, and even if you have already used it several times. Let’s see them, so you don’t go down the rabbit hole as it happened to me before." }, { "code": null, "e": 4916, "s": 4871, "text": "Write in disorder your train-test split code" }, { "code": null, "e": 4961, "s": 4916, "text": "Write in disorder your train-test split code" }, { "code": null, "e": 5334, "s": 4961, "text": "Yes, as silly as it sounds, it has the potential to be a huge headache. Picture this, it’s early in the morning and you have been all night working on a dataset. Cleaning, merging data, doing some feature engineering...the usual. It’s time for you to make the train-test split so you can try a simple model before going to bed. You write your code, but instead of writing:" }, { "code": null, "e": 5367, "s": 5334, "text": "X_train, X_test, y_train, y_test" }, { "code": null, "e": 5391, "s": 5367, "text": "You write, for example:" }, { "code": null, "e": 5424, "s": 5391, "text": "X_test, X_train, y_test, y_train" }, { "code": null, "e": 6087, "s": 5424, "text": "Sounds silly? One of the most important rules in Data Science is that you shouldn’t reveal your test score until you’re satisfied with your training/cross-validated score. But remember, you wrote in disorder your train-test split code, so the score you’re getting is not your training, but instead it’s your test score. You may spend hours trying to understand why you’re getting such low values on your training data. Or even worse, you may discard your project because of having such a bad performance. In any case, it’s a mistake that once it’s done, it’s hard to find and it may lead to hours of deep diving into your code trying so solve this silly mistake." }, { "code": null, "e": 6125, "s": 6087, "text": "2. Mistype the size of the test group" }, { "code": null, "e": 6547, "s": 6125, "text": "One of the parameters you should specify is either β€˜train_size’ or β€˜test_size’. You should use only one of them, but even more important, be sure not to confuse them. Otherwise, you could be setting a train set with only 20–30%. This could lead to several problems. From not having enough data to train a proper model, to obtaining too good, or too bad results that may lead you into some time-consuming further analysis." }, { "code": null, "e": 6603, "s": 6547, "text": "3. Normalize your test group apart from your train data" }, { "code": null, "e": 7060, "s": 6603, "text": "Normalization is the process of adjusting values measured on different scales to a common scale. Suppose you’re trying to predict whether a person is male or female, given a set of features such as height, weight and heart rate. In this case, all features are in different scales. For example, height could be in centimetres, while weight may be in kilos. In cases like this, is highly recommended to normalize the data to express it all in a common scale." }, { "code": null, "e": 7117, "s": 7060, "text": "Sklearn offers a very friendly library to do it calling:" }, { "code": null, "e": 7166, "s": 7117, "text": "from sklearn.preprocessing import StandardScaler" }, { "code": null, "e": 7430, "s": 7166, "text": "The process of normalizing takes the Mean and Standard Deviation of each feature and adjusted their scale in order to be in between -1 and 1 with a Mean of 0. Once we imported the library, we can create an object StandardScaler, to proceed with the normalization:" }, { "code": null, "e": 7456, "s": 7430, "text": "scaler = StandardScaler()" }, { "code": null, "e": 7661, "s": 7456, "text": "However, if we are splitting our data into train and test groups, we should fit our StandardScaler object first using our train group and then transform our test group using that same object. For example:" }, { "code": null, "e": 7749, "s": 7661, "text": "scaler.fit(X_train)X_train = scaler.transform(X_train)X_test = scaler.transform(X_test)" }, { "code": null, "e": 8187, "s": 7749, "text": "Why do we have to normalize data this way? Remember that we’ll use our data to train our model, so we’ll want our StandardScaler object to register and proceed with the Mean and Standard Deviation of our train set and transform our test group using it. Otherwise, we would be doing two different transformations, taking two different Means and two different Standard Deviations. Treating as different data that’s supposed to be the same." }, { "code": null, "e": 8238, "s": 8187, "text": "4. Not shuffle your data when needed or vice-versa" }, { "code": null, "e": 8762, "s": 8238, "text": "Another parameter from our Sklearn train_test_split is β€˜shuffle’. Let’s keep the previous example and let’s suppose that our dataset is composed of 1000 elements, of which the first 500 correspond to males, and the last 500 correspond to females. The default value for this parameter is β€˜True’, but if by mistake or ignorance we set it to β€˜False’ and we split our data 80–20, we’ll end up training our model with a dataset with 500 males and 300 females, and testing it with a dataset only containing 200 females within it." }, { "code": null, "e": 8908, "s": 8762, "text": "Take into account that the default value is β€˜True’, so if it comes a time when you don’t want to shuffle your data, don’t forget to specify it ;)" }, { "code": null, "e": 8951, "s": 8908, "text": "5. Not wisely use the β€˜stratify’ parameter" }, { "code": null, "e": 9379, "s": 8951, "text": "The β€˜stratify’ parameter comes into handy so that the proportion of values in the sample produced in our test group will be the same as the proportion of values provided to parameter stratify. This results especially useful when working around classification problems, since if we don’t provide this parameter with an array-like object, we may end with a non-representative distribution of our target classes in our test group." }, { "code": null, "e": 9453, "s": 9379, "text": "Usually, this parameter is used by passing the target variable like this:" }, { "code": null, "e": 9578, "s": 9453, "text": "X_train, X_test, y_train, y_test = train_test_split(your_data, y, test_size=0.2, stratify=y, random_state=123, shuffle=True)" }, { "code": null, "e": 9627, "s": 9578, "text": "6. Forget of setting theβ€˜random_state’ parameter" }, { "code": null, "e": 9755, "s": 9627, "text": "Finally, this is something we can find in several tools from Sklearn, and the documentation is pretty clear about how it works:" }, { "code": null, "e": 9979, "s": 9755, "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": 10328, "s": 9979, "text": "In other words: if you don’t specify a number or RandomState object instance, each iteration of the train_test_split will give you different groups, since the seed used to proceed with the randomness around the split would be different. This may lead to confusion if for any reason we have to run our code, and we start obtaining different results." }, { "code": null, "e": 10670, "s": 10328, "text": "This, my fellow friends, are the 6 mistakes I’ve made working with train-test splits that led me to hours and hours of decoding and debugging, due to amateur errors. If you have been unlucky enough to face some other, I’d love to hear about it. And as always, any constructive critic or suggestion is welcome through the comments sections :)" }, { "code": null, "e": 10968, "s": 10670, "text": "Also, don’t forget to check out my last article about Web scraping in 5 minutes and more in my writer profile in Towards Data Science. And if you liked this article, don’t forget to follow me, and if you want to receive my latest articles directly on your email, just subscribe to my newsletter :)" } ]
Apache NiFi - API
NiFi offers a large number of API, which helps developers to make changes and get information of NiFi from any other tool or custom developed applications. In this tutorial, we will use postman app in google chrome to explain some examples. To add postmantoyour Google Chrome, go to the below mentioned URL and click add to chrome button. You will now see a new app added toyour Google Chrome. chrome web store The current version of NiFi rest API is 1.8.0 and the documentation is present in the below mentioned URL. https://nifi.apache.org/docs/nifi-docs/rest-api/index.html Following are the most used NiFi rest API Modules βˆ’ http://<nifi url>:<nifi port>/nifi-api/<api-path> http://<nifi url>:<nifi port>/nifi-api/<api-path> In case HTTPS is enabled https://<nifi url>:<nifi port>/nifi-api/<api-path> In case HTTPS is enabled https://<nifi url>:<nifi port>/nifi-api/<api-path> Let us now consider an example and run on postman to get the details about the running NiFi instance. GET http://localhost:8080/nifi-api/flow/about { "about": { "title": "NiFi", "version": "1.7.1", "uri": "http://localhost:8080/nifi-api/", "contentViewerUrl": "../nifi-content-viewer/", "timezone": "SGT", "buildTag": "nifi-1.7.1-RC1", "buildTimestamp": "07/12/2018 12:54:43 SGT" } } 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2559, "s": 2318, "text": "NiFi offers a large number of API, which helps developers to make changes and get information of NiFi from any other tool or custom developed applications. In this tutorial, we will use postman app in google chrome to explain some examples." }, { "code": null, "e": 2712, "s": 2559, "text": "To add postmantoyour Google Chrome, go to the below mentioned URL and click add to chrome button. You will now see a new app added toyour Google Chrome." }, { "code": null, "e": 2729, "s": 2712, "text": "chrome web store" }, { "code": null, "e": 2836, "s": 2729, "text": "The current version of NiFi rest API is 1.8.0 and the documentation is present in the below mentioned URL." }, { "code": null, "e": 2895, "s": 2836, "text": "https://nifi.apache.org/docs/nifi-docs/rest-api/index.html" }, { "code": null, "e": 2947, "s": 2895, "text": "Following are the most used NiFi rest API Modules βˆ’" }, { "code": null, "e": 2997, "s": 2947, "text": "http://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 3047, "s": 2997, "text": "http://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 3123, "s": 3047, "text": "In case HTTPS is enabled\nhttps://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 3199, "s": 3123, "text": "In case HTTPS is enabled\nhttps://<nifi url>:<nifi port>/nifi-api/<api-path>" }, { "code": null, "e": 3301, "s": 3199, "text": "Let us now consider an example and run on postman to get the details about the running NiFi instance." }, { "code": null, "e": 3348, "s": 3301, "text": "GET http://localhost:8080/nifi-api/flow/about\n" }, { "code": null, "e": 3633, "s": 3348, "text": "{\n \"about\": {\n \"title\": \"NiFi\",\n \"version\": \"1.7.1\",\n \"uri\": \"http://localhost:8080/nifi-api/\",\n \"contentViewerUrl\": \"../nifi-content-viewer/\",\n \"timezone\": \"SGT\",\n \"buildTag\": \"nifi-1.7.1-RC1\",\n \"buildTimestamp\": \"07/12/2018 12:54:43 SGT\"\n }\n}\n" }, { "code": null, "e": 3668, "s": 3633, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3687, "s": 3668, "text": " Arnab Chakraborty" }, { "code": null, "e": 3722, "s": 3687, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3743, "s": 3722, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3776, "s": 3743, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3789, "s": 3776, "text": " Nilay Mehta" }, { "code": null, "e": 3824, "s": 3789, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3842, "s": 3824, "text": " Bigdata Engineer" }, { "code": null, "e": 3875, "s": 3842, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3893, "s": 3875, "text": " Bigdata Engineer" }, { "code": null, "e": 3926, "s": 3893, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 3944, "s": 3926, "text": " Bigdata Engineer" }, { "code": null, "e": 3951, "s": 3944, "text": " Print" }, { "code": null, "e": 3962, "s": 3951, "text": " Add Notes" } ]
Aggregate by country, state and city in a MongoDB collection with multiple documents
Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. To aggregate in MongoDB, use aggregate(). Let us create a collection with documents βˆ’ > db.demo620.insertOne({"Country":"IND","City":"Delhi",state:"Delhi"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9a8de96c954c74be91e6a1") } > db.demo620.insertOne({"Country":"IND","City":"Bangalore",state:"Karnataka"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9a8e336c954c74be91e6a3") } > db.demo620.insertOne({"Country":"IND","City":"Mumbai",state:"Maharashtra"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9a8e636c954c74be91e6a4") } Display all documents from a collection with the help of find() method βˆ’ > db.demo620.find(); This will produce the following output βˆ’ { "_id" : ObjectId("5e9a8de96c954c74be91e6a1"), "Country" : "IND", "City" : "Delhi", "state" : "Delhi" } { "_id" : ObjectId("5e9a8e336c954c74be91e6a3"), "Country" : "IND", "City" : "Bangalore", "state" : "Karnataka" } { "_id" : ObjectId("5e9a8e636c954c74be91e6a4"), "Country" : "IND", "City" : "Mumbai", "state" : "Maharashtra" } Following is the query to aggregate by country, state and city βˆ’ > db.demo620.aggregate([ ... { "$group": { ... "_id": { ... "Country": "$Country", ... "state": "$state" ... }, ... "City": { ... "$addToSet": { ... "City": "$City" ... } ... } ... }}, ... { "$group": { ... "_id": "$_id.Country", ... "states": { ... "$addToSet": { ... "state": "$_id.state", ... "City": "$City" ... } ... } ... }} ... ]).pretty(); This will produce the following output βˆ’ { "_id" : "IND", "states" : [ { "state" : "Delhi", "City" : [ { "City" : "Delhi" } ] }, { "state" : "Maharashtra", "City" : [ { "City" : "Mumbai" } ] }, { "state" : "Karnataka", "City" : [ { "City" : "Bangalore" } ] } ] }
[ { "code": null, "e": 1219, "s": 1062, "text": "Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result." }, { "code": null, "e": 1305, "s": 1219, "text": "To aggregate in MongoDB, use aggregate(). Let us create a collection with documents βˆ’" }, { "code": null, "e": 1791, "s": 1305, "text": "> db.demo620.insertOne({\"Country\":\"IND\",\"City\":\"Delhi\",state:\"Delhi\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9a8de96c954c74be91e6a1\")\n}\n> db.demo620.insertOne({\"Country\":\"IND\",\"City\":\"Bangalore\",state:\"Karnataka\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9a8e336c954c74be91e6a3\")\n}\n> db.demo620.insertOne({\"Country\":\"IND\",\"City\":\"Mumbai\",state:\"Maharashtra\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9a8e636c954c74be91e6a4\")\n}" }, { "code": null, "e": 1864, "s": 1791, "text": "Display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 1885, "s": 1864, "text": "> db.demo620.find();" }, { "code": null, "e": 1926, "s": 1885, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2256, "s": 1926, "text": "{ \"_id\" : ObjectId(\"5e9a8de96c954c74be91e6a1\"), \"Country\" : \"IND\", \"City\" : \"Delhi\", \"state\" : \"Delhi\" }\n{ \"_id\" : ObjectId(\"5e9a8e336c954c74be91e6a3\"), \"Country\" : \"IND\", \"City\" : \"Bangalore\", \"state\" : \"Karnataka\" }\n{ \"_id\" : ObjectId(\"5e9a8e636c954c74be91e6a4\"), \"Country\" : \"IND\", \"City\" : \"Mumbai\", \"state\" : \"Maharashtra\" }" }, { "code": null, "e": 2321, "s": 2256, "text": "Following is the query to aggregate by country, state and city βˆ’" }, { "code": null, "e": 2813, "s": 2321, "text": "> db.demo620.aggregate([\n... { \"$group\": {\n... \"_id\": {\n... \"Country\": \"$Country\",\n... \"state\": \"$state\"\n... },\n... \"City\": {\n... \"$addToSet\": {\n... \"City\": \"$City\"\n... }\n... }\n... }},\n... { \"$group\": {\n... \"_id\": \"$_id.Country\",\n... \"states\": {\n... \"$addToSet\": {\n... \"state\": \"$_id.state\",\n... \"City\": \"$City\"\n... }\n... }\n... }}\n... ]).pretty();" }, { "code": null, "e": 2854, "s": 2813, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 3322, "s": 2854, "text": "{\n \"_id\" : \"IND\",\n \"states\" : [\n {\n \"state\" : \"Delhi\",\n \"City\" : [\n {\n \"City\" : \"Delhi\"\n }\n ]\n },\n {\n \"state\" : \"Maharashtra\",\n \"City\" : [\n {\n \"City\" : \"Mumbai\"\n }\n ]\n },\n {\n \"state\" : \"Karnataka\",\n \"City\" : [\n {\n \"City\" : \"Bangalore\"\n }\n ]\n }\n ]\n}" } ]
How to repeat a random sample in R?
The random sample can be repeated by using replicate function in R. For example, if we have a vector that contains 1, 2, 3, 4, 5 and we want to repeat this random sample five times then replicate(5,x) can be used and the output will be matrix of the below form: [,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 2 2 2 2 2 [3,] 3 3 3 3 3 [4,] 4 4 4 4 4 [5,] 5 5 5 5 5 Live Demo > x1<-sample(0:1,10,replace=TRUE) > x1 [1] 1 0 1 0 1 1 1 0 0 1 > replicate(2,x1) [,1] [,2] [1,] 1 1 [2,] 0 0 [3,] 1 1 [4,] 0 0 [5,] 1 1 [6,] 1 1 [7,] 1 1 [8,] 0 0 [9,] 0 0 [10,] 1 1 Live Demo > x2<-rnorm(20,5,0.43) > x2 [1] 4.946766 4.930826 4.845512 4.940984 5.091849 5.437576 5.438818 4.319041 [9] 5.294105 4.941349 5.895272 5.161996 4.541355 5.065261 5.065255 4.770162 [17] 4.575399 4.466801 4.814925 5.568215 > replicate(4,x2) [,1] [,2] [,3] [,4] [1,] 4.946766 4.946766 4.946766 4.946766 [2,] 4.930826 4.930826 4.930826 4.930826 [3,] 4.845512 4.845512 4.845512 4.845512 [4,] 4.940984 4.940984 4.940984 4.940984 [5,] 5.091849 5.091849 5.091849 5.091849 [6,] 5.437576 5.437576 5.437576 5.437576 [7,] 5.438818 5.438818 5.438818 5.438818 [8,] 4.319041 4.319041 4.319041 4.319041 [9,] 5.294105 5.294105 5.294105 5.294105 [10,] 4.941349 4.941349 4.941349 4.941349 [11,] 5.895272 5.895272 5.895272 5.895272 [12,] 5.161996 5.161996 5.161996 5.161996 [13,] 4.541355 4.541355 4.541355 4.541355 [14,] 5.065261 5.065261 5.065261 5.065261 [15,] 5.065255 5.065255 5.065255 5.065255 [16,] 4.770162 4.770162 4.770162 4.770162 [17,] 4.575399 4.575399 4.575399 4.575399 [18,] 4.466801 4.466801 4.466801 4.466801 [19,] 4.814925 4.814925 4.814925 4.814925 [20,] 5.568215 5.568215 5.568215 5.568215 Live Demo > x3<-rpois(20,5) > x3 [1] 8 4 5 3 4 3 4 3 8 3 2 6 5 6 4 7 6 2 2 2 > replicate(8,x3) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 8 8 8 8 8 8 8 8 [2,] 4 4 4 4 4 4 4 4 [3,] 5 5 5 5 5 5 5 5 [4,] 3 3 3 3 3 3 3 3 [5,] 4 4 4 4 4 4 4 4 [6,] 3 3 3 3 3 3 3 3 [7,] 4 4 4 4 4 4 4 4 [8,] 3 3 3 3 3 3 3 3 [9,] 8 8 8 8 8 8 8 8 [10,] 3 3 3 3 3 3 3 3 [11,] 2 2 2 2 2 2 2 2 [12,] 6 6 6 6 6 6 6 6 [13,] 5 5 5 5 5 5 5 5 [14,] 6 6 6 6 6 6 6 6 [15,] 4 4 4 4 4 4 4 4 [16,] 7 7 7 7 7 7 7 7 [17,] 6 6 6 6 6 6 6 6 [18,] 2 2 2 2 2 2 2 2 [19,] 2 2 2 2 2 2 2 2 [20,] 2 2 2 2 2 2 2 2 Live Demo > x4<-sample(c("A","B","c","d"),10,replace=TRUE) > x4 [1] "B" "A" "B" "A" "c" "B" "d" "A" "d" "d" > replicate(5,x4) [,1] [,2] [,3] [,4] [,5] [1,] "B" "B" "B" "B" "B" [2,] "A" "A" "A" "A" "A" [3,] "B" "B" "B" "B" "B" [4,] "A" "A" "A" "A" "A" [5,] "c" "c" "c" "c" "c" [6,] "B" "B" "B" "B" "B" [7,] "d" "d" "d" "d" "d" [8,] "A" "A" "A" "A" "A" [9,] "d" "d" "d" "d" "d" [10,] "d" "d" "d" "d" "d"
[ { "code": null, "e": 1324, "s": 1062, "text": "The random sample can be repeated by using replicate function in R. For example, if we have a vector that contains 1, 2, 3, 4, 5 and we want to repeat this random sample five times then replicate(5,x) can be used and the output will be matrix of the below form:" }, { "code": null, "e": 1424, "s": 1324, "text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 1 1 1 1 1\n[2,] 2 2 2 2 2\n[3,] 3 3 3 3 3\n[4,] 4 4 4 4 4\n[5,] 5 5 5 5 5" }, { "code": null, "e": 1434, "s": 1424, "text": "Live Demo" }, { "code": null, "e": 1473, "s": 1434, "text": "> x1<-sample(0:1,10,replace=TRUE)\n> x1" }, { "code": null, "e": 1497, "s": 1473, "text": "[1] 1 0 1 0 1 1 1 0 0 1" }, { "code": null, "e": 1515, "s": 1497, "text": "> replicate(2,x1)" }, { "code": null, "e": 1616, "s": 1515, "text": "[,1] [,2]\n[1,] 1 1\n[2,] 0 0\n[3,] 1 1\n[4,] 0 0\n[5,] 1 1\n[6,] 1 1\n[7,] 1 1\n[8,] 0 0\n[9,] 0 0\n[10,] 1 1" }, { "code": null, "e": 1626, "s": 1616, "text": "Live Demo" }, { "code": null, "e": 1654, "s": 1626, "text": "> x2<-rnorm(20,5,0.43)\n> x2" }, { "code": null, "e": 1847, "s": 1654, "text": "[1] 4.946766 4.930826 4.845512 4.940984 5.091849 5.437576 5.438818 4.319041\n[9] 5.294105 4.941349 5.895272 5.161996 4.541355 5.065261 5.065255 4.770162\n[17] 4.575399 4.466801 4.814925 5.568215" }, { "code": null, "e": 1865, "s": 1847, "text": "> replicate(4,x2)" }, { "code": null, "e": 2716, "s": 1865, "text": "[,1] [,2] [,3] [,4]\n[1,] 4.946766 4.946766 4.946766 4.946766\n[2,] 4.930826 4.930826 4.930826 4.930826\n[3,] 4.845512 4.845512 4.845512 4.845512\n[4,] 4.940984 4.940984 4.940984 4.940984\n[5,] 5.091849 5.091849 5.091849 5.091849\n[6,] 5.437576 5.437576 5.437576 5.437576\n[7,] 5.438818 5.438818 5.438818 5.438818\n[8,] 4.319041 4.319041 4.319041 4.319041\n[9,] 5.294105 5.294105 5.294105 5.294105\n[10,] 4.941349 4.941349 4.941349 4.941349\n[11,] 5.895272 5.895272 5.895272 5.895272\n[12,] 5.161996 5.161996 5.161996 5.161996\n[13,] 4.541355 4.541355 4.541355 4.541355\n[14,] 5.065261 5.065261 5.065261 5.065261\n[15,] 5.065255 5.065255 5.065255 5.065255\n[16,] 4.770162 4.770162 4.770162 4.770162\n[17,] 4.575399 4.575399 4.575399 4.575399\n[18,] 4.466801 4.466801 4.466801 4.466801\n[19,] 4.814925 4.814925 4.814925 4.814925\n[20,] 5.568215 5.568215 5.568215 5.568215" }, { "code": null, "e": 2726, "s": 2716, "text": "Live Demo" }, { "code": null, "e": 2749, "s": 2726, "text": "> x3<-rpois(20,5)\n> x3" }, { "code": null, "e": 2793, "s": 2749, "text": "[1] 8 4 5 3 4 3 4 3 8 3 2 6 5 6 4 7 6 2 2 2" }, { "code": null, "e": 2811, "s": 2793, "text": "> replicate(8,x3)" }, { "code": null, "e": 3282, "s": 2811, "text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 8 8 8 8 8 8 8 8\n[2,] 4 4 4 4 4 4 4 4\n[3,] 5 5 5 5 5 5 5 5\n[4,] 3 3 3 3 3 3 3 3\n[5,] 4 4 4 4 4 4 4 4\n[6,] 3 3 3 3 3 3 3 3\n[7,] 4 4 4 4 4 4 4 4\n[8,] 3 3 3 3 3 3 3 3\n[9,] 8 8 8 8 8 8 8 8\n[10,] 3 3 3 3 3 3 3 3\n[11,] 2 2 2 2 2 2 2 2\n[12,] 6 6 6 6 6 6 6 6\n[13,] 5 5 5 5 5 5 5 5\n[14,] 6 6 6 6 6 6 6 6\n[15,] 4 4 4 4 4 4 4 4\n[16,] 7 7 7 7 7 7 7 7\n[17,] 6 6 6 6 6 6 6 6\n[18,] 2 2 2 2 2 2 2 2\n[19,] 2 2 2 2 2 2 2 2\n[20,] 2 2 2 2 2 2 2 2" }, { "code": null, "e": 3292, "s": 3282, "text": "Live Demo" }, { "code": null, "e": 3346, "s": 3292, "text": "> x4<-sample(c(\"A\",\"B\",\"c\",\"d\"),10,replace=TRUE)\n> x4" }, { "code": null, "e": 3390, "s": 3346, "text": "[1] \"B\" \"A\" \"B\" \"A\" \"c\" \"B\" \"d\" \"A\" \"d\" \"d\"" }, { "code": null, "e": 3408, "s": 3390, "text": "> replicate(5,x4)" }, { "code": null, "e": 3684, "s": 3408, "text": "[,1] [,2] [,3] [,4] [,5]\n[1,] \"B\" \"B\" \"B\" \"B\" \"B\"\n[2,] \"A\" \"A\" \"A\" \"A\" \"A\"\n[3,] \"B\" \"B\" \"B\" \"B\" \"B\"\n[4,] \"A\" \"A\" \"A\" \"A\" \"A\"\n[5,] \"c\" \"c\" \"c\" \"c\" \"c\"\n[6,] \"B\" \"B\" \"B\" \"B\" \"B\"\n[7,] \"d\" \"d\" \"d\" \"d\" \"d\"\n[8,] \"A\" \"A\" \"A\" \"A\" \"A\"\n[9,] \"d\" \"d\" \"d\" \"d\" \"d\"\n[10,] \"d\" \"d\" \"d\" \"d\" \"d\"" } ]
MongoDB Tutorial in Java - GeeksforGeeks
12 May, 2020 MongoDB is an open-source cross-platform document database developed using C++. Some features of MongoDB are: High and effective performance Easily scalable High availability It can store high volume of data It contains data in the form of collections and documents instead of rows and tables. A collection is a set of documents. The collection does not have schemas. It represents data in the form of a hierarchical model with which the storage of arrays and other data structures will be easy. The essentials components of MongoDB are listed below: id: This field represents a unique field in MongoDB. This field is created by default.Collection: It is a set of MongoDB documents. It exists with a single database.Database: This is the container for collections. Multiple databases can be stored in a mongoDB server.Document: A record in mongoDB is called a document. It containes names and values.Field: It is a name-value pair in a document. id: This field represents a unique field in MongoDB. This field is created by default. Collection: It is a set of MongoDB documents. It exists with a single database. Database: This is the container for collections. Multiple databases can be stored in a mongoDB server. Document: A record in mongoDB is called a document. It containes names and values. Field: It is a name-value pair in a document. Note: Make sure to install and setup MongoDB JDBC driver and Java. Table of contents: 1. Establishing connections to database 2. Creating a MongoDb collection 3. Getting a Collection 4. Inserting Values into MongoDb 5. Displaying the list of all Documents 6. Updating documents in the MongoDB 7. Deleting a Document 8. Dropping of a Collection 9. Displaying all the collections For making the connection, you have to mention the database name. MongoDB creates a database by default if no name is mentioned. Firstly, import the required libraries for establishing the connection.Here, β€œMongoClient” is used to create the client for the database.β€œMongoCredential” is used for creating the credentials.And finally, to access the database β€œMongoDatabase” is used.Username will be: β€œGFGUser” and the database name will be β€œmongoDbβ€œ.The function β€œ.toCharArray()” is used to convert the password into a character array.The function β€œ.getDatabase()” is used for getting the database. Firstly, import the required libraries for establishing the connection. Here, β€œMongoClient” is used to create the client for the database. β€œMongoCredential” is used for creating the credentials. And finally, to access the database β€œMongoDatabase” is used. Username will be: β€œGFGUser” and the database name will be β€œmongoDbβ€œ. The function β€œ.toCharArray()” is used to convert the password into a character array. The function β€œ.getDatabase()” is used for getting the database. The following code establishes a connection to MongoDB -> // Java program for establishing connections// to MongoDb import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class ConnectionDB { public static void establishConnections() { try { MongoClient db = new MongoClient("localhost", 27017); MongoCredential credential; credential = MongoCredential .createCredential( "GFGUser", "mongoDb", "password".toCharArray()); System.out.println( "Successfully Connected" + " to the database"); MongoDatabase database = db.getDatabase("mongoDb"); System.out.println("Credentials are: " + credential); } catch (Exception e) { System.out.println( "Connection establishment failed"); System.out.println(e); } }} Output: To create a collection com.mongodb.client.MongoDatabase class and createCollection() method is used. Here, β€œdatabase.createCollection()” creates a collection named as β€œGFGCollection”. Following is the code for creating collection: // Java program to create a MongoDb collection import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void createCollection( String collectionName) { try { // establishConnections() Code // is defined above establishConnections(); // Get the database instance MongoDatabase database = db.getDatabase("mongoDb"); // Create the collection database.createCollection(collectionName); System.out.println( "Collection created Successfully"); } catch (Exception e) { System.out.println( "Collection creation failed"); System.out.println(e); } }} Output: For getting a collection, MongoCollection.getCollection() method is used. Below is the implementation of this approach: // Java program to retrieve a MongoDb collection import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void getCollection( String collectionName) { try { // establishConnections() Code // is defined above establishConnections(); // Retrieve the collection MongoCollection<Document> collection = database .getCollection(collectionName); System.out.println( "Collection retrieved Successfully"); } catch (Exception e) { System.out.println( "Collection retrieval failed"); System.out.println(e); } }} Output Only a document type of data can be inserted a MongoDB. Therefore, either we can create a document with the values to be inserted using append() method or pass a document directly into the MongoDB using .insert() method. Here, first, we created a new document as β€œtitle” and then append the β€œabout” section. Then, we have given the respective values to the documents. The function β€œ.insertOne()” is used to insert the document into the collection. Below is the implementation of this approach: // Java program to insert values into MongoDB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { // Function to insert only one // document in to the MongoDB public static void insertADocIntoDb() { try { // establishConnections() Code // is defined above establishConnections(); // Creating the document // to be inserted Document document = new Document("title", "MongoDB") .append("about", "Open-Source database") // Insert the document collection.insertOne(document); System.out.println( "Document inserted Successfully"); } catch (Exception e) { System.out.println( "Document insertion failed"); System.out.println(e); } } // Function to insert multiple // documents in to the MongoDB public static void insertManyDocsIntoDb() { try { // establishConnections() Code // is defined above establishConnections(); // Creating the document // to be inserted Document document = new Document("title", "MongoDB") .append("about", "Open-Source database"); Document document1 = new Document("title", "retrieveDb") .append("about", "Open-source database"); // Adding the documents into a list List<Document> dblist = new ArrayList<Document>(); dblist.add(document); dblist.add(document1); // Insert the list of documents into DB collection.insertMany(dblist); System.out.println( "Documents inserted Successfully"); } catch (Exception e) { System.out.println( "Documents insertion failed"); System.out.println(e); } }} Output: For displaying all documents of collection, find() method is used. Here, the database has two documents namely β€œdocument” and β€œdocument1”, which are retrieved using find() method. We use an iterator since it will iterate over each document present in the list and display it to us. Following is code for displaying all the documents: // Java code to display documents from DB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void displayDocuments() { try { // establishConnections() Code // is defined above establishConnections(); System.out.println( "Displaying the list" + " of Documents"); // Get the list of documents from the DB FindIterable<Document> iterobj = collection.find(); // Print the documents using iterators Iterator itr = iterobj.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } catch (Exception e) { System.out.println( "Could not find the documents " + "or No document exists"); System.out.println(e); } }} Output: For updating the document, updateOne() method is used.Here, β€œFilters.eq” creates a filter that matches all documents with the name provided as argument. β€œUpdates.set()” is used to update the document as the given value in the argument. Following is the code for it: // Java code to update the documents in DB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void updateDocuments() { try { // establishConnections() Code // is defined above establishConnections(); MongoDatabase database = mongo.getDatabase("mongoDb"); MongoCollection<Document> collection = database.getCollection( "GFGCollection"); collection.updateOne( Filters.eq("title", "MongoDB"), Updates.set("about", "Database")); System.out.println( "Successfully updated" + " the document"); } catch (Exception e) { System.out.println( "Updation failed"); System.out.println(e); } }} Output: For deleting the document, deleteOne() method is used. Following is the code for deleting the document -> // Java code to update the documents in DB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void deleteDocuments() { try { // establishConnections() Code // is defined above establishConnections(); MongoDatabase database = mongo.getDatabase("mongoDb"); MongoCollection<Document> collection = database.getCollection( "GFGCollection"); collection.deleteOne( Filters.eq("title", "Open-Source Database")); System.out.println( "Successfully deleted" + " the document"); } catch (Exception e) { System.out.println( "Deletion failed"); System.out.println(e); } }} Output: β€œCollection.drop()” is used to drop the created collection. Following is the code for dropping the collection: // Java code to drop a collection in MongoDb import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void dropACollection() { try { // establishConnections() Code // is defined above establishConnections(); // Get the collection MongoCollection<Document> collection = database .getCollection( "GFGCollection"); // Drop the above collection collection.drop(); System.out.println( "Successfully dropped" + " collection"); } catch (Exception e) { System.out.println( "Drop failed"); System.out.println(e); } }} Output: For displaying the list of all collections, listCollectionNames() method is used.Here, we iterate over all the collections we created with the help of β€œfor()” statement. Database.listCollectionNames() is used to display the list of all collections present in the database.Following is the code for displaying all the collections: // Java code to display all collections import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void displayCollections() { try { // establishConnections() Code // is defined above establishConnections(); MongoDatabase database = mongo.getDatabase("mongoDb"); System.out.println( "Displaying the list" + " of all collections"); MongoCollection<Document> collection = database.getCollection( "GFGCollection"); for (String allColl : database .listCollectionNames()) { System.out.println(allColl); } } catch (Exception e) { System.out.println( "Collections display failed"); System.out.println(e); } }} Output: Java MongoDB Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Overriding in Java Multidimensional Arrays in Java LinkedList in Java ArrayList in Java Explain passport in Node.js Upload and Retrieve Image on MongoDB using Mongoose Mongoose | findOneAndReplace() Function Mongoose | countDocuments() Function Mongoose | exists() Function
[ { "code": null, "e": 23929, "s": 23901, "text": "\n12 May, 2020" }, { "code": null, "e": 24039, "s": 23929, "text": "MongoDB is an open-source cross-platform document database developed using C++. Some features of MongoDB are:" }, { "code": null, "e": 24070, "s": 24039, "text": "High and effective performance" }, { "code": null, "e": 24086, "s": 24070, "text": "Easily scalable" }, { "code": null, "e": 24104, "s": 24086, "text": "High availability" }, { "code": null, "e": 24137, "s": 24104, "text": "It can store high volume of data" }, { "code": null, "e": 24425, "s": 24137, "text": "It contains data in the form of collections and documents instead of rows and tables. A collection is a set of documents. The collection does not have schemas. It represents data in the form of a hierarchical model with which the storage of arrays and other data structures will be easy." }, { "code": null, "e": 24480, "s": 24425, "text": "The essentials components of MongoDB are listed below:" }, { "code": null, "e": 24875, "s": 24480, "text": "id: This field represents a unique field in MongoDB. This field is created by default.Collection: It is a set of MongoDB documents. It exists with a single database.Database: This is the container for collections. Multiple databases can be stored in a mongoDB server.Document: A record in mongoDB is called a document. It containes names and values.Field: It is a name-value pair in a document." }, { "code": null, "e": 24962, "s": 24875, "text": "id: This field represents a unique field in MongoDB. This field is created by default." }, { "code": null, "e": 25042, "s": 24962, "text": "Collection: It is a set of MongoDB documents. It exists with a single database." }, { "code": null, "e": 25145, "s": 25042, "text": "Database: This is the container for collections. Multiple databases can be stored in a mongoDB server." }, { "code": null, "e": 25228, "s": 25145, "text": "Document: A record in mongoDB is called a document. It containes names and values." }, { "code": null, "e": 25274, "s": 25228, "text": "Field: It is a name-value pair in a document." }, { "code": null, "e": 25341, "s": 25274, "text": "Note: Make sure to install and setup MongoDB JDBC driver and Java." }, { "code": null, "e": 25653, "s": 25341, "text": "Table of contents:\n1. Establishing connections to database\n2. Creating a MongoDb collection\n3. Getting a Collection\n4. Inserting Values into MongoDb\n5. Displaying the list of all Documents\n6. Updating documents in the MongoDB\n7. Deleting a Document\n8. Dropping of a Collection\n9. Displaying all the collections\n" }, { "code": null, "e": 25782, "s": 25653, "text": "For making the connection, you have to mention the database name. MongoDB creates a database by default if no name is mentioned." }, { "code": null, "e": 26251, "s": 25782, "text": "Firstly, import the required libraries for establishing the connection.Here, β€œMongoClient” is used to create the client for the database.β€œMongoCredential” is used for creating the credentials.And finally, to access the database β€œMongoDatabase” is used.Username will be: β€œGFGUser” and the database name will be β€œmongoDbβ€œ.The function β€œ.toCharArray()” is used to convert the password into a character array.The function β€œ.getDatabase()” is used for getting the database." }, { "code": null, "e": 26323, "s": 26251, "text": "Firstly, import the required libraries for establishing the connection." }, { "code": null, "e": 26390, "s": 26323, "text": "Here, β€œMongoClient” is used to create the client for the database." }, { "code": null, "e": 26446, "s": 26390, "text": "β€œMongoCredential” is used for creating the credentials." }, { "code": null, "e": 26507, "s": 26446, "text": "And finally, to access the database β€œMongoDatabase” is used." }, { "code": null, "e": 26576, "s": 26507, "text": "Username will be: β€œGFGUser” and the database name will be β€œmongoDbβ€œ." }, { "code": null, "e": 26662, "s": 26576, "text": "The function β€œ.toCharArray()” is used to convert the password into a character array." }, { "code": null, "e": 26726, "s": 26662, "text": "The function β€œ.getDatabase()” is used for getting the database." }, { "code": null, "e": 26784, "s": 26726, "text": "The following code establishes a connection to MongoDB ->" }, { "code": "// Java program for establishing connections// to MongoDb import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class ConnectionDB { public static void establishConnections() { try { MongoClient db = new MongoClient(\"localhost\", 27017); MongoCredential credential; credential = MongoCredential .createCredential( \"GFGUser\", \"mongoDb\", \"password\".toCharArray()); System.out.println( \"Successfully Connected\" + \" to the database\"); MongoDatabase database = db.getDatabase(\"mongoDb\"); System.out.println(\"Credentials are: \" + credential); } catch (Exception e) { System.out.println( \"Connection establishment failed\"); System.out.println(e); } }}", "e": 27812, "s": 26784, "text": null }, { "code": null, "e": 27820, "s": 27812, "text": "Output:" }, { "code": null, "e": 28051, "s": 27820, "text": "To create a collection com.mongodb.client.MongoDatabase class and createCollection() method is used. Here, β€œdatabase.createCollection()” creates a collection named as β€œGFGCollection”. Following is the code for creating collection:" }, { "code": "// Java program to create a MongoDb collection import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void createCollection( String collectionName) { try { // establishConnections() Code // is defined above establishConnections(); // Get the database instance MongoDatabase database = db.getDatabase(\"mongoDb\"); // Create the collection database.createCollection(collectionName); System.out.println( \"Collection created Successfully\"); } catch (Exception e) { System.out.println( \"Collection creation failed\"); System.out.println(e); } }}", "e": 28891, "s": 28051, "text": null }, { "code": null, "e": 28899, "s": 28891, "text": "Output:" }, { "code": null, "e": 29019, "s": 28899, "text": "For getting a collection, MongoCollection.getCollection() method is used. Below is the implementation of this approach:" }, { "code": "// Java program to retrieve a MongoDb collection import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void getCollection( String collectionName) { try { // establishConnections() Code // is defined above establishConnections(); // Retrieve the collection MongoCollection<Document> collection = database .getCollection(collectionName); System.out.println( \"Collection retrieved Successfully\"); } catch (Exception e) { System.out.println( \"Collection retrieval failed\"); System.out.println(e); } }}", "e": 29829, "s": 29019, "text": null }, { "code": null, "e": 29836, "s": 29829, "text": "Output" }, { "code": null, "e": 30057, "s": 29836, "text": "Only a document type of data can be inserted a MongoDB. Therefore, either we can create a document with the values to be inserted using append() method or pass a document directly into the MongoDB using .insert() method." }, { "code": null, "e": 30284, "s": 30057, "text": "Here, first, we created a new document as β€œtitle” and then append the β€œabout” section. Then, we have given the respective values to the documents. The function β€œ.insertOne()” is used to insert the document into the collection." }, { "code": null, "e": 30330, "s": 30284, "text": "Below is the implementation of this approach:" }, { "code": "// Java program to insert values into MongoDB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { // Function to insert only one // document in to the MongoDB public static void insertADocIntoDb() { try { // establishConnections() Code // is defined above establishConnections(); // Creating the document // to be inserted Document document = new Document(\"title\", \"MongoDB\") .append(\"about\", \"Open-Source database\") // Insert the document collection.insertOne(document); System.out.println( \"Document inserted Successfully\"); } catch (Exception e) { System.out.println( \"Document insertion failed\"); System.out.println(e); } } // Function to insert multiple // documents in to the MongoDB public static void insertManyDocsIntoDb() { try { // establishConnections() Code // is defined above establishConnections(); // Creating the document // to be inserted Document document = new Document(\"title\", \"MongoDB\") .append(\"about\", \"Open-Source database\"); Document document1 = new Document(\"title\", \"retrieveDb\") .append(\"about\", \"Open-source database\"); // Adding the documents into a list List<Document> dblist = new ArrayList<Document>(); dblist.add(document); dblist.add(document1); // Insert the list of documents into DB collection.insertMany(dblist); System.out.println( \"Documents inserted Successfully\"); } catch (Exception e) { System.out.println( \"Documents insertion failed\"); System.out.println(e); } }}", "e": 32482, "s": 30330, "text": null }, { "code": null, "e": 32490, "s": 32482, "text": "Output:" }, { "code": null, "e": 32557, "s": 32490, "text": "For displaying all documents of collection, find() method is used." }, { "code": null, "e": 32772, "s": 32557, "text": "Here, the database has two documents namely β€œdocument” and β€œdocument1”, which are retrieved using find() method. We use an iterator since it will iterate over each document present in the list and display it to us." }, { "code": null, "e": 32824, "s": 32772, "text": "Following is code for displaying all the documents:" }, { "code": "// Java code to display documents from DB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void displayDocuments() { try { // establishConnections() Code // is defined above establishConnections(); System.out.println( \"Displaying the list\" + \" of Documents\"); // Get the list of documents from the DB FindIterable<Document> iterobj = collection.find(); // Print the documents using iterators Iterator itr = iterobj.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } catch (Exception e) { System.out.println( \"Could not find the documents \" + \"or No document exists\"); System.out.println(e); } }}", "e": 33810, "s": 32824, "text": null }, { "code": null, "e": 33818, "s": 33810, "text": "Output:" }, { "code": null, "e": 34054, "s": 33818, "text": "For updating the document, updateOne() method is used.Here, β€œFilters.eq” creates a filter that matches all documents with the name provided as argument. β€œUpdates.set()” is used to update the document as the given value in the argument." }, { "code": null, "e": 34084, "s": 34054, "text": "Following is the code for it:" }, { "code": "// Java code to update the documents in DB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void updateDocuments() { try { // establishConnections() Code // is defined above establishConnections(); MongoDatabase database = mongo.getDatabase(\"mongoDb\"); MongoCollection<Document> collection = database.getCollection( \"GFGCollection\"); collection.updateOne( Filters.eq(\"title\", \"MongoDB\"), Updates.set(\"about\", \"Database\")); System.out.println( \"Successfully updated\" + \" the document\"); } catch (Exception e) { System.out.println( \"Updation failed\"); System.out.println(e); } }}", "e": 35034, "s": 34084, "text": null }, { "code": null, "e": 35042, "s": 35034, "text": "Output:" }, { "code": null, "e": 35148, "s": 35042, "text": "For deleting the document, deleteOne() method is used. Following is the code for deleting the document ->" }, { "code": "// Java code to update the documents in DB import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void deleteDocuments() { try { // establishConnections() Code // is defined above establishConnections(); MongoDatabase database = mongo.getDatabase(\"mongoDb\"); MongoCollection<Document> collection = database.getCollection( \"GFGCollection\"); collection.deleteOne( Filters.eq(\"title\", \"Open-Source Database\")); System.out.println( \"Successfully deleted\" + \" the document\"); } catch (Exception e) { System.out.println( \"Deletion failed\"); System.out.println(e); } }}", "e": 36086, "s": 35148, "text": null }, { "code": null, "e": 36094, "s": 36086, "text": "Output:" }, { "code": null, "e": 36205, "s": 36094, "text": "β€œCollection.drop()” is used to drop the created collection. Following is the code for dropping the collection:" }, { "code": "// Java code to drop a collection in MongoDb import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void dropACollection() { try { // establishConnections() Code // is defined above establishConnections(); // Get the collection MongoCollection<Document> collection = database .getCollection( \"GFGCollection\"); // Drop the above collection collection.drop(); System.out.println( \"Successfully dropped\" + \" collection\"); } catch (Exception e) { System.out.println( \"Drop failed\"); System.out.println(e); } }}", "e": 37091, "s": 36205, "text": null }, { "code": null, "e": 37099, "s": 37091, "text": "Output:" }, { "code": null, "e": 37429, "s": 37099, "text": "For displaying the list of all collections, listCollectionNames() method is used.Here, we iterate over all the collections we created with the help of β€œfor()” statement. Database.listCollectionNames() is used to display the list of all collections present in the database.Following is the code for displaying all the collections:" }, { "code": "// Java code to display all collections import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential; public class Collection { public static void displayCollections() { try { // establishConnections() Code // is defined above establishConnections(); MongoDatabase database = mongo.getDatabase(\"mongoDb\"); System.out.println( \"Displaying the list\" + \" of all collections\"); MongoCollection<Document> collection = database.getCollection( \"GFGCollection\"); for (String allColl : database .listCollectionNames()) { System.out.println(allColl); } } catch (Exception e) { System.out.println( \"Collections display failed\"); System.out.println(e); } }}", "e": 38427, "s": 37429, "text": null }, { "code": null, "e": 38435, "s": 38427, "text": "Output:" }, { "code": null, "e": 38440, "s": 38435, "text": "Java" }, { "code": null, "e": 38448, "s": 38440, "text": "MongoDB" }, { "code": null, "e": 38453, "s": 38448, "text": "Java" }, { "code": null, "e": 38551, "s": 38453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38560, "s": 38551, "text": "Comments" }, { "code": null, "e": 38573, "s": 38560, "text": "Old Comments" }, { "code": null, "e": 38605, "s": 38573, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 38624, "s": 38605, "text": "Overriding in Java" }, { "code": null, "e": 38656, "s": 38624, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38675, "s": 38656, "text": "LinkedList in Java" }, { "code": null, "e": 38693, "s": 38675, "text": "ArrayList in Java" }, { "code": null, "e": 38721, "s": 38693, "text": "Explain passport in Node.js" }, { "code": null, "e": 38773, "s": 38721, "text": "Upload and Retrieve Image on MongoDB using Mongoose" }, { "code": null, "e": 38813, "s": 38773, "text": "Mongoose | findOneAndReplace() Function" }, { "code": null, "e": 38850, "s": 38813, "text": "Mongoose | countDocuments() Function" } ]
Tower Of Hanoi Problem
Tower of Hanoi is a puzzle problem. Where we have three stands and n discs. Initially, Discs are placed in the first stand. We have to place discs into the third or destination stand, the second or auxiliary stand can be used as a helping stand. But there are some rules to follow. We can transfer only one disc for each movement. Only the topmost disc can be picked up from a stand. No bigger disc will be placed at the top of the smaller disc. This problem can be solved easily by recursion. At first, using recursion the top (n-1) discs are placed from source to auxiliary stand, then place the last disc from source to destination, then again place (n-1) disc from auxiliary stand to destination stand by recursion. Input: Number of discs: 3 Output: 1. Move disk 1 from A to C 2. Move disk 2 from A to B 3. Move disk 1 from C to B 4. Move disk 3 from A to C 5. Move disk 1 from B to A 6. Move disk 2 from B to C 7. Move disk 1 from A to C toh(n, s, a, d) Input: Number of discs, source, auxiliary, destination. Output: Steps to move discs from source to destination maintaining proper rules. Begin if n = 1, then display move disc from s to d toh(n-1, s, d, a) display move disc from s to d toh(n-1, a, s, d) End #include<iostream> using namespace std; void TOH(int n, char s, char a, char d) { static int count = 0; //store number of counts if(n == 1) { count++; cout << count<< ". Move disk " << n << " from "<<s <<" to "<<d<<endl; return; //base case, when only one disk } TOH(n-1, s, d, a); //recursive call the function count++; cout << count<< ". Move disk " << n << " from "<<s <<" to"<<d<<endl; TOH(n-1, a, s, d); } int main() { int n; cout << "Enter the number of disks: "; cin >> n; TOH(n, 'A','B','C'); } Enter the number of disks: 3 1. Move disk 1 from A to C 2. Move disk 2 from A to B 3. Move disk 1 from C to B 4. Move disk 3 from A to C 5. Move disk 1 from B to A 6. Move disk 2 from B to C 7. Move disk 1 from A to C
[ { "code": null, "e": 1308, "s": 1062, "text": "Tower of Hanoi is a puzzle problem. Where we have three stands and n discs. Initially, Discs are placed in the first stand. We have to place discs into the third or destination stand, the second or auxiliary stand can be used as a helping stand." }, { "code": null, "e": 1344, "s": 1308, "text": "But there are some rules to follow." }, { "code": null, "e": 1394, "s": 1344, "text": " We can transfer only one disc for each movement." }, { "code": null, "e": 1447, "s": 1394, "text": "Only the topmost disc can be picked up from a stand." }, { "code": null, "e": 1509, "s": 1447, "text": "No bigger disc will be placed at the top of the smaller disc." }, { "code": null, "e": 1783, "s": 1509, "text": "This problem can be solved easily by recursion. At first, using recursion the top (n-1) discs are placed from source to auxiliary stand, then place the last disc from source to destination, then again place (n-1) disc from auxiliary stand to destination stand by recursion." }, { "code": null, "e": 2006, "s": 1783, "text": "Input:\nNumber of discs: 3\nOutput:\n1. Move disk 1 from A to C\n2. Move disk 2 from A to B\n3. Move disk 1 from C to B\n4. Move disk 3 from A to C\n5. Move disk 1 from B to A\n6. Move disk 2 from B to C\n7. Move disk 1 from A to C" }, { "code": null, "e": 2022, "s": 2006, "text": "toh(n, s, a, d)" }, { "code": null, "e": 2078, "s": 2022, "text": "Input: Number of discs, source, auxiliary, destination." }, { "code": null, "e": 2159, "s": 2078, "text": "Output: Steps to move discs from source to destination maintaining proper rules." }, { "code": null, "e": 2299, "s": 2159, "text": "Begin\n if n = 1, then\n display move disc from s to d\n toh(n-1, s, d, a)\n\n display move disc from s to d\n toh(n-1, a, s, d)\nEnd" }, { "code": null, "e": 2884, "s": 2299, "text": "#include<iostream>\nusing namespace std;\n\nvoid TOH(int n, char s, char a, char d) {\n static int count = 0; //store number of counts\n if(n == 1) {\n count++;\n cout << count<< \". Move disk \" << n << \" from \"<<s <<\" to \"<<d<<endl;\n return; //base case, when only one disk\n }\n\n TOH(n-1, s, d, a); //recursive call the function\n count++;\n cout << count<< \". Move disk \" << n << \" from \"<<s <<\" to\"<<d<<endl;\n TOH(n-1, a, s, d);\n}\n\nint main() {\n int n;\n cout << \"Enter the number of disks: \";\n cin >> n;\n TOH(n, 'A','B','C');\n}" }, { "code": null, "e": 3102, "s": 2884, "text": "Enter the number of disks: 3\n1. Move disk 1 from A to C\n2. Move disk 2 from A to B\n3. Move disk 1 from C to B\n4. Move disk 3 from A to C\n5. Move disk 1 from B to A\n6. Move disk 2 from B to C\n7. Move disk 1 from A to C" } ]
Deploy a Flask App on Heroku and Connect it to a JawsDB-MySQL Database | by Edward Krueger | Towards Data Science
By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer. In this article, we’ll cover how to deploy an app with a Pipfile.lock to the cloud and connect the app to a cloud database. For more information on virtual environments or getting started with the environment and package manager Pipenv, check out this article! Newer developers often install everything at the system level due to a lack of understanding of, or experience with, virtual environments. Python packages installed with pip are placed at the system level. Retrieving requirements this way for every project creates an unmanageable global Python environment on your machine. Virtual environments allow you to compartmentalize your software while keeping an inventory of dependencies. Pipenv, a tool for virtual environment and Python package management, allows developers to create isolated software products that are easier to deploy, build upon, and modify. Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and for creating, using, and managing your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product. Heroku offers many software products, and we’ll need the Heroku cloud platform service to host an app and JawsDB to use a MySQL database. Don’t worry, creating an account and using these features is free! We are going to use the Heroku GUI to deploy a database and a Python app. In our previous deployment, we used an SQLite database. When using an SQLite database, every app redeployment will reset your database. Heroku’s JawsDB allows our data to persist through app updates. Additionally, hosting, configuring, patching, and managing the database is all done for you with JawsDB. Heroku allows us to deploy an app from a GitHub branch. Once we have a working app with a Pipfile pushed to GitHub, we are ready to make some final changes to the repository to prepare for deployment. Be sure to have your Pipfile at the project’s root directory so Heroku can find it! Note: These next changes allow our app to run on Unix systems. Gunicorn is not compatible with PCs, so you will not be able to test these changes locally if you are not using a Linux or Unix machine. Gunicorn is a Python WSGI HTTP server that will serve your Flask application on Heroku. By running the line below, you add gunicorn to your Pipfile. pipenv install gunicorn Create a Procfile in the project root folder and add the following line: web: gunicorn app:app The first app represents the name of the python file that runs your application or the name of the module where the app is located. The second represents your app name, i.e., app.py. This Procfile works with gunicorn and Heroku's Dynos to serve your app remotely. Set up an account with Heroku if you haven’t already, don’t worry all the features we show here are free! Go to your app on Heroku.com and click resources. Then type β€œJawsDB MySQL” into the addons box, as seen below. Select the free version and click provision. Great, we now have a MySQL database deployed for our app. Next, we need to integrate this new database into our app logic. First, let’s add Pymysql, a Python SQL library, to our Pipfile with the following. pipenv install pymysql Now let’s get our connection string and modify it for pymysql. Go to settings and look at the configuration variables. You’ll find a connection string that resembles the one below. mysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.amazonaws.com:3306/fq14casdf1rb3y3n We need to make a change to the DB connection string so that it uses the Pymysql driver. In a text editor, remove the mysql and add in its place mysql+pymysql and then save the updated string. mysql+pymysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.amazonaws.com:3306/fq14casdf1rb3y3n You’ll need to add this to your configuration variables on Heroku. To do this, go to settings, then config vars and update the connection string. Create a new file called .env and add the connection string for your cloud database as DB_CONN,shown below. DB_CONN=”mysql+pymysql://root:PASSWORD@HOSTNAME:3306/records_db” Note: Running pipenv shell gives us access to these hidden environmental variables. Similarly, we can access the hidden variables in Python with os. SQLALCHEMY_DB_URL = os.getenv(β€œDB_CONN”) Be sure to add the above line to your database.py file so that it ready to connect to the cloud! Once we have our app tested and working locally, we push all code to the master branch. Then on Heroku, go to deploy a new app to see the page below. Next on Heroku, select GitHub, enter the name of the repository and hit search. Once your username and repository appear, click connect. Then select the desired branch and click deploy. Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock. If you don’t use Pipenv, you will need to have a requiremnts.txt for this build to occur. Once again, place these files at your project’s root. Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message. The app is successfully deployed! Click to view button to see the deployed app on Heroku. You might run into an error where your tables have not been created before you attempt to get or post data. To solve this, we use the following line in our app.py. @app.before_first_requestdef setup(): db.create_all() We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch. Coding and building useful software requires the management of complexity. We discussed Github as a version control tool, Pipenv as an environment and package manager and some benefits of having cloud companies manage your databases. These tools help reduce the complexity of building software so developers can focus on building rather than managing. Practicing proper environment and package management is crucial for data scientists and developers who want their code deployed, built upon, or used in production. Using an environment and package manager such as Pipenv makes many processes, including deployment, more comfortable and more efficient! Additionally, having a well managed GitHub master branch with a Pipfile allowed Heroku’s severs to rebuild our app with minimal troubleshooting. This lets us deploy an app from a project directory on GitHub to Heroku in minutes. We hope this guide has been helpful and welcome comments and questions, thank you!
[ { "code": null, "e": 282, "s": 171, "text": "By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer." }, { "code": null, "e": 543, "s": 282, "text": "In this article, we’ll cover how to deploy an app with a Pipfile.lock to the cloud and connect the app to a cloud database. For more information on virtual environments or getting started with the environment and package manager Pipenv, check out this article!" }, { "code": null, "e": 976, "s": 543, "text": "Newer developers often install everything at the system level due to a lack of understanding of, or experience with, virtual environments. Python packages installed with pip are placed at the system level. Retrieving requirements this way for every project creates an unmanageable global Python environment on your machine. Virtual environments allow you to compartmentalize your software while keeping an inventory of dependencies." }, { "code": null, "e": 1152, "s": 976, "text": "Pipenv, a tool for virtual environment and Python package management, allows developers to create isolated software products that are easier to deploy, build upon, and modify." }, { "code": null, "e": 1450, "s": 1152, "text": "Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and for creating, using, and managing your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product." }, { "code": null, "e": 1655, "s": 1450, "text": "Heroku offers many software products, and we’ll need the Heroku cloud platform service to host an app and JawsDB to use a MySQL database. Don’t worry, creating an account and using these features is free!" }, { "code": null, "e": 1729, "s": 1655, "text": "We are going to use the Heroku GUI to deploy a database and a Python app." }, { "code": null, "e": 2034, "s": 1729, "text": "In our previous deployment, we used an SQLite database. When using an SQLite database, every app redeployment will reset your database. Heroku’s JawsDB allows our data to persist through app updates. Additionally, hosting, configuring, patching, and managing the database is all done for you with JawsDB." }, { "code": null, "e": 2319, "s": 2034, "text": "Heroku allows us to deploy an app from a GitHub branch. Once we have a working app with a Pipfile pushed to GitHub, we are ready to make some final changes to the repository to prepare for deployment. Be sure to have your Pipfile at the project’s root directory so Heroku can find it!" }, { "code": null, "e": 2519, "s": 2319, "text": "Note: These next changes allow our app to run on Unix systems. Gunicorn is not compatible with PCs, so you will not be able to test these changes locally if you are not using a Linux or Unix machine." }, { "code": null, "e": 2668, "s": 2519, "text": "Gunicorn is a Python WSGI HTTP server that will serve your Flask application on Heroku. By running the line below, you add gunicorn to your Pipfile." }, { "code": null, "e": 2692, "s": 2668, "text": "pipenv install gunicorn" }, { "code": null, "e": 2765, "s": 2692, "text": "Create a Procfile in the project root folder and add the following line:" }, { "code": null, "e": 2787, "s": 2765, "text": "web: gunicorn app:app" }, { "code": null, "e": 3051, "s": 2787, "text": "The first app represents the name of the python file that runs your application or the name of the module where the app is located. The second represents your app name, i.e., app.py. This Procfile works with gunicorn and Heroku's Dynos to serve your app remotely." }, { "code": null, "e": 3157, "s": 3051, "text": "Set up an account with Heroku if you haven’t already, don’t worry all the features we show here are free!" }, { "code": null, "e": 3268, "s": 3157, "text": "Go to your app on Heroku.com and click resources. Then type β€œJawsDB MySQL” into the addons box, as seen below." }, { "code": null, "e": 3436, "s": 3268, "text": "Select the free version and click provision. Great, we now have a MySQL database deployed for our app. Next, we need to integrate this new database into our app logic." }, { "code": null, "e": 3519, "s": 3436, "text": "First, let’s add Pymysql, a Python SQL library, to our Pipfile with the following." }, { "code": null, "e": 3542, "s": 3519, "text": "pipenv install pymysql" }, { "code": null, "e": 3723, "s": 3542, "text": "Now let’s get our connection string and modify it for pymysql. Go to settings and look at the configuration variables. You’ll find a connection string that resembles the one below." }, { "code": null, "e": 3844, "s": 3723, "text": "mysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.amazonaws.com:3306/fq14casdf1rb3y3n" }, { "code": null, "e": 3933, "s": 3844, "text": "We need to make a change to the DB connection string so that it uses the Pymysql driver." }, { "code": null, "e": 4037, "s": 3933, "text": "In a text editor, remove the mysql and add in its place mysql+pymysql and then save the updated string." }, { "code": null, "e": 4166, "s": 4037, "text": "mysql+pymysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.amazonaws.com:3306/fq14casdf1rb3y3n" }, { "code": null, "e": 4312, "s": 4166, "text": "You’ll need to add this to your configuration variables on Heroku. To do this, go to settings, then config vars and update the connection string." }, { "code": null, "e": 4420, "s": 4312, "text": "Create a new file called .env and add the connection string for your cloud database as DB_CONN,shown below." }, { "code": null, "e": 4485, "s": 4420, "text": "DB_CONN=”mysql+pymysql://root:PASSWORD@HOSTNAME:3306/records_db”" }, { "code": null, "e": 4634, "s": 4485, "text": "Note: Running pipenv shell gives us access to these hidden environmental variables. Similarly, we can access the hidden variables in Python with os." }, { "code": null, "e": 4675, "s": 4634, "text": "SQLALCHEMY_DB_URL = os.getenv(β€œDB_CONN”)" }, { "code": null, "e": 4772, "s": 4675, "text": "Be sure to add the above line to your database.py file so that it ready to connect to the cloud!" }, { "code": null, "e": 4922, "s": 4772, "text": "Once we have our app tested and working locally, we push all code to the master branch. Then on Heroku, go to deploy a new app to see the page below." }, { "code": null, "e": 5108, "s": 4922, "text": "Next on Heroku, select GitHub, enter the name of the repository and hit search. Once your username and repository appear, click connect. Then select the desired branch and click deploy." }, { "code": null, "e": 5423, "s": 5108, "text": "Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock. If you don’t use Pipenv, you will need to have a requiremnts.txt for this build to occur. Once again, place these files at your project’s root." }, { "code": null, "e": 5543, "s": 5423, "text": "Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message." }, { "code": null, "e": 5633, "s": 5543, "text": "The app is successfully deployed! Click to view button to see the deployed app on Heroku." }, { "code": null, "e": 5797, "s": 5633, "text": "You might run into an error where your tables have not been created before you attempt to get or post data. To solve this, we use the following line in our app.py." }, { "code": null, "e": 5855, "s": 5797, "text": "@app.before_first_requestdef setup(): db.create_all()" }, { "code": null, "e": 6063, "s": 5855, "text": "We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch." }, { "code": null, "e": 6415, "s": 6063, "text": "Coding and building useful software requires the management of complexity. We discussed Github as a version control tool, Pipenv as an environment and package manager and some benefits of having cloud companies manage your databases. These tools help reduce the complexity of building software so developers can focus on building rather than managing." }, { "code": null, "e": 6716, "s": 6415, "text": "Practicing proper environment and package management is crucial for data scientists and developers who want their code deployed, built upon, or used in production. Using an environment and package manager such as Pipenv makes many processes, including deployment, more comfortable and more efficient!" }, { "code": null, "e": 6945, "s": 6716, "text": "Additionally, having a well managed GitHub master branch with a Pipfile allowed Heroku’s severs to rebuild our app with minimal troubleshooting. This lets us deploy an app from a project directory on GitHub to Heroku in minutes." } ]
C++ Inheritance introduction | Practice | GeeksforGeeks
Create two classes: Cuboid The Cuboid class should have three data fields- length, width and height of int types. The class should have display() method, to print the length, width and height of the cuboid separated by space. CuboidVol The CuboidVol class is derived from Cuboid class, i.e., it is the sub-class of Cuboid class. The class should have read_input() method, to read the values of length, width and height of the Cuboid. The CuboidVol class should also overload the display() method to print the volume of the Cuboid ( length * width * height ). Input: The first line contains the number of test cases and one and only line of each test case contains 3 space separated integer denoting length, width, and height of the Cuboid Output: The output should consist of exactly two lines: In the first line, print the length, width, and height of the cuboid separated by space. In the second line, print the volume of the cuboid. Constraints: 0 <= (length, width, height) <= 100 Example: Sample input: 1 12 10 2 Sample output: 12 10 2 240 Explanation: As here length = 12, width = 10 and height = 2 Volume of the cuboid is = ( length * width * height ) = 12 * 10 * 2 = 240 0 atulharsh274Premium2 weeks ago class Cuboid { //Add your code here. protected: int length,width,height; public: void display(){ cout<<length<<" "<<width<<" "<<height<<endl; }}; class CuboidVol: public Cuboid{ //Add your code here. public: void read_input(int l , int w , int h){ length = l; width = w; height = h; } void display(){ cout<<length*height*width<<endl; }}; 0 vamsichippanapalli3 months ago // { Driver Code Starts//Initial Template for C++ #include <iostream>using namespace std; // } Driver Code Ends//User function Template for C++ class Cuboid { protected: int lenth; int width; int height; public: void read_input(int l,int w,int h) { lenth=l; width=w; height=h; } void display() { cout<<endl<<lenth<<" "<<width<<" "<<height<<endl; }}; class CuboidVol: public Cuboid{ public: void display() { cout<<endl<<(lenth*width*height); }}; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { int l, w, h; cin>>l>>w>>h; // Declare a CuboidVol object CuboidVol c_vol; // Read length width and height c_vol.read_input(l,w,h); // Print length, width and height c_vol.Cuboid::display(); // Print the Volume c_vol.display(); } return 0;} // } Driver Code Ends 0 vamsichippanapalli3 months ago void display() { cout<<lenth<<" "<<width<<" "<<height<<endl; } 0 tushargarg98683 months ago // { Driver Code Starts//Initial Template for C++ #include <iostream>using namespace std; // } Driver Code Ends//User function Template for C++ class Cuboid { //Add your code here. protected: int length; int width; int height; public: void display(){ cout<<length<<" "<<width<<" "<<height<<endl; }}; class CuboidVol: public Cuboid{ //Add your code here. public: void read_input(int l, int w, int h){ length=l; width=w; height=h; } void display(){ cout<<(length*width*height)<<endl; }}; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { int l, w, h; cin>>l>>w>>h; // Declare a CuboidVol object CuboidVol c_vol; // Read length width and height c_vol.read_input(l,w,h); // Print length, width and height c_vol.Cuboid::display(); // Print the Volume c_vol.display(); } return 0;} // } Driver Code Ends 0 himanshuharsh19993 months ago class Cuboid { protected: int length, width, height; public: void display(){ cout<<length<<" "<<width<<" "<<height<<endl; } }; class CuboidVol: public Cuboid { public: void read_input(int l, int w, int h) { length = l; width = w; height = h; } void display(){ cout<<length*width*height<<endl; } }; 0 martial9 months ago martial https://uploads.disquscdn.c... https://uploads.disquscdn.c... 0 Utkarsh Aditya This comment was deleted. 0 Utkarsh Aditya This comment was deleted. 0 Utkarsh Aditya This comment was deleted. 0 Utkarsh Aditya This comment was deleted. 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": 246, "s": 226, "text": "Create two classes:" }, { "code": null, "e": 452, "s": 246, "text": "Cuboid\nThe Cuboid class should have three data fields- length, width and height of int types. The class should have display() method, to print the length, width and height of the cuboid separated by space." }, { "code": null, "e": 786, "s": 452, "text": "CuboidVol \nThe CuboidVol class is derived from Cuboid class, i.e., it is the sub-class of Cuboid class. The class should have read_input() method, to read the values of length, width and height of the Cuboid. The CuboidVol class should also overload the display() method to print the volume of the Cuboid ( length * width * height )." }, { "code": null, "e": 793, "s": 786, "text": "Input:" }, { "code": null, "e": 966, "s": 793, "text": "The first line contains the number of test cases and one and only line of each test case contains 3 space separated integer denoting length, width, and height of the Cuboid" }, { "code": null, "e": 974, "s": 966, "text": "Output:" }, { "code": null, "e": 1178, "s": 974, "text": "The output should consist of exactly two lines: \nIn the first line, print the length, width, and height of the cuboid separated by space. \nIn the second line, print the volume of the cuboid.\nConstraints:" }, { "code": null, "e": 1223, "s": 1178, "text": "0 <= (length, width, height) <= 100\nExample:" }, { "code": null, "e": 1237, "s": 1223, "text": "Sample input:" }, { "code": null, "e": 1239, "s": 1237, "text": "1" }, { "code": null, "e": 1247, "s": 1239, "text": "12 10 2" }, { "code": null, "e": 1262, "s": 1247, "text": "Sample output:" }, { "code": null, "e": 1271, "s": 1262, "text": "12 10 2 " }, { "code": null, "e": 1275, "s": 1271, "text": "240" }, { "code": null, "e": 1288, "s": 1275, "text": "Explanation:" }, { "code": null, "e": 1335, "s": 1288, "text": "As here length = 12, width = 10 and height = 2" }, { "code": null, "e": 1389, "s": 1335, "text": "Volume of the cuboid is = ( length * width * height )" }, { "code": null, "e": 1441, "s": 1389, "text": " = 12 * 10 * 2" }, { "code": null, "e": 1485, "s": 1441, "text": " = 240" }, { "code": null, "e": 1489, "s": 1487, "text": "0" }, { "code": null, "e": 1520, "s": 1489, "text": "atulharsh274Premium2 weeks ago" }, { "code": null, "e": 1677, "s": 1520, "text": "class Cuboid { //Add your code here. protected: int length,width,height; public: void display(){ cout<<length<<\" \"<<width<<\" \"<<height<<endl; }};" }, { "code": null, "e": 1907, "s": 1677, "text": "class CuboidVol: public Cuboid{ //Add your code here. public: void read_input(int l , int w , int h){ length = l; width = w; height = h; } void display(){ cout<<length*height*width<<endl; }};" }, { "code": null, "e": 1911, "s": 1909, "text": "0" }, { "code": null, "e": 1942, "s": 1911, "text": "vamsichippanapalli3 months ago" }, { "code": null, "e": 1992, "s": 1942, "text": "// { Driver Code Starts//Initial Template for C++" }, { "code": null, "e": 2032, "s": 1992, "text": "#include <iostream>using namespace std;" }, { "code": null, "e": 2086, "s": 2032, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 2324, "s": 2086, "text": "class Cuboid { protected: int lenth; int width; int height; public: void read_input(int l,int w,int h) { lenth=l; width=w; height=h; } void display() { cout<<endl<<lenth<<\" \"<<width<<\" \"<<height<<endl; }};" }, { "code": null, "e": 2440, "s": 2324, "text": "class CuboidVol: public Cuboid{ public: void display() { cout<<endl<<(lenth*width*height); }};" }, { "code": null, "e": 2465, "s": 2440, "text": "// { Driver Code Starts." }, { "code": null, "e": 2850, "s": 2465, "text": "int main(){ int t; cin>>t; while(t--) { int l, w, h; cin>>l>>w>>h; // Declare a CuboidVol object CuboidVol c_vol; // Read length width and height c_vol.read_input(l,w,h); // Print length, width and height c_vol.Cuboid::display(); // Print the Volume c_vol.display(); } return 0;} // } Driver Code Ends" }, { "code": null, "e": 2852, "s": 2850, "text": "0" }, { "code": null, "e": 2883, "s": 2852, "text": "vamsichippanapalli3 months ago" }, { "code": null, "e": 2958, "s": 2883, "text": "void display() { cout<<lenth<<\" \"<<width<<\" \"<<height<<endl; }" }, { "code": null, "e": 2960, "s": 2958, "text": "0" }, { "code": null, "e": 2987, "s": 2960, "text": "tushargarg98683 months ago" }, { "code": null, "e": 3037, "s": 2987, "text": "// { Driver Code Starts//Initial Template for C++" }, { "code": null, "e": 3077, "s": 3037, "text": "#include <iostream>using namespace std;" }, { "code": null, "e": 3131, "s": 3077, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 3300, "s": 3131, "text": "class Cuboid { //Add your code here. protected: int length; int width; int height; public: void display(){ cout<<length<<\" \"<<width<<\" \"<<height<<endl; }};" }, { "code": null, "e": 3524, "s": 3300, "text": "class CuboidVol: public Cuboid{ //Add your code here. public: void read_input(int l, int w, int h){ length=l; width=w; height=h; } void display(){ cout<<(length*width*height)<<endl; }};" }, { "code": null, "e": 3549, "s": 3524, "text": "// { Driver Code Starts." }, { "code": null, "e": 3934, "s": 3549, "text": "int main(){ int t; cin>>t; while(t--) { int l, w, h; cin>>l>>w>>h; // Declare a CuboidVol object CuboidVol c_vol; // Read length width and height c_vol.read_input(l,w,h); // Print length, width and height c_vol.Cuboid::display(); // Print the Volume c_vol.display(); } return 0;} // } Driver Code Ends" }, { "code": null, "e": 3936, "s": 3934, "text": "0" }, { "code": null, "e": 3966, "s": 3936, "text": "himanshuharsh19993 months ago" }, { "code": null, "e": 4365, "s": 3966, "text": "class Cuboid \n{\n protected:\n int length, width, height;\n public:\n void display(){\n cout<<length<<\" \"<<width<<\" \"<<height<<endl;\n }\n};\n\nclass CuboidVol: public Cuboid\n{\n public:\n void read_input(int l, int w, int h)\n {\n length = l;\n width = w;\n height = h;\n }\n void display(){\n cout<<length*width*height<<endl;\n }\n};" }, { "code": null, "e": 4367, "s": 4365, "text": "0" }, { "code": null, "e": 4387, "s": 4367, "text": "martial9 months ago" }, { "code": null, "e": 4395, "s": 4387, "text": "martial" }, { "code": null, "e": 4457, "s": 4395, "text": "https://uploads.disquscdn.c... https://uploads.disquscdn.c..." }, { "code": null, "e": 4459, "s": 4457, "text": "0" }, { "code": null, "e": 4474, "s": 4459, "text": "Utkarsh Aditya" }, { "code": null, "e": 4500, "s": 4474, "text": "This comment was deleted." }, { "code": null, "e": 4502, "s": 4500, "text": "0" }, { "code": null, "e": 4517, "s": 4502, "text": "Utkarsh Aditya" }, { "code": null, "e": 4543, "s": 4517, "text": "This comment was deleted." }, { "code": null, "e": 4545, "s": 4543, "text": "0" }, { "code": null, "e": 4560, "s": 4545, "text": "Utkarsh Aditya" }, { "code": null, "e": 4586, "s": 4560, "text": "This comment was deleted." }, { "code": null, "e": 4588, "s": 4586, "text": "0" }, { "code": null, "e": 4603, "s": 4588, "text": "Utkarsh Aditya" }, { "code": null, "e": 4629, "s": 4603, "text": "This comment was deleted." }, { "code": null, "e": 4775, "s": 4629, "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": 4811, "s": 4775, "text": " Login to access your submissions. " }, { "code": null, "e": 4821, "s": 4811, "text": "\nProblem\n" }, { "code": null, "e": 4831, "s": 4821, "text": "\nContest\n" }, { "code": null, "e": 4894, "s": 4831, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5042, "s": 4894, "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": 5250, "s": 5042, "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": 5356, "s": 5250, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Operations on struct variables in C
Here we will see what type of operations can be performed on struct variables. Here basically one operation can be performed for struct. The operation is assignment operation. Some other operations like equality check or other are not available for stack. #include <stdio.h> typedef struct { //define a structure for complex objects int real, imag; }complex; void displayComplex(complex c){ printf("(%d + %di)\n", c.real, c.imag); } main() { complex c1 = {5, 2}; complex c2 = {8, 6}; printf("Complex numbers are:\n"); displayComplex(c1); displayComplex(c2); } Complex numbers are: (5 + 2i) (8 + 6i) This works fine as we have assigned some values into struct. Now if we want to compare two struct objects, let us see the difference. #include <stdio.h> typedef struct { //define a structure for complex objects int real, imag; }complex; void displayComplex(complex c){ printf("(%d + %di)\n", c.real, c.imag); } main() { complex c1 = {5, 2}; complex c2 = c1; printf("Complex numbers are:\n"); displayComplex(c1); displayComplex(c2); if(c1 == c2){ printf("Complex numbers are same."); } else { printf("Complex numbers are not same."); } } [Error] invalid operands to binary == (have 'complex' and 'complex')
[ { "code": null, "e": 1318, "s": 1062, "text": "Here we will see what type of operations can be performed on struct variables. Here basically one operation can be performed for struct. The operation is assignment operation. Some other operations like equality check or other are not available for stack." }, { "code": null, "e": 1643, "s": 1318, "text": "#include <stdio.h>\ntypedef struct { //define a structure for complex objects\n int real, imag;\n}complex;\nvoid displayComplex(complex c){\n printf(\"(%d + %di)\\n\", c.real, c.imag);\n}\nmain() {\n complex c1 = {5, 2};\n complex c2 = {8, 6};\n printf(\"Complex numbers are:\\n\");\n displayComplex(c1);\n displayComplex(c2);\n}" }, { "code": null, "e": 1682, "s": 1643, "text": "Complex numbers are:\n(5 + 2i)\n(8 + 6i)" }, { "code": null, "e": 1816, "s": 1682, "text": "This works fine as we have assigned some values into struct. Now if we want to compare two struct objects, let us see the difference." }, { "code": null, "e": 2261, "s": 1816, "text": "#include <stdio.h>\ntypedef struct { //define a structure for complex objects\n int real, imag;\n}complex;\nvoid displayComplex(complex c){\n printf(\"(%d + %di)\\n\", c.real, c.imag);\n}\nmain() {\n complex c1 = {5, 2};\n complex c2 = c1;\n printf(\"Complex numbers are:\\n\");\n displayComplex(c1);\n displayComplex(c2);\n if(c1 == c2){\n printf(\"Complex numbers are same.\");\n } else {\n printf(\"Complex numbers are not same.\");\n }\n}" }, { "code": null, "e": 2330, "s": 2261, "text": "[Error] invalid operands to binary == (have 'complex' and 'complex')" } ]
How can we modify an existing module in Java 9?
The module is a named, self-describing collection of code and data. The code has been organized as a set of packages containing types like Java classes and interfaces. The data includes resources and other kinds of static information. We need to declare a module then add module-info.java at the root of the source code. Below is the template of the "module-info.java" file. module <module-name> { requires <module-name1> ; requires <module-name2>; exports <package-name1>; exports <package-name2>; exports <package-name> to <module-name> } We can use certain command-line options that help us to modify existing modules and add dependencies to them, export additional packages. Below are the few command-line commands that can be used to modify an existing module. 1) --add-reads <module>=<target-module>(,<target-module>)* The above command can update <module> to read < target-module>, regardless of the module declaration. <target-module> can be ALL-UNNAMED to read all nameless modules. 2) --add-exports <module>/<package>=<target-module>(,<target-module>)* The above command can update <module> to export <package> to <target-module>, regardless of the module declaration. <target-module> can be ALL-UNNAMED to export to all nameless modules. 3) --add-opens <module>/<package>=<target-module>(,<target-module>)* The above command update <module> to open <package> to <target-module>, regardless of the module declaration. 4) --patch-module <module>=<file>(;<file>)* The above command can replace or increase a module with classes and resources in jar files or directories.
[ { "code": null, "e": 1383, "s": 1062, "text": "The module is a named, self-describing collection of code and data. The code has been organized as a set of packages containing types like Java classes and interfaces. The data includes resources and other kinds of static information. We need to declare a module then add module-info.java at the root of the source code." }, { "code": null, "e": 1437, "s": 1383, "text": "Below is the template of the \"module-info.java\" file." }, { "code": null, "e": 1620, "s": 1437, "text": "module <module-name> {\n requires <module-name1> ;\n requires <module-name2>;\n\n exports <package-name1>;\n exports <package-name2>;\n\n exports <package-name> to <module-name>\n}" }, { "code": null, "e": 1758, "s": 1620, "text": "We can use certain command-line options that help us to modify existing modules and add dependencies to them, export additional packages." }, { "code": null, "e": 1845, "s": 1758, "text": "Below are the few command-line commands that can be used to modify an existing module." }, { "code": null, "e": 1904, "s": 1845, "text": "1) --add-reads <module>=<target-module>(,<target-module>)*" }, { "code": null, "e": 2071, "s": 1904, "text": "The above command can update <module> to read < target-module>, regardless of the module declaration. <target-module> can be ALL-UNNAMED to read all nameless modules." }, { "code": null, "e": 2142, "s": 2071, "text": "2) --add-exports <module>/<package>=<target-module>(,<target-module>)*" }, { "code": null, "e": 2328, "s": 2142, "text": "The above command can update <module> to export <package> to <target-module>, regardless of the module declaration. <target-module> can be ALL-UNNAMED to export to all nameless modules." }, { "code": null, "e": 2397, "s": 2328, "text": "3) --add-opens <module>/<package>=<target-module>(,<target-module>)*" }, { "code": null, "e": 2507, "s": 2397, "text": "The above command update <module> to open <package> to <target-module>, regardless of the module declaration." }, { "code": null, "e": 2551, "s": 2507, "text": "4) --patch-module <module>=<file>(;<file>)*" }, { "code": null, "e": 2658, "s": 2551, "text": "The above command can replace or increase a module with classes and resources in jar files or directories." } ]
Custom Object Detection using TensorFlow from Scratch | by Khush Patel | Towards Data Science
In this tutorial, we’re going to get our hands dirty and train our own dog (corgi) detector using a pre-trained SSD MobileNet V2 model. Instead of training your own model from scratch, you can build on existing models and fine-tune them for your own purpose without requiring as much computing power. Install Tensorflow using the following command: $ pip install tensorflow If you have a GPU that you can use with Tensorflow: $ pip install tensorflow-gpu $ pip install pillow Cython lxml jupyter matplotlib Install protobuf using Homebrew (you can learn more about Homebrew here) $ brew install protobuf For protobuf installation on other OS, follow the instructions here. In this tutorial, we’re going to use resources in the Tensorflow models repository. Since it does not come with the Tensorflow installation, we need to clone it from their Github repo: First change into the Tensorflow directory: # For example: ~/anaconda/envs/<your_env_name>/lib/python3.6/site-packages/tensorflow$ cd <path_to_your_tensorflow_installation> Clone the Tensorflow models repository: $ git clone https://github.com/tensorflow/models.git From this point on, this directory will be referred to as the modelsdirectory Every time you start a new terminal window to work with the pre-trained models, it is important to compile Protobuf and change your PYTHONPATH. Run the following from your terminal: $ cd <path_to_your_tensorflow_installation>/models/research/$ protoc object_detection/protos/*.proto --python_out=.$ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim Run a quick test to confirm that the Object Detection API is working properly: $ python object_detection/builders/model_builder_test.py If the result looks like the following, you’re ready to proceed to the next steps! ...............----------------------------------------------------------------------Ran 15 tests in 0.123sOK To make this tutorial easier to follow along, create the following folder structure within the models directory you just cloned: models β”œβ”€β”€ annotations | └── xmls β”œβ”€β”€ images β”œβ”€β”€ checkpoints β”œβ”€β”€ tf_record β”œβ”€β”€ research ... These folders will be used to store the required components for our model as we proceed. You can collect data in either images or video format. Here I mentioned both ways to collect data. Data preparation is the most important part of training your own model. Since we’re going to train a corgi detector, we must collect pictures of corgis! About 200 of them would be sufficient. I recommend using google-images-download to download images. It searches Google Images and then downloads images based on the inputs you provided. In the inputs, you can specify search parameters such as keywords, number of images, image format, image size, and usage rights. Since we’re downloading more than 100 images at a time, we need a chromedriver in the models directory (download here). Once you have the chromedriver ready, you could use this sample command to download images. Make sure all your images are in the jpg format: # From the models directory$ googleimagesdownload --keywords 'welsh corgi dog' \--limit 200 \--size medium \--chromedriver ./chromedriver \--format jpg After downloading, save all images to models/images/. To make subsequent processes easier, let's rename the images as numbers (e.g. 1.jpg, 2.jpg) by running the following script: import ospath = 'models/images/'counter = 1for f in os.listdir(path): suffix = f.split('.')[-1] if suffix == 'jpg' or suffix == 'png': new = '{}.{}'.format(str(counter), suffix) os.rename(path + f, path + new) counter = int(counter) + 1 medium.com Once you’ve collected all the images you need, you need to label them manually. There are many packages that serve this purpose. labelImg is a popular choice. labelImg provides a user-friendly GUI. Plus, it saves label files (.xml) in the popular Pascal VOC format. If you want these images for training YOLO(You only Look Once) then use YOLO. Just set the current directory and Save directory as per our structure. Here's what a labelled image looks like in labelImg: Double check that every image has a corresponding .xml file and save them in models/annotations/xmls/. For a large number of annotations, you can use different shortcuts mentioned below: Ctrl + u - Load all of the images from a directoryCtrl + r - Change the default annotation target dirCtrl + s - Savew - Create a rect boxd - Next imagea - Previous imagedel - Delete the selected rect boxCtrl++ - Zoom inCtrl-- - Zoom outCtrl + d - Copy the current label and rect boxSpace - Flag the current image as verified↑→↓←Keyboard arrows to move selected rect box Classes need to be listed in the label map. Since we’re only detecting corgis, the label map should contain only one item like the following: item { id: 1 name: 'corgi'} Note that id must start from 1, because 0 is a reserved id. Save this file as label_map.pbtxt in models/annotations/ trainval.txt is a list of image names without file extensions. Since we have sequential numbers for image names, the list should look like this: 123...198199200 Save this file as trainval.txt in models/annotations/ You can use this link to create XML files to CSV. We have all images and their bounding boxes are in XML format. Also all image has separate XML file so using this code we are creating a CSV file which contains all the XML files and their bounding box co-ordinates to single CSV file which is input for creating TFrecords. TFRecord is an important data format designed for Tensorflow. (Read more about it here). Before you can train your custom object detector, you must convert your data into the TFRecord format. Since we need to train as well as validate our model, the data set will be split into training (train.record) and validation sets (val.record). The purpose of training set is straight forward - it is the set of examples the model learns from. The validation set is a set of examples used DURING TRAINING to iteratively assess model accuracy. We’re going to use create_tf_record.py to convert our data set into train.record and val.record. Download here and save it to models/research/object_detection/dataset_tools/. Just change the label name in if row_label == β€˜Label1’: as per your classifications. This script is preconfigured to do 70–30 train-val split. Execute it by running: # From the models directory$ python research/object_detection/dataset_tools/create_tf_record.py If the script is executed successfully, train.record and val.record should appear in your models/research/ directory. Move them into the models/tf_record/ directory. There are many pre-trained object detection models available in the model zoo. In order to train them using our custom data set, the models need to be restored in Tensorflow using their checkpoints (.ckpt files), which are records of previous model states. For this tutorial, we’re going to download ssd_mobilenet_v2_coco here and save its model checkpoint files (model.ckpt.meta, model.ckpt.index, model.ckpt.data-00000-of-00001) to our models/checkpoints/ directory. Each of the pretrained models has a config file that contains details about the model. To detect our custom class, the config file needs to be modified accordingly. The config files are included in the models directory you cloned in the very beginning. You can find them in: models/research/object_detection/samples/configs In our case, we’ll modify the config file for ssd_mobilenet_v2_coco. Make a copy of it first and save it in the models/ directory. Here are the items we need to change: Since we’re only trying to detect corgis, change num_classes to 1fine_tune_checkpoint tells the model which checkpoint file to use. Set this to checkpoints/model.ckptThe model also needs to know where the TFRecord files and label maps are for both training and validation sets. Since our train.record and val.record are saved in tf_record folder, our config should reflect that: Since we’re only trying to detect corgis, change num_classes to 1 fine_tune_checkpoint tells the model which checkpoint file to use. Set this to checkpoints/model.ckpt The model also needs to know where the TFRecord files and label maps are for both training and validation sets. Since our train.record and val.record are saved in tf_record folder, our config should reflect that: train_input_reader: { tf_record_input_reader { input_path: "tf_record/train.record" } label_map_path: "annotations/label_map.pbtxt"}eval_input_reader: { tf_record_input_reader { input_path: "tf_record/val.record" } label_map_path: "annotations/label_map.pbtxt" shuffle: false num_readers: 1} At this point, your models directory should look like this: models β”œβ”€β”€ annotations | β”œβ”€β”€ label_map.pbtxt | β”œβ”€β”€ trainval.txt | └── xmls | β”œβ”€β”€ 1.xml | β”œβ”€β”€ 2.xml | β”œβ”€β”€ ... | β”œβ”€β”€ images | β”œβ”€β”€ 1.jpg | β”œβ”€β”€ 2.jpg | β”œβ”€β”€ ... | β”œβ”€β”€ checkpoints | β”œβ”€β”€ model.ckpt.data-00000-of-00001 | β”œβ”€β”€ model.ckpt.index | └── model.ckpt.meta | β”œβ”€β”€ tf_record | β”œβ”€β”€ train.record | └── val.record | β”œβ”€β”€ research | β”œβ”€β”€ ... ... If you have successfully completed all previous steps, you’re ready to start training! Follow the steps below: # Change into the models directory$ cd tensorflow/models# Make directory for storing training progress$ mkdir train# Make directory for storing validation results$ mkdir eval# Begin training$ python research/object_detection/train.py \ --logtostderr \ --train_dir=train \ --pipeline_config_path=ssd_mobilenet_v2_coco.config Training time varies depending on the computing power of your machine. Evaluation can be run in parallel with training. The eval.py script checks the train directory for progress and evaluate the model based on the most recent checkpoint. # From the models directory$ python research/object_detection/eval.py \ --logtostderr \ --pipeline_config_path=ssd_mobilenet_v2_coco.config \ --checkpoint_dir=train \ --eval_dir=eval You can visualize model training progress using Tensorboard: # From the models directory$ tensorboard --logdir=./ Based on the graphs output by Tensorboard, you may decide when you want to stop training. Usually, you may stop the process when the loss function is tapering off and no longer decreasing by a significant amount. In my case, I stopped at step 3258. Once you finish training your model, you can export your model to be used for inference. If you’ve been following the folder structure, use the following command: # From the models directory$ mkdir fine_tuned_model$ python research/object_detection/export_inference_graph.py \ --input_type image_tensor \ --pipeline_config_path ssd_mobilenet_v2_coco.config \ --trained_checkpoint_prefix train/model.ckpt-<the_highest_checkpoint_number> \ --output_directory fine_tuned_model Now that you have a model, you can use it to detect corgis in pictures and videos! For the purpose of demonstration, we’re going to detect corgis in an image. Before you proceed, pick an image you want to test the model with. The models directory came with a notebook file (.ipynb) that we can use to get inference with a few tweaks. It is located at models/research/object_detection/object_detection_tutorial.ipynb. Follow the steps below to tweak the notebook: MODEL_NAME = 'ssd_mobilenet_v2_coco_2018_03_29'PATH_TO_CKPT = 'path/to/your/frozen_inference_graph.pb'PATH_TO_LABELS = 'models/annotations/label_map.pbtxt'NUM_CLASSES = 1Comment out cell #5 completely (just below Download Model)Since we’re only testing on one image, comment out PATH_TO_TEST_IMAGES_DIR and TEST_IMAGE_PATHS in cell #9 (just below Detection)In cell #11 (the last cell), remove the for-loop, unindent its content, and add path to your test image: MODEL_NAME = 'ssd_mobilenet_v2_coco_2018_03_29' PATH_TO_CKPT = 'path/to/your/frozen_inference_graph.pb' PATH_TO_LABELS = 'models/annotations/label_map.pbtxt' NUM_CLASSES = 1 Comment out cell #5 completely (just below Download Model) Since we’re only testing on one image, comment out PATH_TO_TEST_IMAGES_DIR and TEST_IMAGE_PATHS in cell #9 (just below Detection) In cell #11 (the last cell), remove the for-loop, unindent its content, and add path to your test image: imagepath = 'path/to/image_you_want_to_test.jpg After following through the steps, run the notebook and you should see the corgi in your test image highlighted by a bounding box! There you have your custom corgi detector! Tensorflow Object Detection Model Documentation Do visit my Website: http://www.khushpatel.com
[ { "code": null, "e": 308, "s": 172, "text": "In this tutorial, we’re going to get our hands dirty and train our own dog (corgi) detector using a pre-trained SSD MobileNet V2 model." }, { "code": null, "e": 473, "s": 308, "text": "Instead of training your own model from scratch, you can build on existing models and fine-tune them for your own purpose without requiring as much computing power." }, { "code": null, "e": 521, "s": 473, "text": "Install Tensorflow using the following command:" }, { "code": null, "e": 546, "s": 521, "text": "$ pip install tensorflow" }, { "code": null, "e": 598, "s": 546, "text": "If you have a GPU that you can use with Tensorflow:" }, { "code": null, "e": 627, "s": 598, "text": "$ pip install tensorflow-gpu" }, { "code": null, "e": 679, "s": 627, "text": "$ pip install pillow Cython lxml jupyter matplotlib" }, { "code": null, "e": 752, "s": 679, "text": "Install protobuf using Homebrew (you can learn more about Homebrew here)" }, { "code": null, "e": 776, "s": 752, "text": "$ brew install protobuf" }, { "code": null, "e": 845, "s": 776, "text": "For protobuf installation on other OS, follow the instructions here." }, { "code": null, "e": 1030, "s": 845, "text": "In this tutorial, we’re going to use resources in the Tensorflow models repository. Since it does not come with the Tensorflow installation, we need to clone it from their Github repo:" }, { "code": null, "e": 1074, "s": 1030, "text": "First change into the Tensorflow directory:" }, { "code": null, "e": 1203, "s": 1074, "text": "# For example: ~/anaconda/envs/<your_env_name>/lib/python3.6/site-packages/tensorflow$ cd <path_to_your_tensorflow_installation>" }, { "code": null, "e": 1243, "s": 1203, "text": "Clone the Tensorflow models repository:" }, { "code": null, "e": 1296, "s": 1243, "text": "$ git clone https://github.com/tensorflow/models.git" }, { "code": null, "e": 1374, "s": 1296, "text": "From this point on, this directory will be referred to as the modelsdirectory" }, { "code": null, "e": 1518, "s": 1374, "text": "Every time you start a new terminal window to work with the pre-trained models, it is important to compile Protobuf and change your PYTHONPATH." }, { "code": null, "e": 1556, "s": 1518, "text": "Run the following from your terminal:" }, { "code": null, "e": 1720, "s": 1556, "text": "$ cd <path_to_your_tensorflow_installation>/models/research/$ protoc object_detection/protos/*.proto --python_out=.$ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim" }, { "code": null, "e": 1799, "s": 1720, "text": "Run a quick test to confirm that the Object Detection API is working properly:" }, { "code": null, "e": 1856, "s": 1799, "text": "$ python object_detection/builders/model_builder_test.py" }, { "code": null, "e": 1939, "s": 1856, "text": "If the result looks like the following, you’re ready to proceed to the next steps!" }, { "code": null, "e": 2049, "s": 1939, "text": "...............----------------------------------------------------------------------Ran 15 tests in 0.123sOK" }, { "code": null, "e": 2178, "s": 2049, "text": "To make this tutorial easier to follow along, create the following folder structure within the models directory you just cloned:" }, { "code": null, "e": 2298, "s": 2178, "text": "models β”œβ”€β”€ annotations | └── xmls β”œβ”€β”€ images β”œβ”€β”€ checkpoints β”œβ”€β”€ tf_record β”œβ”€β”€ research ..." }, { "code": null, "e": 2387, "s": 2298, "text": "These folders will be used to store the required components for our model as we proceed." }, { "code": null, "e": 2486, "s": 2387, "text": "You can collect data in either images or video format. Here I mentioned both ways to collect data." }, { "code": null, "e": 2678, "s": 2486, "text": "Data preparation is the most important part of training your own model. Since we’re going to train a corgi detector, we must collect pictures of corgis! About 200 of them would be sufficient." }, { "code": null, "e": 2954, "s": 2678, "text": "I recommend using google-images-download to download images. It searches Google Images and then downloads images based on the inputs you provided. In the inputs, you can specify search parameters such as keywords, number of images, image format, image size, and usage rights." }, { "code": null, "e": 3215, "s": 2954, "text": "Since we’re downloading more than 100 images at a time, we need a chromedriver in the models directory (download here). Once you have the chromedriver ready, you could use this sample command to download images. Make sure all your images are in the jpg format:" }, { "code": null, "e": 3367, "s": 3215, "text": "# From the models directory$ googleimagesdownload --keywords 'welsh corgi dog' \\--limit 200 \\--size medium \\--chromedriver ./chromedriver \\--format jpg" }, { "code": null, "e": 3546, "s": 3367, "text": "After downloading, save all images to models/images/. To make subsequent processes easier, let's rename the images as numbers (e.g. 1.jpg, 2.jpg) by running the following script:" }, { "code": null, "e": 3810, "s": 3546, "text": "import ospath = 'models/images/'counter = 1for f in os.listdir(path): suffix = f.split('.')[-1] if suffix == 'jpg' or suffix == 'png': new = '{}.{}'.format(str(counter), suffix) os.rename(path + f, path + new) counter = int(counter) + 1" }, { "code": null, "e": 3821, "s": 3810, "text": "medium.com" }, { "code": null, "e": 3980, "s": 3821, "text": "Once you’ve collected all the images you need, you need to label them manually. There are many packages that serve this purpose. labelImg is a popular choice." }, { "code": null, "e": 4237, "s": 3980, "text": "labelImg provides a user-friendly GUI. Plus, it saves label files (.xml) in the popular Pascal VOC format. If you want these images for training YOLO(You only Look Once) then use YOLO. Just set the current directory and Save directory as per our structure." }, { "code": null, "e": 4290, "s": 4237, "text": "Here's what a labelled image looks like in labelImg:" }, { "code": null, "e": 4393, "s": 4290, "text": "Double check that every image has a corresponding .xml file and save them in models/annotations/xmls/." }, { "code": null, "e": 4477, "s": 4393, "text": "For a large number of annotations, you can use different shortcuts mentioned below:" }, { "code": null, "e": 4847, "s": 4477, "text": "Ctrl + u - Load all of the images from a directoryCtrl + r - Change the default annotation target dirCtrl + s - Savew - Create a rect boxd - Next imagea - Previous imagedel - Delete the selected rect boxCtrl++ - Zoom inCtrl-- - Zoom outCtrl + d - Copy the current label and rect boxSpace - Flag the current image as verified↑→↓←Keyboard arrows to move selected rect box" }, { "code": null, "e": 4989, "s": 4847, "text": "Classes need to be listed in the label map. Since we’re only detecting corgis, the label map should contain only one item like the following:" }, { "code": null, "e": 5023, "s": 4989, "text": "item { id: 1 name: 'corgi'}" }, { "code": null, "e": 5083, "s": 5023, "text": "Note that id must start from 1, because 0 is a reserved id." }, { "code": null, "e": 5140, "s": 5083, "text": "Save this file as label_map.pbtxt in models/annotations/" }, { "code": null, "e": 5285, "s": 5140, "text": "trainval.txt is a list of image names without file extensions. Since we have sequential numbers for image names, the list should look like this:" }, { "code": null, "e": 5301, "s": 5285, "text": "123...198199200" }, { "code": null, "e": 5355, "s": 5301, "text": "Save this file as trainval.txt in models/annotations/" }, { "code": null, "e": 5678, "s": 5355, "text": "You can use this link to create XML files to CSV. We have all images and their bounding boxes are in XML format. Also all image has separate XML file so using this code we are creating a CSV file which contains all the XML files and their bounding box co-ordinates to single CSV file which is input for creating TFrecords." }, { "code": null, "e": 5870, "s": 5678, "text": "TFRecord is an important data format designed for Tensorflow. (Read more about it here). Before you can train your custom object detector, you must convert your data into the TFRecord format." }, { "code": null, "e": 6212, "s": 5870, "text": "Since we need to train as well as validate our model, the data set will be split into training (train.record) and validation sets (val.record). The purpose of training set is straight forward - it is the set of examples the model learns from. The validation set is a set of examples used DURING TRAINING to iteratively assess model accuracy." }, { "code": null, "e": 6387, "s": 6212, "text": "We’re going to use create_tf_record.py to convert our data set into train.record and val.record. Download here and save it to models/research/object_detection/dataset_tools/." }, { "code": null, "e": 6472, "s": 6387, "text": "Just change the label name in if row_label == β€˜Label1’: as per your classifications." }, { "code": null, "e": 6553, "s": 6472, "text": "This script is preconfigured to do 70–30 train-val split. Execute it by running:" }, { "code": null, "e": 6649, "s": 6553, "text": "# From the models directory$ python research/object_detection/dataset_tools/create_tf_record.py" }, { "code": null, "e": 6815, "s": 6649, "text": "If the script is executed successfully, train.record and val.record should appear in your models/research/ directory. Move them into the models/tf_record/ directory." }, { "code": null, "e": 7072, "s": 6815, "text": "There are many pre-trained object detection models available in the model zoo. In order to train them using our custom data set, the models need to be restored in Tensorflow using their checkpoints (.ckpt files), which are records of previous model states." }, { "code": null, "e": 7284, "s": 7072, "text": "For this tutorial, we’re going to download ssd_mobilenet_v2_coco here and save its model checkpoint files (model.ckpt.meta, model.ckpt.index, model.ckpt.data-00000-of-00001) to our models/checkpoints/ directory." }, { "code": null, "e": 7449, "s": 7284, "text": "Each of the pretrained models has a config file that contains details about the model. To detect our custom class, the config file needs to be modified accordingly." }, { "code": null, "e": 7559, "s": 7449, "text": "The config files are included in the models directory you cloned in the very beginning. You can find them in:" }, { "code": null, "e": 7608, "s": 7559, "text": "models/research/object_detection/samples/configs" }, { "code": null, "e": 7739, "s": 7608, "text": "In our case, we’ll modify the config file for ssd_mobilenet_v2_coco. Make a copy of it first and save it in the models/ directory." }, { "code": null, "e": 7777, "s": 7739, "text": "Here are the items we need to change:" }, { "code": null, "e": 8156, "s": 7777, "text": "Since we’re only trying to detect corgis, change num_classes to 1fine_tune_checkpoint tells the model which checkpoint file to use. Set this to checkpoints/model.ckptThe model also needs to know where the TFRecord files and label maps are for both training and validation sets. Since our train.record and val.record are saved in tf_record folder, our config should reflect that:" }, { "code": null, "e": 8222, "s": 8156, "text": "Since we’re only trying to detect corgis, change num_classes to 1" }, { "code": null, "e": 8324, "s": 8222, "text": "fine_tune_checkpoint tells the model which checkpoint file to use. Set this to checkpoints/model.ckpt" }, { "code": null, "e": 8537, "s": 8324, "text": "The model also needs to know where the TFRecord files and label maps are for both training and validation sets. Since our train.record and val.record are saved in tf_record folder, our config should reflect that:" }, { "code": null, "e": 8843, "s": 8537, "text": "train_input_reader: { tf_record_input_reader { input_path: \"tf_record/train.record\" } label_map_path: \"annotations/label_map.pbtxt\"}eval_input_reader: { tf_record_input_reader { input_path: \"tf_record/val.record\" } label_map_path: \"annotations/label_map.pbtxt\" shuffle: false num_readers: 1}" }, { "code": null, "e": 8903, "s": 8843, "text": "At this point, your models directory should look like this:" }, { "code": null, "e": 9362, "s": 8903, "text": "models β”œβ”€β”€ annotations | β”œβ”€β”€ label_map.pbtxt | β”œβ”€β”€ trainval.txt | └── xmls | β”œβ”€β”€ 1.xml | β”œβ”€β”€ 2.xml | β”œβ”€β”€ ... | β”œβ”€β”€ images | β”œβ”€β”€ 1.jpg | β”œβ”€β”€ 2.jpg | β”œβ”€β”€ ... | β”œβ”€β”€ checkpoints | β”œβ”€β”€ model.ckpt.data-00000-of-00001 | β”œβ”€β”€ model.ckpt.index | └── model.ckpt.meta | β”œβ”€β”€ tf_record | β”œβ”€β”€ train.record | └── val.record | β”œβ”€β”€ research | β”œβ”€β”€ ... ..." }, { "code": null, "e": 9449, "s": 9362, "text": "If you have successfully completed all previous steps, you’re ready to start training!" }, { "code": null, "e": 9473, "s": 9449, "text": "Follow the steps below:" }, { "code": null, "e": 9806, "s": 9473, "text": "# Change into the models directory$ cd tensorflow/models# Make directory for storing training progress$ mkdir train# Make directory for storing validation results$ mkdir eval# Begin training$ python research/object_detection/train.py \\ --logtostderr \\ --train_dir=train \\ --pipeline_config_path=ssd_mobilenet_v2_coco.config" }, { "code": null, "e": 9877, "s": 9806, "text": "Training time varies depending on the computing power of your machine." }, { "code": null, "e": 10045, "s": 9877, "text": "Evaluation can be run in parallel with training. The eval.py script checks the train directory for progress and evaluate the model based on the most recent checkpoint." }, { "code": null, "e": 10240, "s": 10045, "text": "# From the models directory$ python research/object_detection/eval.py \\ --logtostderr \\ --pipeline_config_path=ssd_mobilenet_v2_coco.config \\ --checkpoint_dir=train \\ --eval_dir=eval" }, { "code": null, "e": 10301, "s": 10240, "text": "You can visualize model training progress using Tensorboard:" }, { "code": null, "e": 10354, "s": 10301, "text": "# From the models directory$ tensorboard --logdir=./" }, { "code": null, "e": 10603, "s": 10354, "text": "Based on the graphs output by Tensorboard, you may decide when you want to stop training. Usually, you may stop the process when the loss function is tapering off and no longer decreasing by a significant amount. In my case, I stopped at step 3258." }, { "code": null, "e": 10766, "s": 10603, "text": "Once you finish training your model, you can export your model to be used for inference. If you’ve been following the folder structure, use the following command:" }, { "code": null, "e": 11090, "s": 10766, "text": "# From the models directory$ mkdir fine_tuned_model$ python research/object_detection/export_inference_graph.py \\ --input_type image_tensor \\ --pipeline_config_path ssd_mobilenet_v2_coco.config \\ --trained_checkpoint_prefix train/model.ckpt-<the_highest_checkpoint_number> \\ --output_directory fine_tuned_model" }, { "code": null, "e": 11316, "s": 11090, "text": "Now that you have a model, you can use it to detect corgis in pictures and videos! For the purpose of demonstration, we’re going to detect corgis in an image. Before you proceed, pick an image you want to test the model with." }, { "code": null, "e": 11553, "s": 11316, "text": "The models directory came with a notebook file (.ipynb) that we can use to get inference with a few tweaks. It is located at models/research/object_detection/object_detection_tutorial.ipynb. Follow the steps below to tweak the notebook:" }, { "code": null, "e": 12015, "s": 11553, "text": "MODEL_NAME = 'ssd_mobilenet_v2_coco_2018_03_29'PATH_TO_CKPT = 'path/to/your/frozen_inference_graph.pb'PATH_TO_LABELS = 'models/annotations/label_map.pbtxt'NUM_CLASSES = 1Comment out cell #5 completely (just below Download Model)Since we’re only testing on one image, comment out PATH_TO_TEST_IMAGES_DIR and TEST_IMAGE_PATHS in cell #9 (just below Detection)In cell #11 (the last cell), remove the for-loop, unindent its content, and add path to your test image:" }, { "code": null, "e": 12063, "s": 12015, "text": "MODEL_NAME = 'ssd_mobilenet_v2_coco_2018_03_29'" }, { "code": null, "e": 12119, "s": 12063, "text": "PATH_TO_CKPT = 'path/to/your/frozen_inference_graph.pb'" }, { "code": null, "e": 12173, "s": 12119, "text": "PATH_TO_LABELS = 'models/annotations/label_map.pbtxt'" }, { "code": null, "e": 12189, "s": 12173, "text": "NUM_CLASSES = 1" }, { "code": null, "e": 12248, "s": 12189, "text": "Comment out cell #5 completely (just below Download Model)" }, { "code": null, "e": 12378, "s": 12248, "text": "Since we’re only testing on one image, comment out PATH_TO_TEST_IMAGES_DIR and TEST_IMAGE_PATHS in cell #9 (just below Detection)" }, { "code": null, "e": 12483, "s": 12378, "text": "In cell #11 (the last cell), remove the for-loop, unindent its content, and add path to your test image:" }, { "code": null, "e": 12531, "s": 12483, "text": "imagepath = 'path/to/image_you_want_to_test.jpg" }, { "code": null, "e": 12662, "s": 12531, "text": "After following through the steps, run the notebook and you should see the corgi in your test image highlighted by a bounding box!" }, { "code": null, "e": 12705, "s": 12662, "text": "There you have your custom corgi detector!" }, { "code": null, "e": 12753, "s": 12705, "text": "Tensorflow Object Detection Model Documentation" } ]
HTML Text Formatting Elements - GeeksforGeeks
15 Sep, 2021 As we know, HTML provides many predefined elements that are used to change the formatting of text. The formatting can be used to set the text styles (like – bold, italic, or emphasized, etc.), highlighting the text, making text superscript and subscript, etc. Text Formatting Elements: <b> and <strong> Tags: Both tags are used to make a text bold. The text content of tag is shown as important information in the webpage. Example: HTML <!DOCTYPE html><html> <head> <title>Bold and strong</title></head> <body> <!--Normal text--> <p>Normal Text</p> <!--Text in Bold--> <p><b>Bold Text</b></p> <!--Text in Strong--> <p><strong> Strong Text</strong></p></body> </html> Output: HTML <i> and <em> Tags: Both tags are used to make the text italic and emphasized. Both the element have an opening and closing tags. Example: HTML <!DOCTYPE html><html> <head> <title>Italic and emphasized</title></head> <body> <!--Normal text--> <p>Normal Text</p> <!--Text in Italics--> <p><i>The Text inside italic Tag</i></p> <!--Text in Emphasize--> <p><em>Emphasized Text</em></p></body> </html> Output: HTML <small> and <big> Tags: The <small> tag is used to set small font-size where as <big> tag is used to set big font-size. Example: HTML <!DOCTYPE html><html> <head> <title>Small and Big</title></head> <body> <!--Text in Normal--> <p>Normal text</p> <small>The text inside small Tag</small> <p> <big>The text inside big Tag</big> </p></body> </html> Output: HTML <sup> and <sub> Tags: The <sup> tag is used to superscript a text where as <sub> tag is used to subscript a text. Example: HTML <!DOCTYPE html><html> <head> <title>Superscript and Subscript</title></head> <body> <!--Text in Normal--> <p>Normal Text <!--Text in Superscript--> <p> <sup>superscript </sup> Text </p> <!--Text in Subscript--> <p> <sub>subscript</sub>Text </p></body> </html> Output: HTML <ins> and <del> Tag: The <ins> tag is used to underline a text marking the part as inserted or added. It also has an opening and a closing tag. This tag is mainly used in a text in place of deleted text whereas <del> tag is used to delete the text it adds a strike line on the text. Example: HTML <!DOCTYPE html><html> <head> <title>Inserting and deleting</title></head> <body> <!--Deleting andText in Insert--> <b> <p>The TajMahal is located in <del>Bombay</del> <ins>Agra</ins> </p> </b></body> </html> Output: HTML <mark> Tag: The <mark> tag is used to highlighting a text. It has an opening and closing tag. Example: HTML <!DOCTYPE html><html> <head> <title>Highlight</title></head> <body> <!--Text in Normal--> <p>Normal Text</p> <!--Text in Highlight--> <p> <mark>Highlighted Text</mark> </p></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery How to auto-resize an image to fit a div container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24814, "s": 24786, "text": "\n15 Sep, 2021" }, { "code": null, "e": 25074, "s": 24814, "text": "As we know, HTML provides many predefined elements that are used to change the formatting of text. The formatting can be used to set the text styles (like – bold, italic, or emphasized, etc.), highlighting the text, making text superscript and subscript, etc." }, { "code": null, "e": 25100, "s": 25074, "text": "Text Formatting Elements:" }, { "code": null, "e": 25237, "s": 25100, "text": "<b> and <strong> Tags: Both tags are used to make a text bold. The text content of tag is shown as important information in the webpage." }, { "code": null, "e": 25247, "s": 25237, "text": "Example: " }, { "code": null, "e": 25252, "s": 25247, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bold and strong</title></head> <body> <!--Normal text--> <p>Normal Text</p> <!--Text in Bold--> <p><b>Bold Text</b></p> <!--Text in Strong--> <p><strong> Strong Text</strong></p></body> </html>", "e": 25510, "s": 25252, "text": null }, { "code": null, "e": 25518, "s": 25510, "text": "Output:" }, { "code": null, "e": 25652, "s": 25518, "text": "HTML <i> and <em> Tags: Both tags are used to make the text italic and emphasized. Both the element have an opening and closing tags." }, { "code": null, "e": 25661, "s": 25652, "text": "Example:" }, { "code": null, "e": 25666, "s": 25661, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Italic and emphasized</title></head> <body> <!--Normal text--> <p>Normal Text</p> <!--Text in Italics--> <p><i>The Text inside italic Tag</i></p> <!--Text in Emphasize--> <p><em>Emphasized Text</em></p></body> </html>", "e": 25948, "s": 25666, "text": null }, { "code": null, "e": 25957, "s": 25948, "text": "Output: " }, { "code": null, "e": 26082, "s": 25957, "text": "HTML <small> and <big> Tags: The <small> tag is used to set small font-size where as <big> tag is used to set big font-size." }, { "code": null, "e": 26094, "s": 26084, "text": "Example: " }, { "code": null, "e": 26099, "s": 26094, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Small and Big</title></head> <body> <!--Text in Normal--> <p>Normal text</p> <small>The text inside small Tag</small> <p> <big>The text inside big Tag</big> </p></body> </html>", "e": 26344, "s": 26099, "text": null }, { "code": null, "e": 26353, "s": 26344, "text": "Output: " }, { "code": null, "e": 26472, "s": 26353, "text": "HTML <sup> and <sub> Tags: The <sup> tag is used to superscript a text where as <sub> tag is used to subscript a text." }, { "code": null, "e": 26482, "s": 26472, "text": "Example: " }, { "code": null, "e": 26487, "s": 26482, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Superscript and Subscript</title></head> <body> <!--Text in Normal--> <p>Normal Text <!--Text in Superscript--> <p> <sup>superscript </sup> Text </p> <!--Text in Subscript--> <p> <sub>subscript</sub>Text </p></body> </html>", "e": 26801, "s": 26487, "text": null }, { "code": null, "e": 26809, "s": 26801, "text": "Output:" }, { "code": null, "e": 27097, "s": 26809, "text": "HTML <ins> and <del> Tag: The <ins> tag is used to underline a text marking the part as inserted or added. It also has an opening and a closing tag. This tag is mainly used in a text in place of deleted text whereas <del> tag is used to delete the text it adds a strike line on the text." }, { "code": null, "e": 27106, "s": 27097, "text": "Example:" }, { "code": null, "e": 27111, "s": 27106, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Inserting and deleting</title></head> <body> <!--Deleting andText in Insert--> <b> <p>The TajMahal is located in <del>Bombay</del> <ins>Agra</ins> </p> </b></body> </html>", "e": 27371, "s": 27111, "text": null }, { "code": null, "e": 27379, "s": 27371, "text": "Output:" }, { "code": null, "e": 27478, "s": 27379, "text": "HTML <mark> Tag: The <mark> tag is used to highlighting a text. It has an opening and closing tag." }, { "code": null, "e": 27488, "s": 27478, "text": "Example: " }, { "code": null, "e": 27493, "s": 27488, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Highlight</title></head> <body> <!--Text in Normal--> <p>Normal Text</p> <!--Text in Highlight--> <p> <mark>Highlighted Text</mark> </p></body> </html>", "e": 27713, "s": 27493, "text": null }, { "code": null, "e": 27721, "s": 27713, "text": "Output:" }, { "code": null, "e": 27858, "s": 27721, "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": 27873, "s": 27858, "text": "HTML-Questions" }, { "code": null, "e": 27883, "s": 27873, "text": "HTML-Tags" }, { "code": null, "e": 27890, "s": 27883, "text": "Picked" }, { "code": null, "e": 27895, "s": 27890, "text": "HTML" }, { "code": null, "e": 27912, "s": 27895, "text": "Web Technologies" }, { "code": null, "e": 27917, "s": 27912, "text": "HTML" }, { "code": null, "e": 28015, "s": 27917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28024, "s": 28015, "text": "Comments" }, { "code": null, "e": 28037, "s": 28024, "text": "Old Comments" }, { "code": null, "e": 28061, "s": 28037, "text": "REST API (Introduction)" }, { "code": null, "e": 28098, "s": 28061, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28118, "s": 28098, "text": "Angular File Upload" }, { "code": null, "e": 28147, "s": 28118, "text": "Form validation using jQuery" }, { "code": null, "e": 28209, "s": 28147, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 28251, "s": 28209, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28284, "s": 28251, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28327, "s": 28284, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28372, "s": 28327, "text": "Convert a string to an integer in JavaScript" } ]
Static class in C#
The C# static class cannot be instantiated and can only have only static members. The static class in C# is sealed and cannot contain instance constructors. The following is an example with static class and static members βˆ’ Live Demo using System; public static class Demo { public static float PI = 3.14f; public static int calc(int n){return n*n;} } class Program { public static void Main(string[] args) { Console.WriteLine("PI: "+Demo.PI); Console.WriteLine("Square: " + Demo.calc(3)); } } PI: 3.14 Square: 9 Above, the static class is βˆ’ public static class Demo { public static float PI = 3.14f; public static int calc(int n){return n*n;} } Above we have the following static members βˆ’ public static float PI = 3.14f; public static int calc(int n){return n*n;}
[ { "code": null, "e": 1219, "s": 1062, "text": "The C# static class cannot be instantiated and can only have only static members. The static class in C# is sealed and cannot contain instance constructors." }, { "code": null, "e": 1286, "s": 1219, "text": "The following is an example with static class and static members βˆ’" }, { "code": null, "e": 1297, "s": 1286, "text": " Live Demo" }, { "code": null, "e": 1584, "s": 1297, "text": "using System;\n\npublic static class Demo {\n public static float PI = 3.14f;\n public static int calc(int n){return n*n;}\n}\n\nclass Program {\n\n public static void Main(string[] args) {\n Console.WriteLine(\"PI: \"+Demo.PI);\n Console.WriteLine(\"Square: \" + Demo.calc(3));\n }\n}" }, { "code": null, "e": 1603, "s": 1584, "text": "PI: 3.14\nSquare: 9" }, { "code": null, "e": 1632, "s": 1603, "text": "Above, the static class is βˆ’" }, { "code": null, "e": 1742, "s": 1632, "text": "public static class Demo {\n public static float PI = 3.14f;\n public static int calc(int n){return n*n;}\n}" }, { "code": null, "e": 1787, "s": 1742, "text": "Above we have the following static members βˆ’" }, { "code": null, "e": 1862, "s": 1787, "text": "public static float PI = 3.14f;\npublic static int calc(int n){return n*n;}" } ]
How can we use nested transactions in MySQL?
We can work with nested transactions in MySQL with the help of SAVEPOINT. Firstly, create a table. After that, begin the transaction. Now, insert records in the table created above. Use SAVEPOINT statement to set a named transaction savepoint with a name of identifier. Here are all the steps shown in the form of query βˆ’ Create table mysql> create table NestedTransactionDemo -> ( -> Name varchar(200) -> ); Query OK, 0 rows affected (0.63 sec) Start the transaction βˆ’ mysql> START TRANSACTION; Query OK, 0 rows affected (0.00 sec) Now, insert a record in the table mysql> insert into NestedTransactionDemo values('John'); Query OK, 1 row affected (0.04 sec) Display the record added above βˆ’ mysql> select *from NestedTransactionDemo; +------+ | Name | +------+ | John | +------+ 1 row in set (0.00 sec) Let us begin with working on transactions to create nested transactions βˆ’ mysql> savepoint transaction2; Query OK, 0 rows affected (0.00 sec) mysql> insert into NestedTransactionDemo values('David'); Query OK, 1 row affected (0.00 sec) mysql> select *from NestedTransactionDemo; +-------+ | Name | +-------+ | John | | David | +-------+ 2 rows in set (0.00 sec) mysql> rollback to transaction2; Query OK, 0 rows affected (0.00 sec) mysql> select *from NestedTransactionDemo; +------+ | Name | +------+ | John | +------+ 1 row in set (0.00 sec) mysql> rollback to transaction2; Query OK, 0 rows affected (0.00 sec)
[ { "code": null, "e": 1136, "s": 1062, "text": "We can work with nested transactions in MySQL with the help of SAVEPOINT." }, { "code": null, "e": 1196, "s": 1136, "text": "Firstly, create a table. After that, begin the transaction." }, { "code": null, "e": 1332, "s": 1196, "text": "Now, insert records in the table created above. Use SAVEPOINT statement to set a named transaction savepoint with a name of identifier." }, { "code": null, "e": 1384, "s": 1332, "text": "Here are all the steps shown in the form of query βˆ’" }, { "code": null, "e": 1397, "s": 1384, "text": "Create table" }, { "code": null, "e": 1517, "s": 1397, "text": "mysql> create table NestedTransactionDemo\n -> (\n -> Name varchar(200)\n -> );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1541, "s": 1517, "text": "Start the transaction βˆ’" }, { "code": null, "e": 1604, "s": 1541, "text": "mysql> START TRANSACTION;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1638, "s": 1604, "text": "Now, insert a record in the table" }, { "code": null, "e": 1731, "s": 1638, "text": "mysql> insert into NestedTransactionDemo values('John');\nQuery OK, 1 row affected (0.04 sec)" }, { "code": null, "e": 1764, "s": 1731, "text": "Display the record added above βˆ’" }, { "code": null, "e": 1876, "s": 1764, "text": "mysql> select *from NestedTransactionDemo;\n+------+\n| Name |\n+------+\n| John |\n+------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1950, "s": 1876, "text": "Let us begin with working on transactions to create nested transactions βˆ’" }, { "code": null, "e": 2495, "s": 1950, "text": "mysql> savepoint transaction2;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> insert into NestedTransactionDemo values('David');\nQuery OK, 1 row affected (0.00 sec)\nmysql> select *from NestedTransactionDemo;\n+-------+\n| Name |\n+-------+\n| John |\n| David |\n+-------+\n2 rows in set (0.00 sec)\n\nmysql> rollback to transaction2;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> select *from NestedTransactionDemo;\n+------+\n| Name |\n+------+\n| John |\n+------+\n1 row in set (0.00 sec)\n\nmysql> rollback to transaction2;\nQuery OK, 0 rows affected (0.00 sec)" } ]
Machine Learning and Signal Processing | by Prasanna Sethuraman | Towards Data Science
Signal processing has given us a bag of tools that have been refined and put to very good use in the last fifty years. There is autocorrelation, convolution, Fourier and wavelet transforms, adaptive filtering via Least Mean Squares (LMS) or Recursive Least Squares (RLS), linear estimators, compressed sensing and gradient descent, to mention a few. Different tools are used to solve different problems, and sometimes, we use a combination of these tools to build a system to process signals. Machine Learning, or the deep neural networks, is much simpler to get used to because the underlying mathematics is fairly straightforward regardless of what network architecture we use. The complexity and the mystery of neural networks lie in the amount of data they process to get the fascinating results we currently have. This article is an effort to compare the performance of a neural network for a few key signal processing algorithms. Let us look at time series prediction as the first example. We will implement a three layer sequential deep neural network to predict the next sample of a signal. We will also do it the traditional way by using a tap delay filter and adapting the weights based on the mean square error β€” this is the LMS filtering, an iterative approach to the optimal Weiner filter for estimating signal from noisy measurement. We will then compare the prediction error between the two methods. So, let us get started with writing the code! Let us first import all the usual python libraries we need. Since we are going to be using the TensorFlow and Keras framework, we will import them too. Let us start building our 3 layer Neural network now. The input layer takes 64 samples and produces 32 samples. The hidden layer maps these 32 outputs from the first layer to 8 samples. The final layer maps these 8 samples in to 1 predicted output. Remember that the input size is provided with the input_shape parameter in the first layer. We will use the Adam optimizer without bothering about what it is. That is the benefit of TensorFlow, we don’t need to know every detail about all the processing required for neural network to build one using this amazing framework. If we find out that the Adam optimizer doesn’t work as well, we will simply try another optimizer β€” RMSprop for example. Let us now create a time series, a simple superposition of sine waves. We will then add noise to it to mimic a real world signal. Now that we have the data, let us think about how to feed this data to the neural network for training. We know the network takes 64 samples at the input and produces one output sample. Since we want to train the network to predict the next sample, we want to use the 65th sample as the output label. The first input set is therefore from sample 0 to sample 63 (the first 64 samples) and the first label is sample 64 (the 65th sample). The second input set can either be a separate set of 64 samples (non-overlapping window), or we can choose to have a sliding window and take 64 samples from sample 1 to sample 64. Let us follow the sliding window approach, just to generate a lot of training data from the time series we have. Also note that we are using the noisy samples as the input while using the noiseless data as the label. We want the neural network to predict the actual signal even in presence of noise. Let us look at the sizes of the time series data and the training data. See that we generated 5000 samples for our time series data, but we created 3935 x 64 = 251840 samples of input data to our neural network. The shape of train_data is the number of input sets x input length. Here, we have 3935 batches of input, each input being 64 samples long. print(y.shape, train_data.shape, train_labels.shape)(5000,) (3935, 64) (3935,) We are now ready to train the neural network. Let us instantiate the model first. The model summary provides information on how many layers, what is the output shape, and the number of parameters we need to train for this neural network. For the first layer, we have 64 inputs and 32 outputs. A dense layer implemets the equation y = f(Wx + b), where f is the activation function, W is the weight matrix and b is the bias. We can immediately see that W is a 64 x 32 matrix, and b is a 32 x 1 vector. This gives us 32 x 64 + 32 = 2080 parameters to train for the first layer. The reader can do similar computations to verify the parameters for second and third layer, as an exercise in understanding. After all, you wouldn’t be reading this article unless you are a beginner to Machine Learning and eager to get started :) model = dnn_keras_tspred_model()Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param # =================================================================dense (Dense) (None, 32) 2080 _________________________________________________________________dense_1 (Dense) (None, 8) 264 _________________________________________________________________dense_2 (Dense) (None, 1) 9 =================================================================Total params: 2,353Trainable params: 2,353Non-trainable params: 0_________________________________________________________________ Alright, onward to training then. Since we are using the Keras framework, training is as simple as calling the fit() method. With TensorFlow, we need to do a little more work, but that is for another article. Let us use 100 epochs, which just means that we will use the same training data again and again to train the neural network and will do so 100 times. In each epoch, the network uses the number of batches of input and label sets to train the parameters. Let us use the datetime to profile how long this training takes, and the history value that is returned as a Python Dictionary to get the validation loss after each epoch. DNN training done. Time elapsed: 10.177171 s Now that the network is trained, and we see that the validation loss has decreased over epochs to the point that it has flattened out (indicating further training doesn’t yield any significant improvements), let us use this network to see how well it performs against test data. Let us create the test data set exactly the same way as we created the training data sets, but use only that part of the time series that we have not used for training before. We want to surprise the neural network with data it has not seen before to know how well it can perform. We will now call the predict() method in Keras framework to get the outputs of the neural network for the test data set. This step is different if we use the TensorFlow framework, but we will cover that in another article. As we see, the prediction from neural network is very close to the actual noise free data! We will use a L=64 tap filter to predict the next sample. We don’t need that large a filter, but let us keep the number of inputs per output sample same as what we used for neural network. The filter coefficients (or weights) are obtained by computing the error between predicted and measured sample, and adjusting the weights based on the correlation between mean square error and the input measurements. As you see in the code, yrlms[k] is the filter output when the inputs are ypn[k-L:k], the error is computed as the difference between the noisy measured value ypn[k] and the filter output yrlms[k]. The correlation between measurement and error is given by the product of ypn[k-L:k] and e, and mu is the LMS step size (or learning rate). As we see, the LMS prediction is equally good, despite having much lower complexity. (64,) (1064,) Before we close this section, let us compare the error between LMS prediction and the neural network prediction. To be fair, I ignored the initial portion of the LMS to give it time to converge when measuring the mean square error and SNR. Despite that, we see that the neural network performance is 5 dB better than the LMS performance! Neural network SNR: 19.986311477279084LMS Prediction SNR: 14.93359076022336 Alright, a neural network beat LMS by 5 dB in signal prediction, but let us see if a neural network can be trained to do the Fourier Transform. We will compare it to the FFT (Fast Fourier Transform) from SciPy FFTPack. The FFT algorithm is at the heart of signal processing, can the neural network be trained to mimic that too? Let us find out... We will use the same signal we created before, the superposition of sine waves, to evaluate FFT as well. Let us look at the FFT ouput first. Let us create a neural network model to mimic the FFT now. In contrast to the model we created before where we have 64 inputs but only one output, this model needs to generate 64 outputs for every 64 sample input set. And since FFT inputs and outputs are complex, we need twice the number of samples at the input, arranged as real followed by imaginary. Since the outputs are also complex, we again 2 x NFFT samples. To train this neural network model, let us use random data generated using numpy.random.normal and set the labels based on the FFT routine from the SciPy FFTPack that we are comparing with. The rest of the code is fairly similar to the previous neural network training. Here, I am running 10,000 batches at a time, and I have an outer for loop to do multiple sets of 10,000 batches if the network needs more training. Note that this needs the model to be created outside the for loop, so that the weights are not reinitialized. See from model summary that there are almost 50,000 parameters for just a 64 point FFT. We can reduce this a bit since we are only evaluating real inputs while keeping the imaginary parts as zero, but the goal here is to quickly compare if the neural network can be trained to do the Fourier Transform. Model: "sequential_1"_________________________________________________________________Layer (type) Output Shape Param # =================================================================dense_3 (Dense) (None, 128) 16512 _________________________________________________________________dense_4 (Dense) (None, 128) 16512 _________________________________________________________________dense_5 (Dense) (None, 128) 16512 =================================================================Total params: 49,536Trainable params: 49,536Non-trainable params: 0_________________________________________________________________DNN training done. Time elapsed: 30.64511 s Training is done. Let us now test the network using the same input samples we created for LMS. We compare the neural network output to the FFT ouput and they are identical! How amazing is that! Let us do one last evaluation before we conclude this article. We will compare the neural network output with the FFT output for some random input data, and see how the mean square error and SNR looks like. Running the code below, we get a decent 23.64 dB SNR. While we do see some samples every now and then where the error is high, for most part, the error is very small. Given that we trained the neural network for only 10,000 batches, this is a pretty good result! Neural Network SNR compared to SciPy FFT: 23.64254974707859 Being stuck inside during Covid-19, it was a fun weekend project to compare machine learning performance to some key signal processing algorithms. We see that machine learning can do what signal processing can, but has inherently higher complexity, with the benefit of being generalizable to different problems. The signal processing algorithms are optimal for the job in terms of complexity, but are specific to the particular problems they solve. We can’t use FFT in place of LMS or vice versa, while we can use the same neural network processor, and just load a different set of weights to solve a different problem. That is the versatility of neural networks. And with that note, I’ll conclude this article. I hope you had as much fun reading this as I had putting this together. Please leave your feedback too if you found it helpful and learnt a thing or two!
[ { "code": null, "e": 664, "s": 171, "text": "Signal processing has given us a bag of tools that have been refined and put to very good use in the last fifty years. There is autocorrelation, convolution, Fourier and wavelet transforms, adaptive filtering via Least Mean Squares (LMS) or Recursive Least Squares (RLS), linear estimators, compressed sensing and gradient descent, to mention a few. Different tools are used to solve different problems, and sometimes, we use a combination of these tools to build a system to process signals." }, { "code": null, "e": 990, "s": 664, "text": "Machine Learning, or the deep neural networks, is much simpler to get used to because the underlying mathematics is fairly straightforward regardless of what network architecture we use. The complexity and the mystery of neural networks lie in the amount of data they process to get the fascinating results we currently have." }, { "code": null, "e": 1632, "s": 990, "text": "This article is an effort to compare the performance of a neural network for a few key signal processing algorithms. Let us look at time series prediction as the first example. We will implement a three layer sequential deep neural network to predict the next sample of a signal. We will also do it the traditional way by using a tap delay filter and adapting the weights based on the mean square error β€” this is the LMS filtering, an iterative approach to the optimal Weiner filter for estimating signal from noisy measurement. We will then compare the prediction error between the two methods. So, let us get started with writing the code!" }, { "code": null, "e": 1784, "s": 1632, "text": "Let us first import all the usual python libraries we need. Since we are going to be using the TensorFlow and Keras framework, we will import them too." }, { "code": null, "e": 2125, "s": 1784, "text": "Let us start building our 3 layer Neural network now. The input layer takes 64 samples and produces 32 samples. The hidden layer maps these 32 outputs from the first layer to 8 samples. The final layer maps these 8 samples in to 1 predicted output. Remember that the input size is provided with the input_shape parameter in the first layer." }, { "code": null, "e": 2479, "s": 2125, "text": "We will use the Adam optimizer without bothering about what it is. That is the benefit of TensorFlow, we don’t need to know every detail about all the processing required for neural network to build one using this amazing framework. If we find out that the Adam optimizer doesn’t work as well, we will simply try another optimizer β€” RMSprop for example." }, { "code": null, "e": 2609, "s": 2479, "text": "Let us now create a time series, a simple superposition of sine waves. We will then add noise to it to mimic a real world signal." }, { "code": null, "e": 2910, "s": 2609, "text": "Now that we have the data, let us think about how to feed this data to the neural network for training. We know the network takes 64 samples at the input and produces one output sample. Since we want to train the network to predict the next sample, we want to use the 65th sample as the output label." }, { "code": null, "e": 3338, "s": 2910, "text": "The first input set is therefore from sample 0 to sample 63 (the first 64 samples) and the first label is sample 64 (the 65th sample). The second input set can either be a separate set of 64 samples (non-overlapping window), or we can choose to have a sliding window and take 64 samples from sample 1 to sample 64. Let us follow the sliding window approach, just to generate a lot of training data from the time series we have." }, { "code": null, "e": 3525, "s": 3338, "text": "Also note that we are using the noisy samples as the input while using the noiseless data as the label. We want the neural network to predict the actual signal even in presence of noise." }, { "code": null, "e": 3737, "s": 3525, "text": "Let us look at the sizes of the time series data and the training data. See that we generated 5000 samples for our time series data, but we created 3935 x 64 = 251840 samples of input data to our neural network." }, { "code": null, "e": 3876, "s": 3737, "text": "The shape of train_data is the number of input sets x input length. Here, we have 3935 batches of input, each input being 64 samples long." }, { "code": null, "e": 3955, "s": 3876, "text": "print(y.shape, train_data.shape, train_labels.shape)(5000,) (3935, 64) (3935,)" }, { "code": null, "e": 4193, "s": 3955, "text": "We are now ready to train the neural network. Let us instantiate the model first. The model summary provides information on how many layers, what is the output shape, and the number of parameters we need to train for this neural network." }, { "code": null, "e": 4777, "s": 4193, "text": "For the first layer, we have 64 inputs and 32 outputs. A dense layer implemets the equation y = f(Wx + b), where f is the activation function, W is the weight matrix and b is the bias. We can immediately see that W is a 64 x 32 matrix, and b is a 32 x 1 vector. This gives us 32 x 64 + 32 = 2080 parameters to train for the first layer. The reader can do similar computations to verify the parameters for second and third layer, as an exercise in understanding. After all, you wouldn’t be reading this article unless you are a beginner to Machine Learning and eager to get started :)" }, { "code": null, "e": 5544, "s": 4777, "text": "model = dnn_keras_tspred_model()Model: \"sequential\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================dense (Dense) (None, 32) 2080 _________________________________________________________________dense_1 (Dense) (None, 8) 264 _________________________________________________________________dense_2 (Dense) (None, 1) 9 =================================================================Total params: 2,353Trainable params: 2,353Non-trainable params: 0_________________________________________________________________" }, { "code": null, "e": 5753, "s": 5544, "text": "Alright, onward to training then. Since we are using the Keras framework, training is as simple as calling the fit() method. With TensorFlow, we need to do a little more work, but that is for another article." }, { "code": null, "e": 6006, "s": 5753, "text": "Let us use 100 epochs, which just means that we will use the same training data again and again to train the neural network and will do so 100 times. In each epoch, the network uses the number of batches of input and label sets to train the parameters." }, { "code": null, "e": 6178, "s": 6006, "text": "Let us use the datetime to profile how long this training takes, and the history value that is returned as a Python Dictionary to get the validation loss after each epoch." }, { "code": null, "e": 6224, "s": 6178, "text": "DNN training done. Time elapsed: 10.177171 s" }, { "code": null, "e": 6503, "s": 6224, "text": "Now that the network is trained, and we see that the validation loss has decreased over epochs to the point that it has flattened out (indicating further training doesn’t yield any significant improvements), let us use this network to see how well it performs against test data." }, { "code": null, "e": 6784, "s": 6503, "text": "Let us create the test data set exactly the same way as we created the training data sets, but use only that part of the time series that we have not used for training before. We want to surprise the neural network with data it has not seen before to know how well it can perform." }, { "code": null, "e": 7007, "s": 6784, "text": "We will now call the predict() method in Keras framework to get the outputs of the neural network for the test data set. This step is different if we use the TensorFlow framework, but we will cover that in another article." }, { "code": null, "e": 7098, "s": 7007, "text": "As we see, the prediction from neural network is very close to the actual noise free data!" }, { "code": null, "e": 7287, "s": 7098, "text": "We will use a L=64 tap filter to predict the next sample. We don’t need that large a filter, but let us keep the number of inputs per output sample same as what we used for neural network." }, { "code": null, "e": 7504, "s": 7287, "text": "The filter coefficients (or weights) are obtained by computing the error between predicted and measured sample, and adjusting the weights based on the correlation between mean square error and the input measurements." }, { "code": null, "e": 7841, "s": 7504, "text": "As you see in the code, yrlms[k] is the filter output when the inputs are ypn[k-L:k], the error is computed as the difference between the noisy measured value ypn[k] and the filter output yrlms[k]. The correlation between measurement and error is given by the product of ypn[k-L:k] and e, and mu is the LMS step size (or learning rate)." }, { "code": null, "e": 7926, "s": 7841, "text": "As we see, the LMS prediction is equally good, despite having much lower complexity." }, { "code": null, "e": 7940, "s": 7926, "text": "(64,) (1064,)" }, { "code": null, "e": 8278, "s": 7940, "text": "Before we close this section, let us compare the error between LMS prediction and the neural network prediction. To be fair, I ignored the initial portion of the LMS to give it time to converge when measuring the mean square error and SNR. Despite that, we see that the neural network performance is 5 dB better than the LMS performance!" }, { "code": null, "e": 8354, "s": 8278, "text": "Neural network SNR: 19.986311477279084LMS Prediction SNR: 14.93359076022336" }, { "code": null, "e": 8701, "s": 8354, "text": "Alright, a neural network beat LMS by 5 dB in signal prediction, but let us see if a neural network can be trained to do the Fourier Transform. We will compare it to the FFT (Fast Fourier Transform) from SciPy FFTPack. The FFT algorithm is at the heart of signal processing, can the neural network be trained to mimic that too? Let us find out..." }, { "code": null, "e": 8842, "s": 8701, "text": "We will use the same signal we created before, the superposition of sine waves, to evaluate FFT as well. Let us look at the FFT ouput first." }, { "code": null, "e": 9060, "s": 8842, "text": "Let us create a neural network model to mimic the FFT now. In contrast to the model we created before where we have 64 inputs but only one output, this model needs to generate 64 outputs for every 64 sample input set." }, { "code": null, "e": 9259, "s": 9060, "text": "And since FFT inputs and outputs are complex, we need twice the number of samples at the input, arranged as real followed by imaginary. Since the outputs are also complex, we again 2 x NFFT samples." }, { "code": null, "e": 9449, "s": 9259, "text": "To train this neural network model, let us use random data generated using numpy.random.normal and set the labels based on the FFT routine from the SciPy FFTPack that we are comparing with." }, { "code": null, "e": 9787, "s": 9449, "text": "The rest of the code is fairly similar to the previous neural network training. Here, I am running 10,000 batches at a time, and I have an outer for loop to do multiple sets of 10,000 batches if the network needs more training. Note that this needs the model to be created outside the for loop, so that the weights are not reinitialized." }, { "code": null, "e": 10090, "s": 9787, "text": "See from model summary that there are almost 50,000 parameters for just a 64 point FFT. We can reduce this a bit since we are only evaluating real inputs while keeping the imaginary parts as zero, but the goal here is to quickly compare if the neural network can be trained to do the Fourier Transform." }, { "code": null, "e": 10873, "s": 10090, "text": "Model: \"sequential_1\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================dense_3 (Dense) (None, 128) 16512 _________________________________________________________________dense_4 (Dense) (None, 128) 16512 _________________________________________________________________dense_5 (Dense) (None, 128) 16512 =================================================================Total params: 49,536Trainable params: 49,536Non-trainable params: 0_________________________________________________________________DNN training done. Time elapsed: 30.64511 s" }, { "code": null, "e": 11067, "s": 10873, "text": "Training is done. Let us now test the network using the same input samples we created for LMS. We compare the neural network output to the FFT ouput and they are identical! How amazing is that!" }, { "code": null, "e": 11274, "s": 11067, "text": "Let us do one last evaluation before we conclude this article. We will compare the neural network output with the FFT output for some random input data, and see how the mean square error and SNR looks like." }, { "code": null, "e": 11537, "s": 11274, "text": "Running the code below, we get a decent 23.64 dB SNR. While we do see some samples every now and then where the error is high, for most part, the error is very small. Given that we trained the neural network for only 10,000 batches, this is a pretty good result!" }, { "code": null, "e": 11598, "s": 11537, "text": "Neural Network SNR compared to SciPy FFT: 23.64254974707859" }, { "code": null, "e": 12262, "s": 11598, "text": "Being stuck inside during Covid-19, it was a fun weekend project to compare machine learning performance to some key signal processing algorithms. We see that machine learning can do what signal processing can, but has inherently higher complexity, with the benefit of being generalizable to different problems. The signal processing algorithms are optimal for the job in terms of complexity, but are specific to the particular problems they solve. We can’t use FFT in place of LMS or vice versa, while we can use the same neural network processor, and just load a different set of weights to solve a different problem. That is the versatility of neural networks." } ]
reflect.MethodByName() Function in Golang with Examples - GeeksforGeeks
03 May, 2020 Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.MethodByName() Function in Golang is used to get function value corresponding to the method of v with the given name. To access this function, one needs to imports the reflect package in the program. Syntax: func (v Value) MethodByName(name string) Value Parameters: This function does not accept any parameter. Return Value: This function returns a function value corresponding to the method of v with the given name. Below examples illustrate the use of the above method in Golang: Example 1: // Golang program to illustrate// reflect.MethodByName() Function package main import ( "fmt" "reflect") // Main functiontype T struct {} func (t *T) GFG() { fmt.Println("GeeksForGeeks")} func main() { var t T reflect.ValueOf(&t).MethodByName("GFG").Call([]reflect.Value{})} Output: GeeksForGeeks Example 2: // Golang program to illustrate// reflect.MethodByName() Function package main import ( "fmt" "reflect") // Main function type YourT2 struct {}func (y YourT2) MethodFoo(i int, oo string) { fmt.Println(i) fmt.Println(oo)} func Invoke(any interface{}, name string, args... interface{}) { inputs := make([]reflect.Value, len(args)) for i, _ := range args { inputs[i] = reflect.ValueOf(args[i]) } reflect.ValueOf(any).MethodByName(name).Call(inputs)} func main() { Invoke(YourT2{}, "MethodFoo", 10, "Geekforgeeks")} Output: 10 Geekforgeeks Golang-reflect 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 How to Split a String in Golang? fmt.Sprintf() Function in Golang With Examples Slices in Golang Golang Maps Interfaces in Golang Inheritance in GoLang Different Ways to Find the Type of Variable in Golang How to Trim a String in Golang?
[ { "code": null, "e": 25913, "s": 25885, "text": "\n03 May, 2020" }, { "code": null, "e": 26300, "s": 25913, "text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.MethodByName() Function in Golang is used to get function value corresponding to the method of v with the given name. To access this function, one needs to imports the reflect package in the program." }, { "code": null, "e": 26308, "s": 26300, "text": "Syntax:" }, { "code": null, "e": 26356, "s": 26308, "text": "func (v Value) MethodByName(name string) Value\n" }, { "code": null, "e": 26413, "s": 26356, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 26520, "s": 26413, "text": "Return Value: This function returns a function value corresponding to the method of v with the given name." }, { "code": null, "e": 26585, "s": 26520, "text": "Below examples illustrate the use of the above method in Golang:" }, { "code": null, "e": 26596, "s": 26585, "text": "Example 1:" }, { "code": "// Golang program to illustrate// reflect.MethodByName() Function package main import ( \"fmt\" \"reflect\") // Main functiontype T struct {} func (t *T) GFG() { fmt.Println(\"GeeksForGeeks\")} func main() { var t T reflect.ValueOf(&t).MethodByName(\"GFG\").Call([]reflect.Value{})}", "e": 26898, "s": 26596, "text": null }, { "code": null, "e": 26906, "s": 26898, "text": "Output:" }, { "code": null, "e": 26921, "s": 26906, "text": "GeeksForGeeks\n" }, { "code": null, "e": 26932, "s": 26921, "text": "Example 2:" }, { "code": "// Golang program to illustrate// reflect.MethodByName() Function package main import ( \"fmt\" \"reflect\") // Main function type YourT2 struct {}func (y YourT2) MethodFoo(i int, oo string) { fmt.Println(i) fmt.Println(oo)} func Invoke(any interface{}, name string, args... interface{}) { inputs := make([]reflect.Value, len(args)) for i, _ := range args { inputs[i] = reflect.ValueOf(args[i]) } reflect.ValueOf(any).MethodByName(name).Call(inputs)} func main() { Invoke(YourT2{}, \"MethodFoo\", 10, \"Geekforgeeks\")}", "e": 27492, "s": 26932, "text": null }, { "code": null, "e": 27500, "s": 27492, "text": "Output:" }, { "code": null, "e": 27517, "s": 27500, "text": "10\nGeekforgeeks\n" }, { "code": null, "e": 27532, "s": 27517, "text": "Golang-reflect" }, { "code": null, "e": 27544, "s": 27532, "text": "Go Language" }, { "code": null, "e": 27642, "s": 27544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27693, "s": 27642, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 27706, "s": 27693, "text": "Arrays in Go" }, { "code": null, "e": 27739, "s": 27706, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27786, "s": 27739, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 27803, "s": 27786, "text": "Slices in Golang" }, { "code": null, "e": 27815, "s": 27803, "text": "Golang Maps" }, { "code": null, "e": 27836, "s": 27815, "text": "Interfaces in Golang" }, { "code": null, "e": 27858, "s": 27836, "text": "Inheritance in GoLang" }, { "code": null, "e": 27912, "s": 27858, "text": "Different Ways to Find the Type of Variable in Golang" } ]
set upper_bound() function in C++ STL - GeeksforGeeks
23 Jan, 2020 The set::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to next of last element (which can be identified using set end() function) in the set container. Syntax: set_name.upper_bound(key) Parameters: This function accepts a single mandatory parameter key which specifies the element whose upper bound is to be returned. Return Value: The function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator points to std::end() which points to the element next to the last element of the set. Example 1: Below program illustrate the above function: // CPP program to demonstrate the// set::upper_bound() function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(6); cout << "The set elements are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; // when 2 is present // points to next element after 2 auto it = s.upper_bound(2); cout << "\nThe upper bound of key 2 is "; cout << (*it) << endl; // when 3 is not present // points to next greater after 3 it = s.upper_bound(3); cout << "The upper bound of key 3 is "; cout << (*it) << endl; return 0;} The set elements are: 1 2 4 5 6 The upper bound of key 2 is 4 The upper bound of key 3 is 4 Example 2: Below is a better code that also checks if the given element is greater than or equal to the greatest. // CPP program to demonstrate the// set::upper_bound() function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(6); int key = 8; auto it = s.upper_bound(key); if (it == s.end()) cout << "The given key is greater " "than or equal to the largest element \n"; else cout << "The immediate greater element " << "is " << *it << endl; key = 3; it = s.upper_bound(key); if (it == s.end()) cout << "The given key is greater " "than or equal to the largest element \n"; else cout << "The immediate greater element " << "is " << *it << endl; return 0;} The given key is greater than or equal to the largest element The immediate greater element is 4 shashanka136 CPP-Functions cpp-set STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Virtual Function in C++ Bitwise Operators in C/C++ Constructors in C++ Operator Overloading in C++ Templates in C++ with Examples Socket Programming in C/C++ Object Oriented Programming in C++ Polymorphism in C++
[ { "code": null, "e": 25931, "s": 25903, "text": "\n23 Jan, 2020" }, { "code": null, "e": 26291, "s": 25931, "text": "The set::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to next of last element (which can be identified using set end() function) in the set container." }, { "code": null, "e": 26299, "s": 26291, "text": "Syntax:" }, { "code": null, "e": 26325, "s": 26299, "text": "set_name.upper_bound(key)" }, { "code": null, "e": 26457, "s": 26325, "text": "Parameters: This function accepts a single mandatory parameter key which specifies the element whose upper bound is to be returned." }, { "code": null, "e": 26754, "s": 26457, "text": "Return Value: The function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator points to std::end() which points to the element next to the last element of the set." }, { "code": null, "e": 26810, "s": 26754, "text": "Example 1: Below program illustrate the above function:" }, { "code": "// CPP program to demonstrate the// set::upper_bound() function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(6); cout << \"The set elements are: \"; for (auto it = s.begin(); it != s.end(); it++) cout << *it << \" \"; // when 2 is present // points to next element after 2 auto it = s.upper_bound(2); cout << \"\\nThe upper bound of key 2 is \"; cout << (*it) << endl; // when 3 is not present // points to next greater after 3 it = s.upper_bound(3); cout << \"The upper bound of key 3 is \"; cout << (*it) << endl; return 0;}", "e": 27546, "s": 26810, "text": null }, { "code": null, "e": 27640, "s": 27546, "text": "The set elements are: 1 2 4 5 6 \nThe upper bound of key 2 is 4\nThe upper bound of key 3 is 4\n" }, { "code": null, "e": 27754, "s": 27640, "text": "Example 2: Below is a better code that also checks if the given element is greater than or equal to the greatest." }, { "code": "// CPP program to demonstrate the// set::upper_bound() function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(6); int key = 8; auto it = s.upper_bound(key); if (it == s.end()) cout << \"The given key is greater \" \"than or equal to the largest element \\n\"; else cout << \"The immediate greater element \" << \"is \" << *it << endl; key = 3; it = s.upper_bound(key); if (it == s.end()) cout << \"The given key is greater \" \"than or equal to the largest element \\n\"; else cout << \"The immediate greater element \" << \"is \" << *it << endl; return 0;}", "e": 28572, "s": 27754, "text": null }, { "code": null, "e": 28671, "s": 28572, "text": "The given key is greater than or equal to the largest element \nThe immediate greater element is 4\n" }, { "code": null, "e": 28684, "s": 28671, "text": "shashanka136" }, { "code": null, "e": 28698, "s": 28684, "text": "CPP-Functions" }, { "code": null, "e": 28706, "s": 28698, "text": "cpp-set" }, { "code": null, "e": 28710, "s": 28706, "text": "STL" }, { "code": null, "e": 28714, "s": 28710, "text": "C++" }, { "code": null, "e": 28718, "s": 28714, "text": "STL" }, { "code": null, "e": 28722, "s": 28718, "text": "CPP" }, { "code": null, "e": 28820, "s": 28722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28839, "s": 28820, "text": "Inheritance in C++" }, { "code": null, "e": 28863, "s": 28839, "text": "C++ Classes and Objects" }, { "code": null, "e": 28887, "s": 28863, "text": "Virtual Function in C++" }, { "code": null, "e": 28914, "s": 28887, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28934, "s": 28914, "text": "Constructors in C++" }, { "code": null, "e": 28962, "s": 28934, "text": "Operator Overloading in C++" }, { "code": null, "e": 28993, "s": 28962, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29021, "s": 28993, "text": "Socket Programming in C/C++" }, { "code": null, "e": 29056, "s": 29021, "text": "Object Oriented Programming in C++" } ]
How to set and unset cookies using jQuery?
16 Jun, 2020 An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our on cookies in the browser according to our need. Cookies can be set in the browser with the help of JavaScript or the jQuery. Here we will be seeing how to set cookies in the browser with the help of jQuery and how to remove them later on. Here we are using CDN of jQuery cookies to insert a cookie in the browser . Note: Please keep your internet connection on while using this code as it uses CDN services for jQuery. Example 1: Setting cookies in the browser after that we will remove that cookie. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cookie | Geeksforgeeks</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin= "anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script> </head> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <button onclick="addCookie()"> Add Cookie </button> <button onclick="removeCookie()"> remove Cookie </button> <p></p> <script> let addCookie=()=>{ $.cookie("geeksforgeeks", "It is the data of the cookie"); $("p").text("cookie added"); } let removeCookie=()=>{ $.removeCookie("geeksforgeeks", "It is the data of the cookie"); $("p").text("cookie removed"); } </script> </center> </body></html> Output: You can clearly see there is a cookie named GeeksforGeeks with a value. We can also set the cookie Expiry date. Before adding Cookie: After adding Cookies: After removing Cookie: jQuery-Basics JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery jQuery | children() with Examples Scroll to the top of the page using JavaScript/jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to get the value in an input text box using jQuery ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2020" }, { "code": null, "e": 294, "s": 28, "text": "An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our on cookies in the browser according to our need." }, { "code": null, "e": 485, "s": 294, "text": "Cookies can be set in the browser with the help of JavaScript or the jQuery. Here we will be seeing how to set cookies in the browser with the help of jQuery and how to remove them later on." }, { "code": null, "e": 561, "s": 485, "text": "Here we are using CDN of jQuery cookies to insert a cookie in the browser ." }, { "code": null, "e": 665, "s": 561, "text": "Note: Please keep your internet connection on while using this code as it uses CDN services for jQuery." }, { "code": null, "e": 747, "s": 665, "text": "Example 1: Setting cookies in the browser after that we will remove that cookie." }, { "code": null, "e": 752, "s": 747, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Cookie | Geeksforgeeks</title> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin= \"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js\"></script> </head> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <button onclick=\"addCookie()\"> Add Cookie </button> <button onclick=\"removeCookie()\"> remove Cookie </button> <p></p> <script> let addCookie=()=>{ $.cookie(\"geeksforgeeks\", \"It is the data of the cookie\"); $(\"p\").text(\"cookie added\"); } let removeCookie=()=>{ $.removeCookie(\"geeksforgeeks\", \"It is the data of the cookie\"); $(\"p\").text(\"cookie removed\"); } </script> </center> </body></html>", "e": 1890, "s": 752, "text": null }, { "code": null, "e": 2010, "s": 1890, "text": "Output: You can clearly see there is a cookie named GeeksforGeeks with a value. We can also set the cookie Expiry date." }, { "code": null, "e": 2033, "s": 2010, "text": "Before adding Cookie: " }, { "code": null, "e": 2055, "s": 2033, "text": "After adding Cookies:" }, { "code": null, "e": 2078, "s": 2055, "text": "After removing Cookie:" }, { "code": null, "e": 2092, "s": 2078, "text": "jQuery-Basics" }, { "code": null, "e": 2099, "s": 2092, "text": "JQuery" }, { "code": null, "e": 2116, "s": 2099, "text": "Web Technologies" }, { "code": null, "e": 2143, "s": 2116, "text": "Web technologies Questions" }, { "code": null, "e": 2241, "s": 2143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2270, "s": 2241, "text": "Form validation using jQuery" }, { "code": null, "e": 2304, "s": 2270, "text": "jQuery | children() with Examples" }, { "code": null, "e": 2358, "s": 2304, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 2414, "s": 2358, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 2471, "s": 2414, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 2504, "s": 2471, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2566, "s": 2504, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2627, "s": 2566, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2677, "s": 2627, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Understanding RxJava Zip Operator With Example
25 Aug, 2021 According to the official RxJava documentation β€œZip combines the emissions of several Observables using a given function and emits single items based on the outcomes of this function for each combination”. The zip operator enables us to obtain results from several observables at the same time. Image 1. Understanding the Zip Structure. Assume we have the following two network observables: GfGCoursesData – A network observable that yields a list of courses offered at Geeks for Geeks. GfGDSA – A network observable that returns a list of Geeks for Geeks Data Structure Courses GfFCourses have noticed the following: Kotlin fun getGfGCoursesData(): Observable<List<User>> { return networkService.getGfGCoursesData()} GFGDSA is as follows: Kotlin fun getGFGDSA(): Observable<List<User>> { return networkService.getGFGDSA()} And here is our NetworkService: Kotlin class NetworkService { fun gfgCourses(): Observable<List<User>> { return Observable.create<List<User>> { shooterData -> if (!shooterData.isDisposed) { // fetch gfgData from network val gfgData = fetchUserListFromNetwork() shooterData.onNext(gfgData) shooterData.onComplete() } }.subscribeOn(Schedulers.io()) } fun gfgDSA(): Observable<List<User>> { return Observable.create<List<User>> { shooterData -> if (!shooterData.isDisposed) { // fetch gfgData from network val gfgData = fetchUserListFromNetwork() shooterData.onNext(gfgData) shooterData.onComplete() } }.subscribeOn(Schedulers.io()) } private fun fetchUserListFromNetwork(): List<User> { return listOf() } } As an example, consider the following observer: Kotlin private fun getTheObserver(): Observer<List<User>> { return object : Observer<List<User>> { override fun gfgSubscribed(d: Disposable) { println("gfgSubscribed") } override fun onNext(userList: List<User>) { println("onNext : $userList") } override fun onError(e: Throwable) { println("onError : ${e.message}") } override fun onComplete() { println("onComplete") } }} A utility tool for identifying courses that are in common. Kotlin private fun CommonCourses(GfGCourses: List<User>, gfgDSACourses: List<User>): List<User> { val CommonCourses = ArrayList<User>() for (gfgDSACourse in gfgDSACourses) { if (GfGCourses.contains(gfgDSACourse)) { CommonCourses.add(gfgDSACourse) } } return CommonCourses} Kotlin Observable.zip( gfgCourses(), gfgDSACourses(), BiFunction<List<User>, List<User>, List<User>> { cricketFans, gfgCourses-> // fetching results at once. return@BiFunction filterUserWhoLovesBoth(cricketFans, gfgDSA) }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(getObserver()) First, we make two network requests (simultaneously because we’re using Zip Operator), and then we select the courses of DSA which are part of the main courses. Both network calls are executed in parallel by zipping two observables with the RxJava Zip operator. When both observables have finished, we obtain the outcome of both. We obtain the outcomes of both observables at the same time in this manner. Run all jobs in parallel if Schedulers are appropriately assigned to each observable. When all of the jobs have been finished, return the results of all of them in a single callback. We may utilize the RxJava Zip Operator to solve the intriguing problem this way. Picked RxJava Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 323, "s": 28, "text": "According to the official RxJava documentation β€œZip combines the emissions of several Observables using a given function and emits single items based on the outcomes of this function for each combination”. The zip operator enables us to obtain results from several observables at the same time." }, { "code": null, "e": 365, "s": 323, "text": "Image 1. Understanding the Zip Structure." }, { "code": null, "e": 607, "s": 365, "text": "Assume we have the following two network observables: GfGCoursesData – A network observable that yields a list of courses offered at Geeks for Geeks. GfGDSA – A network observable that returns a list of Geeks for Geeks Data Structure Courses" }, { "code": null, "e": 646, "s": 607, "text": "GfFCourses have noticed the following:" }, { "code": null, "e": 653, "s": 646, "text": "Kotlin" }, { "code": "fun getGfGCoursesData(): Observable<List<User>> { return networkService.getGfGCoursesData()}", "e": 749, "s": 653, "text": null }, { "code": null, "e": 771, "s": 749, "text": "GFGDSA is as follows:" }, { "code": null, "e": 778, "s": 771, "text": "Kotlin" }, { "code": "fun getGFGDSA(): Observable<List<User>> { return networkService.getGFGDSA()}", "e": 858, "s": 778, "text": null }, { "code": null, "e": 890, "s": 858, "text": "And here is our NetworkService:" }, { "code": null, "e": 897, "s": 890, "text": "Kotlin" }, { "code": "class NetworkService { fun gfgCourses(): Observable<List<User>> { return Observable.create<List<User>> { shooterData -> if (!shooterData.isDisposed) { // fetch gfgData from network val gfgData = fetchUserListFromNetwork() shooterData.onNext(gfgData) shooterData.onComplete() } }.subscribeOn(Schedulers.io()) } fun gfgDSA(): Observable<List<User>> { return Observable.create<List<User>> { shooterData -> if (!shooterData.isDisposed) { // fetch gfgData from network val gfgData = fetchUserListFromNetwork() shooterData.onNext(gfgData) shooterData.onComplete() } }.subscribeOn(Schedulers.io()) } private fun fetchUserListFromNetwork(): List<User> { return listOf() } }", "e": 1791, "s": 897, "text": null }, { "code": null, "e": 1839, "s": 1791, "text": "As an example, consider the following observer:" }, { "code": null, "e": 1846, "s": 1839, "text": "Kotlin" }, { "code": "private fun getTheObserver(): Observer<List<User>> { return object : Observer<List<User>> { override fun gfgSubscribed(d: Disposable) { println(\"gfgSubscribed\") } override fun onNext(userList: List<User>) { println(\"onNext : $userList\") } override fun onError(e: Throwable) { println(\"onError : ${e.message}\") } override fun onComplete() { println(\"onComplete\") } }}", "e": 2325, "s": 1846, "text": null }, { "code": null, "e": 2384, "s": 2325, "text": "A utility tool for identifying courses that are in common." }, { "code": null, "e": 2391, "s": 2384, "text": "Kotlin" }, { "code": "private fun CommonCourses(GfGCourses: List<User>, gfgDSACourses: List<User>): List<User> { val CommonCourses = ArrayList<User>() for (gfgDSACourse in gfgDSACourses) { if (GfGCourses.contains(gfgDSACourse)) { CommonCourses.add(gfgDSACourse) } } return CommonCourses}", "e": 2728, "s": 2391, "text": null }, { "code": null, "e": 2735, "s": 2728, "text": "Kotlin" }, { "code": "Observable.zip( gfgCourses(), gfgDSACourses(), BiFunction<List<User>, List<User>, List<User>> { cricketFans, gfgCourses-> // fetching results at once. return@BiFunction filterUserWhoLovesBoth(cricketFans, gfgDSA) }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(getObserver())", "e": 3085, "s": 2735, "text": null }, { "code": null, "e": 3491, "s": 3085, "text": "First, we make two network requests (simultaneously because we’re using Zip Operator), and then we select the courses of DSA which are part of the main courses. Both network calls are executed in parallel by zipping two observables with the RxJava Zip operator. When both observables have finished, we obtain the outcome of both. We obtain the outcomes of both observables at the same time in this manner." }, { "code": null, "e": 3577, "s": 3491, "text": "Run all jobs in parallel if Schedulers are appropriately assigned to each observable." }, { "code": null, "e": 3674, "s": 3577, "text": "When all of the jobs have been finished, return the results of all of them in a single callback." }, { "code": null, "e": 3755, "s": 3674, "text": "We may utilize the RxJava Zip Operator to solve the intriguing problem this way." }, { "code": null, "e": 3762, "s": 3755, "text": "Picked" }, { "code": null, "e": 3769, "s": 3762, "text": "RxJava" }, { "code": null, "e": 3777, "s": 3769, "text": "Android" }, { "code": null, "e": 3784, "s": 3777, "text": "Kotlin" }, { "code": null, "e": 3792, "s": 3784, "text": "Android" } ]
How to Find the Screen Resolution of a Device Programmatically in Android?
23 Feb, 2021 Screen Resolution refers to the number of pixels on display. A higher resolution means more pixels and more pixels provide the ability to display more visual information. This entity is widely used in applications related to the broadcasting of real-time visuals such as a live video, gaming, etc for the optimization and frame conversions. The same information can also be used to detect if there is damage to any of the pixels present on the screen. Practically, it is possible to retrieve this information. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file which represents the UI of the application, and create a Button which on click would generate a Toast displaying the number of pixels available at the width and length. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Button which onclick creates a Toast Message--> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="click" /> </RelativeLayout> Step 3: Working with the MainActivity.kt file Go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.graphics.Pointimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare the button from the layout file val btn = findViewById<Button>(R.id.btn) // Action when the button is clicked btn.setOnClickListener { // get default display from the windows manager val display = windowManager.defaultDisplay // declare and initialize a point val size = Point() // store the points related details from the // display variable in the size variable display.getSize(size) // store the point information in integer // variables width and height // where .x extracts width pixels and // .y extracts height pixels val width = size.x val height = size.y // Toast will display the width and height values Toast.makeText( applicationContext, "Width: $width Pixels , Height: $height Pixels", Toast.LENGTH_LONG ).show() } }} Android-Misc Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts How to Communicate Between Fragments in Android? Kotlin Array Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 705, "s": 28, "text": "Screen Resolution refers to the number of pixels on display. A higher resolution means more pixels and more pixels provide the ability to display more visual information. This entity is widely used in applications related to the broadcasting of real-time visuals such as a live video, gaming, etc for the optimization and frame conversions. The same information can also be used to detect if there is damage to any of the pixels present on the screen. Practically, it is possible to retrieve this information. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 734, "s": 705, "text": "Step 1: Create a New Project" }, { "code": null, "e": 898, "s": 734, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 946, "s": 898, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1198, "s": 946, "text": "Go to the activity_main.xml file which represents the UI of the application, and create a Button which on click would generate a Toast displaying the number of pixels available at the width and length. Below is the code for the activity_main.xml file." }, { "code": null, "e": 1202, "s": 1198, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Button which onclick creates a Toast Message--> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"click\" /> </RelativeLayout>", "e": 1760, "s": 1202, "text": null }, { "code": null, "e": 1806, "s": 1760, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 1990, "s": 1806, "text": "Go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 1997, "s": 1990, "text": "Kotlin" }, { "code": "import android.graphics.Pointimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare the button from the layout file val btn = findViewById<Button>(R.id.btn) // Action when the button is clicked btn.setOnClickListener { // get default display from the windows manager val display = windowManager.defaultDisplay // declare and initialize a point val size = Point() // store the points related details from the // display variable in the size variable display.getSize(size) // store the point information in integer // variables width and height // where .x extracts width pixels and // .y extracts height pixels val width = size.x val height = size.y // Toast will display the width and height values Toast.makeText( applicationContext, \"Width: $width Pixels , Height: $height Pixels\", Toast.LENGTH_LONG ).show() } }}", "e": 3360, "s": 1997, "text": null }, { "code": null, "e": 3373, "s": 3360, "text": "Android-Misc" }, { "code": null, "e": 3381, "s": 3373, "text": "Android" }, { "code": null, "e": 3388, "s": 3381, "text": "Kotlin" }, { "code": null, "e": 3396, "s": 3388, "text": "Android" }, { "code": null, "e": 3494, "s": 3396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3563, "s": 3494, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3595, "s": 3563, "text": "Android SDK and it's Components" }, { "code": null, "e": 3644, "s": 3595, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3683, "s": 3644, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3725, "s": 3683, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3794, "s": 3725, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3813, "s": 3794, "text": "Android UI Layouts" }, { "code": null, "e": 3862, "s": 3813, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3875, "s": 3862, "text": "Kotlin Array" } ]
How to count string occurrence in string using JavaScript?
22 Apr, 2019 In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.By counting the array size which will return the number of times the sub-string present in a string.Script to find the number of occurrences in a string: Example-1: Counting occurrence of Geeks in β€œGeeksforGeeks” using β€œmatch()” function.<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var r = "Geeks For Geeks "; document.getElementById("rk").innerHTML = (r.match(/Geeks/g)).length; } </script></body> </html>Output:Before clicking on the Button:After clicking on the Button:The β€˜g’ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence. <!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var r = "Geeks For Geeks "; document.getElementById("rk").innerHTML = (r.match(/Geeks/g)).length; } </script></body> </html> Output: Before clicking on the Button: After clicking on the Button: The β€˜g’ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence. Another Example to count the number of times the string appears in a string.Example-2: Counting occurrence of for in β€œGeeksforGeeks” using Loops.<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = "Geeks for Geeks"; var f = "for"; var i = 0, n = 0, j = 0; while (true) { j = s.indexOf(f, j); if (j >= 0) { n++; j++; } else break; } document.getElementById( "rk").innerHTML = n; } </script></body> </html>Output:Before clicking on the Button :After clicking on the Button: <!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = "Geeks for Geeks"; var f = "for"; var i = 0, n = 0, j = 0; while (true) { j = s.indexOf(f, j); if (j >= 0) { n++; j++; } else break; } document.getElementById( "rk").innerHTML = n; } </script></body> </html> Output: Before clicking on the Button : After clicking on the Button: Example-3: Counting occurrence of Geeks in β€œGeeksforGeeks” using split function.<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = "Geeks for Geeks"; var f = "Geeks"; var r = s.split(f).length - 1; document.getElementById("rk").innerHTML = r; } </script></body> </html>Output:Before clicking on the Button:After clicking on the Button: <!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = "Geeks for Geeks"; var f = "Geeks"; var r = s.split(f).length - 1; document.getElementById("rk").innerHTML = r; } </script></body> </html> Output: Before clicking on the Button: After clicking on the Button: Example-4:Counting occurrence of Geeks in β€œGeeksforGeeks” using indexof().<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = "Geeks for Geeks"; var f = "Geeks"; var r = s.indexOf(f); var c = 0; while (r != -1) { c++; r = s.indexOf(f, r + 1); } document.getElementById("rk").innerHTML = c; } </script></body> </html>Output:Before clicking on the Button :After clicking on the Button:My Personal Notes arrow_drop_upSave <!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick="gfg()"> count </button> <p id="rk"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = "Geeks for Geeks"; var f = "Geeks"; var r = s.indexOf(f); var c = 0; while (r != -1) { c++; r = s.indexOf(f, r + 1); } document.getElementById("rk").innerHTML = c; } </script></body> </html> Output: Before clicking on the Button : After clicking on the Button: JavaScript-Misc javascript-string Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? How do you run JavaScript script through the Terminal? JavaScript | console.log() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2019" }, { "code": null, "e": 420, "s": 28, "text": "In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.By counting the array size which will return the number of times the sub-string present in a string.Script to find the number of occurrences in a string:" }, { "code": null, "e": 1323, "s": 420, "text": "Example-1: Counting occurrence of Geeks in β€œGeeksforGeeks” using β€œmatch()” function.<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var r = \"Geeks For Geeks \"; document.getElementById(\"rk\").innerHTML = (r.match(/Geeks/g)).length; } </script></body> </html>Output:Before clicking on the Button:After clicking on the Button:The β€˜g’ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence." }, { "code": "<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var r = \"Geeks For Geeks \"; document.getElementById(\"rk\").innerHTML = (r.match(/Geeks/g)).length; } </script></body> </html>", "e": 1941, "s": 1323, "text": null }, { "code": null, "e": 1949, "s": 1941, "text": "Output:" }, { "code": null, "e": 1980, "s": 1949, "text": "Before clicking on the Button:" }, { "code": null, "e": 2010, "s": 1980, "text": "After clicking on the Button:" }, { "code": null, "e": 2146, "s": 2010, "text": "The β€˜g’ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence." }, { "code": null, "e": 3242, "s": 2146, "text": "Another Example to count the number of times the string appears in a string.Example-2: Counting occurrence of for in β€œGeeksforGeeks” using Loops.<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = \"Geeks for Geeks\"; var f = \"for\"; var i = 0, n = 0, j = 0; while (true) { j = s.indexOf(f, j); if (j >= 0) { n++; j++; } else break; } document.getElementById( \"rk\").innerHTML = n; } </script></body> </html>Output:Before clicking on the Button :After clicking on the Button:" }, { "code": "<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = \"Geeks for Geeks\"; var f = \"for\"; var i = 0, n = 0, j = 0; while (true) { j = s.indexOf(f, j); if (j >= 0) { n++; j++; } else break; } document.getElementById( \"rk\").innerHTML = n; } </script></body> </html>", "e": 4126, "s": 3242, "text": null }, { "code": null, "e": 4134, "s": 4126, "text": "Output:" }, { "code": null, "e": 4166, "s": 4134, "text": "Before clicking on the Button :" }, { "code": null, "e": 4196, "s": 4166, "text": "After clicking on the Button:" }, { "code": null, "e": 4989, "s": 4196, "text": "Example-3: Counting occurrence of Geeks in β€œGeeksforGeeks” using split function.<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = \"Geeks for Geeks\"; var f = \"Geeks\"; var r = s.split(f).length - 1; document.getElementById(\"rk\").innerHTML = r; } </script></body> </html>Output:Before clicking on the Button:After clicking on the Button:" }, { "code": "<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = \"Geeks for Geeks\"; var f = \"Geeks\"; var r = s.split(f).length - 1; document.getElementById(\"rk\").innerHTML = r; } </script></body> </html>", "e": 5636, "s": 4989, "text": null }, { "code": null, "e": 5644, "s": 5636, "text": "Output:" }, { "code": null, "e": 5675, "s": 5644, "text": "Before clicking on the Button:" }, { "code": null, "e": 5705, "s": 5675, "text": "After clicking on the Button:" }, { "code": null, "e": 6642, "s": 5705, "text": "Example-4:Counting occurrence of Geeks in β€œGeeksforGeeks” using indexof().<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = \"Geeks for Geeks\"; var f = \"Geeks\"; var r = s.indexOf(f); var c = 0; while (r != -1) { c++; r = s.indexOf(f, r + 1); } document.getElementById(\"rk\").innerHTML = c; } </script></body> </html>Output:Before clicking on the Button :After clicking on the Button:My Personal Notes\narrow_drop_upSave" }, { "code": "<!DOCTYPE html><html> <head> <title> count string occurrence in a string </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3> count string occurrence in a string </h3> <button onClick=\"gfg()\"> count </button> <p id=\"rk\"> </p> <!-- Script to count string occurrence in a string --> <script> function gfg() { var s = \"Geeks for Geeks\"; var f = \"Geeks\"; var r = s.indexOf(f); var c = 0; while (r != -1) { c++; r = s.indexOf(f, r + 1); } document.getElementById(\"rk\").innerHTML = c; } </script></body> </html>", "e": 7403, "s": 6642, "text": null }, { "code": null, "e": 7411, "s": 7403, "text": "Output:" }, { "code": null, "e": 7443, "s": 7411, "text": "Before clicking on the Button :" }, { "code": null, "e": 7473, "s": 7443, "text": "After clicking on the Button:" }, { "code": null, "e": 7489, "s": 7473, "text": "JavaScript-Misc" }, { "code": null, "e": 7507, "s": 7489, "text": "javascript-string" }, { "code": null, "e": 7514, "s": 7507, "text": "Picked" }, { "code": null, "e": 7525, "s": 7514, "text": "JavaScript" }, { "code": null, "e": 7623, "s": 7525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7684, "s": 7623, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7756, "s": 7684, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7796, "s": 7756, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7837, "s": 7796, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 7889, "s": 7837, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 7935, "s": 7889, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 7977, "s": 7935, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 8031, "s": 7977, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 8086, "s": 8031, "text": "How do you run JavaScript script through the Terminal?" } ]
Python | OpenCV BGR color palette with trackbars
13 Nov, 2018 OpenCV is a library of programming functions mainly aimed at real-time computer vision.In this article, Let’s create a window which will contain RGB color palette with track bars. By moving the trackbars the value of RGB Colors will change b/w 0 to 255. So using the same, we can find the color with its RGB values. Libraries needed: OpenCV Numpy Approach:Create a black window with three color channels with resolution 512 x 512. Then create three β€˜B’ β€˜G’ β€˜R’ trackbars using predefined functions of OpenCV library. Set the values of channels from 0 to 255. Merging the black window with these color trackbars. # Python program to create RGB color # palette with trackbars # importing librariesimport cv2import numpy as np # empty function called when# any trackbar movesdef emptyFunction(): pass def main(): # blackwindow having 3 color chanels image = np.zeros((512, 512, 3), np.uint8) windowName ="Open CV Color Palette" # window name cv2.namedWindow(windowName) # there trackbars which have the name # of trackbars min and max value cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction) cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction) cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction) # Used to open the window # till press the ESC key while(True): cv2.imshow(windowName, image) if cv2.waitKey(1) == 27: break # values of blue, green, red blue = cv2.getTrackbarPos('Blue', windowName) green = cv2.getTrackbarPos('Green', windowName) red = cv2.getTrackbarPos('Red', windowName) # merge all three color chanels and # make the image composites image from rgb image[:] = [blue, green, red] print(blue, green, red) cv2.destroyAllWindows() # Calling main() if __name__=="__main__": main() Output: Note: Above programs will not run on online IDE. Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Nov, 2018" }, { "code": null, "e": 344, "s": 28, "text": "OpenCV is a library of programming functions mainly aimed at real-time computer vision.In this article, Let’s create a window which will contain RGB color palette with track bars. By moving the trackbars the value of RGB Colors will change b/w 0 to 255. So using the same, we can find the color with its RGB values." }, { "code": null, "e": 375, "s": 344, "text": "Libraries needed:\nOpenCV\nNumpy" }, { "code": null, "e": 640, "s": 375, "text": "Approach:Create a black window with three color channels with resolution 512 x 512. Then create three β€˜B’ β€˜G’ β€˜R’ trackbars using predefined functions of OpenCV library. Set the values of channels from 0 to 255. Merging the black window with these color trackbars." }, { "code": "# Python program to create RGB color # palette with trackbars # importing librariesimport cv2import numpy as np # empty function called when# any trackbar movesdef emptyFunction(): pass def main(): # blackwindow having 3 color chanels image = np.zeros((512, 512, 3), np.uint8) windowName =\"Open CV Color Palette\" # window name cv2.namedWindow(windowName) # there trackbars which have the name # of trackbars min and max value cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction) cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction) cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction) # Used to open the window # till press the ESC key while(True): cv2.imshow(windowName, image) if cv2.waitKey(1) == 27: break # values of blue, green, red blue = cv2.getTrackbarPos('Blue', windowName) green = cv2.getTrackbarPos('Green', windowName) red = cv2.getTrackbarPos('Red', windowName) # merge all three color chanels and # make the image composites image from rgb image[:] = [blue, green, red] print(blue, green, red) cv2.destroyAllWindows() # Calling main() if __name__==\"__main__\": main()", "e": 1968, "s": 640, "text": null }, { "code": null, "e": 1976, "s": 1968, "text": "Output:" }, { "code": null, "e": 2025, "s": 1976, "text": "Note: Above programs will not run on online IDE." }, { "code": null, "e": 2042, "s": 2025, "text": "Image-Processing" }, { "code": null, "e": 2049, "s": 2042, "text": "OpenCV" }, { "code": null, "e": 2056, "s": 2049, "text": "Python" } ]
Two Dimensional List in R Programming
10 May, 2020 A list in R is basically an R object that contains within it, elements belonging to different data types, which may be numbers strings or even other lists. Basically, a list can contain other objects which may be of varying lengths. The list is defined using the list() function in R.A two-dimensional list can be considered as a β€œlist of lists”. A two-dimensional list can be considered as a matrix where each row can have different lengths and supports different data types. One-dimensional lists can be first created using list() function. They can be further enclosed into another outer list. The length of the outer list is the number of inner lists it contains, which is accessed by length() function. The length of the various inner lists can be computed by indexing by using length (list[[index]]) function, where the corresponding index is accessed by [[ ]]. # list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), "hi", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print ("The two-dimensional list is : ")print (list_data) cat("Length of nested list is : ", length (list_data))cat("Length of first inner list is : ", length (list_data[[1]])) Output: [1] "The two-dimensional list is : " [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] 0+5i [[2]] [[2]][[1]] [1] 6 7 8 Length of nested list is : 2 Length of first inner list is : 3 The first list contains three elements, of varying sizes and data types, a sequence of numbers 1 to 5, a string, and a complex number. The second list contains a vector of length three consisting of numbers 6 to 8. All the elements of the list can be accessed by a nested for loop. The outer loop runs uptil the number of elements of the outer list. The inner loop comprises of the individual lengths of the inner lists.The following R code indicates working with two-dimensional lists: # list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), "hi", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2) # runs uptil the length of outer listfor (i in c(1 : length(list_data))){ # runs uptil the length of inner lists at ith indices for (j in c(1: length(list_data[[i]]))) { cat ("List", i, "element", j, ": ") print (list_data[[i]][[j]]) }} Output: List 1 element 1 : [1] 1 2 3 4 5 List 1 element 2 : [1] "hi" List 1 element 3 : [1] 0+5i List 2 element 1 : [1] 6 7 8 Deletion or modification of inner listInner lists can be modified by a single level of indexing. The corresponding inner list element is set to a new value. If the new value is equal to NULL, the element is deleted otherwise modified. Deleting or Updating elements of inner listsElements of inner lists can be deleted or modified by double level of indexing. The element to be modified is set to a new value. If the value is NULL, the corresponding element is deleted. Otherwise, modified.Modification of ListsThe following R code is used for the modification of lists:# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), "hi", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print ("The original list is : ")print (list_data) # modifying third component of first listlist_data[[1]][[3]] = "you"print ("Modification 1")print (list_data) # modifying second inner listlist_data[[2]] <- list (c(0:3))print ("Modification 2")print (list_data)Output:[1] "The original list is : " [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] 0+5i [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 1" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] β€œyou” [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 2" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] "you" [[2]] [[2]][[1]] [1] 0 1 2 3Deletion of ListsThe following R code is used for the deletion of lists:# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), "hi", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print ("The original list is : ")print (list_data) # deleting third component of first listlist_data[[1]][[3]] = NULLprint ("Modification 1")print (list_data) # deleting second inner listlist_data[[2]] <- NULLprint ("Modification 2")print (list_data)Output:[1] "The original list is : " [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] 0+5i [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 1" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 2" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi"After modification 1, the size of the inner list one reduces by one. After modification 2, the second inner list is deleted and the size of the outer list reduces by one. Modification of ListsThe following R code is used for the modification of lists: # list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), "hi", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print ("The original list is : ")print (list_data) # modifying third component of first listlist_data[[1]][[3]] = "you"print ("Modification 1")print (list_data) # modifying second inner listlist_data[[2]] <- list (c(0:3))print ("Modification 2")print (list_data) Output: [1] "The original list is : " [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] 0+5i [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 1" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] β€œyou” [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 2" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] "you" [[2]] [[2]][[1]] [1] 0 1 2 3 Deletion of ListsThe following R code is used for the deletion of lists: # list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), "hi", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print ("The original list is : ")print (list_data) # deleting third component of first listlist_data[[1]][[3]] = NULLprint ("Modification 1")print (list_data) # deleting second inner listlist_data[[2]] <- NULLprint ("Modification 2")print (list_data) Output: [1] "The original list is : " [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[1]][[3]] [1] 0+5i [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 1" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" [[2]] [[2]][[1]] [1] 6 7 8 [1] "Modification 2" [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] "hi" After modification 1, the size of the inner list one reduces by one. After modification 2, the second inner list is deleted and the size of the outer list reduces by one. R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Printing Output of an R Program Group by function in R using Dplyr How to Replace specific values in column in R DataFrame ? How to filter R DataFrame by values in a column? How to change Row Names of DataFrame in R ? Creating a Data Frame from Vectors in R Programming Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 505, "s": 28, "text": "A list in R is basically an R object that contains within it, elements belonging to different data types, which may be numbers strings or even other lists. Basically, a list can contain other objects which may be of varying lengths. The list is defined using the list() function in R.A two-dimensional list can be considered as a β€œlist of lists”. A two-dimensional list can be considered as a matrix where each row can have different lengths and supports different data types." }, { "code": null, "e": 896, "s": 505, "text": "One-dimensional lists can be first created using list() function. They can be further enclosed into another outer list. The length of the outer list is the number of inner lists it contains, which is accessed by length() function. The length of the various inner lists can be computed by indexing by using length (list[[index]]) function, where the corresponding index is accessed by [[ ]]." }, { "code": "# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), \"hi\", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print (\"The two-dimensional list is : \")print (list_data) cat(\"Length of nested list is : \", length (list_data))cat(\"Length of first inner list is : \", length (list_data[[1]]))", "e": 1268, "s": 896, "text": null }, { "code": null, "e": 1276, "s": 1268, "text": "Output:" }, { "code": null, "e": 1479, "s": 1276, "text": "[1] \"The two-dimensional list is : \"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] 0+5i\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\nLength of nested list is : 2\nLength of first inner list is : 3" }, { "code": null, "e": 1694, "s": 1479, "text": "The first list contains three elements, of varying sizes and data types, a sequence of numbers 1 to 5, a string, and a complex number. The second list contains a vector of length three consisting of numbers 6 to 8." }, { "code": null, "e": 1966, "s": 1694, "text": "All the elements of the list can be accessed by a nested for loop. The outer loop runs uptil the number of elements of the outer list. The inner loop comprises of the individual lengths of the inner lists.The following R code indicates working with two-dimensional lists:" }, { "code": "# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), \"hi\", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2) # runs uptil the length of outer listfor (i in c(1 : length(list_data))){ # runs uptil the length of inner lists at ith indices for (j in c(1: length(list_data[[i]]))) { cat (\"List\", i, \"element\", j, \": \") print (list_data[[i]][[j]]) }}", "e": 2416, "s": 1966, "text": null }, { "code": null, "e": 2424, "s": 2416, "text": "Output:" }, { "code": null, "e": 2542, "s": 2424, "text": "List 1 element 1 : [1] 1 2 3 4 5\nList 1 element 2 : [1] \"hi\"\nList 1 element 3 : [1] 0+5i\nList 2 element 1 : [1] 6 7 8" }, { "code": null, "e": 2777, "s": 2542, "text": "Deletion or modification of inner listInner lists can be modified by a single level of indexing. The corresponding inner list element is set to a new value. If the new value is equal to NULL, the element is deleted otherwise modified." }, { "code": null, "e": 4936, "s": 2777, "text": "Deleting or Updating elements of inner listsElements of inner lists can be deleted or modified by double level of indexing. The element to be modified is set to a new value. If the value is NULL, the corresponding element is deleted. Otherwise, modified.Modification of ListsThe following R code is used for the modification of lists:# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), \"hi\", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print (\"The original list is : \")print (list_data) # modifying third component of first listlist_data[[1]][[3]] = \"you\"print (\"Modification 1\")print (list_data) # modifying second inner listlist_data[[2]] <- list (c(0:3))print (\"Modification 2\")print (list_data)Output:[1] \"The original list is : \"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] 0+5i\n\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n\n[1] \"Modification 1\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] β€œyou”\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n\n[1] \"Modification 2\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] \"you\"\n\n\n[[2]]\n[[2]][[1]]\n[1] 0 1 2 3Deletion of ListsThe following R code is used for the deletion of lists:# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), \"hi\", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print (\"The original list is : \")print (list_data) # deleting third component of first listlist_data[[1]][[3]] = NULLprint (\"Modification 1\")print (list_data) # deleting second inner listlist_data[[2]] <- NULLprint (\"Modification 2\")print (list_data)Output:[1] \"The original list is : \"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] 0+5i\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n[1] \"Modification 1\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n[1] \"Modification 2\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"After modification 1, the size of the inner list one reduces by one. After modification 2, the second inner list is deleted and the size of the outer list reduces by one." }, { "code": null, "e": 5017, "s": 4936, "text": "Modification of ListsThe following R code is used for the modification of lists:" }, { "code": "# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), \"hi\", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print (\"The original list is : \")print (list_data) # modifying third component of first listlist_data[[1]][[3]] = \"you\"print (\"Modification 1\")print (list_data) # modifying second inner listlist_data[[2]] <- list (c(0:3))print (\"Modification 2\")print (list_data)", "e": 5463, "s": 5017, "text": null }, { "code": null, "e": 5471, "s": 5463, "text": "Output:" }, { "code": null, "e": 5856, "s": 5471, "text": "[1] \"The original list is : \"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] 0+5i\n\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n\n[1] \"Modification 1\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] β€œyou”\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n\n[1] \"Modification 2\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] \"you\"\n\n\n[[2]]\n[[2]][[1]]\n[1] 0 1 2 3" }, { "code": null, "e": 5929, "s": 5856, "text": "Deletion of ListsThe following R code is used for the deletion of lists:" }, { "code": "# list1 and list2 are uni-dimensional listslist1 <- list (c(1:5), \"hi\", 0 + 5i)list2 <- list(c(6:8)) # create a list_data with two lists as its elementslist_data <- list(list1, list2)print (\"The original list is : \")print (list_data) # deleting third component of first listlist_data[[1]][[3]] = NULLprint (\"Modification 1\")print (list_data) # deleting second inner listlist_data[[2]] <- NULLprint (\"Modification 2\")print (list_data)", "e": 6363, "s": 5929, "text": null }, { "code": null, "e": 6371, "s": 6363, "text": "Output:" }, { "code": null, "e": 6678, "s": 6371, "text": "[1] \"The original list is : \"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[1]][[3]]\n[1] 0+5i\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n[1] \"Modification 1\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"\n\n[[2]]\n[[2]][[1]]\n[1] 6 7 8\n\n[1] \"Modification 2\"\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n\n[[1]][[2]]\n[1] \"hi\"" }, { "code": null, "e": 6849, "s": 6678, "text": "After modification 1, the size of the inner list one reduces by one. After modification 2, the second inner list is deleted and the size of the outer list reduces by one." }, { "code": null, "e": 6860, "s": 6849, "text": "R Language" }, { "code": null, "e": 6958, "s": 6860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7010, "s": 6958, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 7042, "s": 7010, "text": "Printing Output of an R Program" }, { "code": null, "e": 7077, "s": 7042, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 7135, "s": 7077, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 7184, "s": 7135, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 7228, "s": 7184, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 7280, "s": 7228, "text": "Creating a Data Frame from Vectors in R Programming" }, { "code": null, "e": 7332, "s": 7280, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 7390, "s": 7332, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Kibana - Loading Sample Data
We have seen how to upload data from logstash to elasticsearch. We will upload data using logstash and elasticsearch here. But about the data that has date, longitude and latitudefields which we need to use, we will learn in the upcoming chapters. We will also see how to upload data directly in Kibana, if we do not have a CSV file. In this chapter, we will cover following topics βˆ’ Using Logstash upload data having date, longitude and latitude fields in Elasticsearch Using Dev tools to upload bulk data We are going to use data in the form of CSV format and the same is taken from Kaggle.com which deals with data that you can use for an analysis. The data home medical visits to be used here is picked up from site Kaggle.com. The following are the fields available for the CSV file βˆ’ ["Visit_Status","Time_Delay","City","City_id","Patient_Age","Zipcode","Latitude","Longitude", "Pathology","Visiting_Date","Id_type","Id_personal","Number_Home_Visits","Is_Patient_Minor","Geo_point"] The Home_visits.csv is as follows βˆ’ The following is the conf file to be used with logstash βˆ’ input { file { path => "C:/kibanaproject/home_visits.csv" start_position => "beginning" sincedb_path => "NUL" } } filter { csv { separator => "," columns => ["Visit_Status","Time_Delay","City","City_id","Patient_Age", "Zipcode","Latitude","Longitude","Pathology","Visiting_Date", "Id_type","Id_personal","Number_Home_Visits","Is_Patient_Minor","Geo_point"] } date { match => ["Visiting_Date","dd-MM-YYYY HH:mm"] target => "Visiting_Date" } mutate {convert => ["Number_Home_Visits", "integer"]} mutate {convert => ["City_id", "integer"]} mutate {convert => ["Id_personal", "integer"]} mutate {convert => ["Id_type", "integer"]} mutate {convert => ["Zipcode", "integer"]} mutate {convert => ["Patient_Age", "integer"]} mutate { convert => { "Longitude" => "float" } convert => { "Latitude" => "float" } } mutate { rename => { "Longitude" => "[location][lon]" "Latitude" => "[location][lat]" } } } output { elasticsearch { hosts => ["localhost:9200"] index => "medicalvisits-%{+dd.MM.YYYY}" } stdout {codec => json_lines } } By default, logstash considers everything to be uploaded in elasticsearch as string. Incase your CSV file has date field you need to do following to get the date format. For date field βˆ’ date { match => ["Visiting_Date","dd-MM-YYYY HH:mm"] target => "Visiting_Date" } In-case of geo location, elasticsearch understands the same as βˆ’ "location": { "lat":41.565505000000044, "lon": 2.2349995750000695 } So we need to make sure we have Longitude and Latitude in the format elasticsearch needs it. So first we need to convert longitude and latitude to float and later rename it so that it is available as part of location json object with lat and lon. The code for the same is shown here βˆ’ mutate { convert => { "Longitude" => "float" } convert => { "Latitude" => "float" } } mutate { rename => { "Longitude" => "[location][lon]" "Latitude" => "[location][lat]" } } For converting fields to integers, use the following code βˆ’ mutate {convert => ["Number_Home_Visits", "integer"]} mutate {convert => ["City_id", "integer"]} mutate {convert => ["Id_personal", "integer"]} mutate {convert => ["Id_type", "integer"]} mutate {convert => ["Zipcode", "integer"]} mutate {convert => ["Patient_Age", "integer"]} Once the fields are taken care, run the following command to upload the data in elasticsearch βˆ’ Go inside Logstash bin directory and run the following command. logstash -f logstash_homevisists.conf Once done you should see the index mentioned in logstash conf file in elasticsearch as shown below βˆ’ We can now create index pattern on above index uploaded and use it further for creating visualization. We are going to use Dev Tools from Kibana UI. Dev Tools is helpful to upload data in Elasticsearch, without using Logstash. We can post, put, delete, search the data we want in Kibana using Dev Tools. In this section, we will try to load sample data in Kibana itself. We can use it to practice with the sample data and play around with Kibana features to get a good understanding of Kibana. Let us take the json data from the following url and upload the same in Kibana. Similarly, you can try any sample json data to be loaded inside Kibana. Before we start to upload the sample data, we need to have the json data with indices to be used in elasticsearch. When we upload it using logstash, logstash takes care to add the indices and the user does not have to bother about the indices which are required by elasticsearch. [ {"type":"act","line_id":1,"play_name":"Henry IV", "speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"}, {"type":"scene","line_id":2,"play_name":"Henry IV", "speech_number":"","line_number":"","speaker":"","text_entry":"SCENE I.London. The palace."}, {"type":"line","line_id":3,"play_name":"Henry IV", "speech_number":"","line_number":"","speaker":"","text_entry": "Enter KING HENRY, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR WALTER BLUNT, and others"} ] The json code to used with Kibana has to be with indexed as follows βˆ’ {"index":{"_index":"shakespeare","_id":0}} {"type":"act","line_id":1,"play_name":"Henry IV", "speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"} {"index":{"_index":"shakespeare","_id":1}} {"type":"scene","line_id":2,"play_name":"Henry IV", "speech_number":"","line_number":"","speaker":"", "text_entry":"SCENE I. London. The palace."} {"index":{"_index":"shakespeare","_id":2}} {"type":"line","line_id":3,"play_name":"Henry IV", "speech_number":"","line_number":"","speaker":"","text_entry": "Enter KING HENRY, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR WALTER BLUNT, and others"} Note that there is an additional data that goes in the jsonfile βˆ’{"index":{"_index":"nameofindex","_id":key}}. To convert any sample json file compatible with elasticsearch, here we have a small code in php which will output the json file given to the format which elasticsearch wants βˆ’ <?php $myfile = fopen("todo.json", "r") or die("Unable to open file!"); // your json file here $alldata = fread($myfile,filesize("todo.json")); fclose($myfile); $farray = json_decode($alldata); $afinalarray = []; $index_name = "todo"; $i=0; $myfile1 = fopen("todonewfile.json", "w") or die("Unable to open file!"); // writes a new file to be used in kibana dev tool foreach ($farray as $a => $value) { $_index = json_decode('{"index": {"_index": "'.$index_name.'", "_id": "'.$i.'"}}'); fwrite($myfile1, json_encode($_index)); fwrite($myfile1, "\n"); fwrite($myfile1, json_encode($value)); fwrite($myfile1, "\n"); $i++; } ?> We have taken the todo json file from https://jsonplaceholder.typicode.com/todos and use php code to convert to the format we need to upload in Kibana. To load the sample data, open the dev tools tab as shown below βˆ’ We are now going to use the console as shown above. We will take the json data which we got after running it through php code. The command to be used in dev tools to upload the json data is βˆ’ POST _bulk Note that the name of the index we are creating is todo. Once you click the green button the data is uploaded, you can check if the index is created or not in elasticsearch as follows βˆ’ You can check the same in dev tools itself as follows βˆ’ Command βˆ’ GET /_cat/indices If you want to search something in your index:todo , you can do that as shown below βˆ’ Command in dev tool GET /todo/_search The output of the above search is as shown below βˆ’ It gives all the records present in the todoindex. The total records we are getting is 200. We can do that using the following command βˆ’ GET /todo/_search { "query":{ "match":{ "title":"delectusautautem" } } } We are able to fetch the records which match with the title we have given.
[ { "code": null, "e": 2573, "s": 2239, "text": "We have seen how to upload data from logstash to elasticsearch. We will upload data using logstash and elasticsearch here. But about the data that has date, longitude and latitudefields which we need to use, we will learn in the upcoming chapters. We will also see how to upload data directly in Kibana, if we do not have a CSV file." }, { "code": null, "e": 2623, "s": 2573, "text": "In this chapter, we will cover following topics βˆ’" }, { "code": null, "e": 2710, "s": 2623, "text": "Using Logstash upload data having date, longitude and latitude fields in Elasticsearch" }, { "code": null, "e": 2746, "s": 2710, "text": "Using Dev tools to upload bulk data" }, { "code": null, "e": 2891, "s": 2746, "text": "We are going to use data in the form of CSV format and the same is taken from Kaggle.com which deals with data that you can use for an analysis." }, { "code": null, "e": 2971, "s": 2891, "text": "The data home medical visits to be used here is picked up from site Kaggle.com." }, { "code": null, "e": 3029, "s": 2971, "text": "The following are the fields available for the CSV file βˆ’" }, { "code": null, "e": 3229, "s": 3029, "text": "[\"Visit_Status\",\"Time_Delay\",\"City\",\"City_id\",\"Patient_Age\",\"Zipcode\",\"Latitude\",\"Longitude\",\n\"Pathology\",\"Visiting_Date\",\"Id_type\",\"Id_personal\",\"Number_Home_Visits\",\"Is_Patient_Minor\",\"Geo_point\"]\n" }, { "code": null, "e": 3265, "s": 3229, "text": "The Home_visits.csv is as follows βˆ’" }, { "code": null, "e": 3323, "s": 3265, "text": "The following is the conf file to be used with logstash βˆ’" }, { "code": null, "e": 4516, "s": 3323, "text": "input {\n file {\n path => \"C:/kibanaproject/home_visits.csv\"\n start_position => \"beginning\"\n sincedb_path => \"NUL\"\n }\n}\nfilter {\n csv {\n separator => \",\"\n columns =>\n [\"Visit_Status\",\"Time_Delay\",\"City\",\"City_id\",\"Patient_Age\",\n \"Zipcode\",\"Latitude\",\"Longitude\",\"Pathology\",\"Visiting_Date\",\n \"Id_type\",\"Id_personal\",\"Number_Home_Visits\",\"Is_Patient_Minor\",\"Geo_point\"]\n }\n date {\n match => [\"Visiting_Date\",\"dd-MM-YYYY HH:mm\"]\n target => \"Visiting_Date\"\n }\n mutate {convert => [\"Number_Home_Visits\", \"integer\"]}\n mutate {convert => [\"City_id\", \"integer\"]}\n mutate {convert => [\"Id_personal\", \"integer\"]}\n mutate {convert => [\"Id_type\", \"integer\"]}\n mutate {convert => [\"Zipcode\", \"integer\"]}\n mutate {convert => [\"Patient_Age\", \"integer\"]}\n mutate {\n convert => { \"Longitude\" => \"float\" }\n convert => { \"Latitude\" => \"float\" }\n }\n mutate {\n rename => {\n \"Longitude\" => \"[location][lon]\"\n \"Latitude\" => \"[location][lat]\"\n }\n }\n}\noutput {\n elasticsearch {\n hosts => [\"localhost:9200\"]\n index => \"medicalvisits-%{+dd.MM.YYYY}\"\n }\n stdout {codec => json_lines }\n}" }, { "code": null, "e": 4686, "s": 4516, "text": "By default, logstash considers everything to be uploaded in elasticsearch as string. Incase your CSV file has date field you need to do following to get the date format." }, { "code": null, "e": 4703, "s": 4686, "text": "For date field βˆ’" }, { "code": null, "e": 4790, "s": 4703, "text": "date {\n match => [\"Visiting_Date\",\"dd-MM-YYYY HH:mm\"]\n target => \"Visiting_Date\"\n}" }, { "code": null, "e": 4855, "s": 4790, "text": "In-case of geo location, elasticsearch understands the same as βˆ’" }, { "code": null, "e": 4929, "s": 4855, "text": "\"location\": {\n \"lat\":41.565505000000044,\n \"lon\": 2.2349995750000695\n}" }, { "code": null, "e": 5214, "s": 4929, "text": "So we need to make sure we have Longitude and Latitude in the format elasticsearch needs it. So first we need to convert longitude and latitude to float and later rename it so that it is available as part of location json object with lat and lon. The code for the same is shown here βˆ’" }, { "code": null, "e": 5423, "s": 5214, "text": "mutate {\n convert => { \"Longitude\" => \"float\" }\n convert => { \"Latitude\" => \"float\" }\n }\nmutate {\n rename => {\n \"Longitude\" => \"[location][lon]\"\n \"Latitude\" => \"[location][lat]\"\n }\n}" }, { "code": null, "e": 5483, "s": 5423, "text": "For converting fields to integers, use the following code βˆ’" }, { "code": null, "e": 5760, "s": 5483, "text": "mutate {convert => [\"Number_Home_Visits\", \"integer\"]}\nmutate {convert => [\"City_id\", \"integer\"]}\nmutate {convert => [\"Id_personal\", \"integer\"]}\nmutate {convert => [\"Id_type\", \"integer\"]}\nmutate {convert => [\"Zipcode\", \"integer\"]}\nmutate {convert => [\"Patient_Age\", \"integer\"]}" }, { "code": null, "e": 5856, "s": 5760, "text": "Once the fields are taken care, run the following command to upload the data in elasticsearch βˆ’" }, { "code": null, "e": 5920, "s": 5856, "text": "Go inside Logstash bin directory and run the following command." }, { "code": null, "e": 5959, "s": 5920, "text": "logstash -f logstash_homevisists.conf\n" }, { "code": null, "e": 6060, "s": 5959, "text": "Once done you should see the index mentioned in logstash conf file in elasticsearch as shown below βˆ’" }, { "code": null, "e": 6163, "s": 6060, "text": "We can now create index pattern on above index uploaded and use it further for creating\nvisualization." }, { "code": null, "e": 6364, "s": 6163, "text": "We are going to use Dev Tools from Kibana UI. Dev Tools is helpful to upload data in Elasticsearch, without using Logstash. We can post, put, delete, search the data we want in Kibana using Dev Tools." }, { "code": null, "e": 6554, "s": 6364, "text": "In this section, we will try to load sample data in Kibana itself. We can use it to practice with the sample data and play around with Kibana features to get a good understanding of Kibana." }, { "code": null, "e": 6706, "s": 6554, "text": "Let us take the json data from the following url and upload the same in Kibana. Similarly, you can try any sample json data to be loaded inside Kibana." }, { "code": null, "e": 6986, "s": 6706, "text": "Before we start to upload the sample data, we need to have the json data with indices to be used in elasticsearch. When we upload it using logstash, logstash takes care to add the indices and the user does not have to bother about the indices which are required by elasticsearch." }, { "code": null, "e": 7503, "s": 6986, "text": "[\n {\"type\":\"act\",\"line_id\":1,\"play_name\":\"Henry IV\", \n \n \"speech_number\":\"\",\"line_number\":\"\",\"speaker\":\"\",\"text_entry\":\"ACT I\"},\n {\"type\":\"scene\",\"line_id\":2,\"play_name\":\"Henry IV\",\n \"speech_number\":\"\",\"line_number\":\"\",\"speaker\":\"\",\"text_entry\":\"SCENE I.London. The palace.\"},\n {\"type\":\"line\",\"line_id\":3,\"play_name\":\"Henry IV\",\n \"speech_number\":\"\",\"line_number\":\"\",\"speaker\":\"\",\"text_entry\":\n \"Enter KING HENRY, LORD JOHN OF LANCASTER, the \n EARL of WESTMORELAND, SIR WALTER BLUNT, and others\"}\n]\n" }, { "code": null, "e": 7573, "s": 7503, "text": "The json code to used with Kibana has to be with indexed as follows βˆ’" }, { "code": null, "e": 8187, "s": 7573, "text": "{\"index\":{\"_index\":\"shakespeare\",\"_id\":0}}\n{\"type\":\"act\",\"line_id\":1,\"play_name\":\"Henry IV\", \n\"speech_number\":\"\",\"line_number\":\"\",\"speaker\":\"\",\"text_entry\":\"ACT I\"}\n{\"index\":{\"_index\":\"shakespeare\",\"_id\":1}}\n{\"type\":\"scene\",\"line_id\":2,\"play_name\":\"Henry IV\",\n\"speech_number\":\"\",\"line_number\":\"\",\"speaker\":\"\",\n\"text_entry\":\"SCENE I. London. The palace.\"}\n{\"index\":{\"_index\":\"shakespeare\",\"_id\":2}}\n{\"type\":\"line\",\"line_id\":3,\"play_name\":\"Henry IV\",\n\"speech_number\":\"\",\"line_number\":\"\",\"speaker\":\"\",\"text_entry\":\n\"Enter KING HENRY, LORD JOHN OF LANCASTER, the EARL \nof WESTMORELAND, SIR WALTER BLUNT, and others\"}\n" }, { "code": null, "e": 8298, "s": 8187, "text": "Note that there is an additional data that goes in the jsonfile βˆ’{\"index\":{\"_index\":\"nameofindex\",\"_id\":key}}." }, { "code": null, "e": 8474, "s": 8298, "text": "To convert any sample json file compatible with elasticsearch, here we have a small code in php which will output the json file given to the format which elasticsearch wants βˆ’" }, { "code": null, "e": 9170, "s": 8474, "text": "<?php\n $myfile = fopen(\"todo.json\", \"r\") or die(\"Unable to open file!\"); // your json\n file here\n $alldata = fread($myfile,filesize(\"todo.json\"));\n fclose($myfile);\n $farray = json_decode($alldata);\n $afinalarray = [];\n $index_name = \"todo\";\n $i=0;\n $myfile1 = fopen(\"todonewfile.json\", \"w\") or die(\"Unable to open file!\"); //\n writes a new file to be used in kibana dev tool\n foreach ($farray as $a => $value) {\n $_index = json_decode('{\"index\": {\"_index\": \"'.$index_name.'\", \"_id\": \"'.$i.'\"}}');\n fwrite($myfile1, json_encode($_index));\n fwrite($myfile1, \"\\n\");\n fwrite($myfile1, json_encode($value));\n fwrite($myfile1, \"\\n\");\n $i++;\n }\n?>" }, { "code": null, "e": 9322, "s": 9170, "text": "We have taken the todo json file from https://jsonplaceholder.typicode.com/todos and use php code to convert to the format we need to upload in Kibana." }, { "code": null, "e": 9387, "s": 9322, "text": "To load the sample data, open the dev tools tab as shown below βˆ’" }, { "code": null, "e": 9514, "s": 9387, "text": "We are now going to use the console as shown above. We will take the json data which we got after running it through php code." }, { "code": null, "e": 9579, "s": 9514, "text": "The command to be used in dev tools to upload the json data is βˆ’" }, { "code": null, "e": 9591, "s": 9579, "text": "POST _bulk\n" }, { "code": null, "e": 9648, "s": 9591, "text": "Note that the name of the index we are creating is todo." }, { "code": null, "e": 9777, "s": 9648, "text": "Once you click the green button the data is uploaded, you can check if the index is created or not in elasticsearch as follows βˆ’" }, { "code": null, "e": 9833, "s": 9777, "text": "You can check the same in dev tools itself as follows βˆ’" }, { "code": null, "e": 9843, "s": 9833, "text": "Command βˆ’" }, { "code": null, "e": 9862, "s": 9843, "text": "GET /_cat/indices\n" }, { "code": null, "e": 9948, "s": 9862, "text": "If you want to search something in your index:todo , you can do that as shown below βˆ’" }, { "code": null, "e": 9968, "s": 9948, "text": "Command in dev tool" }, { "code": null, "e": 9987, "s": 9968, "text": "GET /todo/_search\n" }, { "code": null, "e": 10038, "s": 9987, "text": "The output of the above search is as shown below βˆ’" }, { "code": null, "e": 10130, "s": 10038, "text": "It gives all the records present in the todoindex. The total records we are getting is 200." }, { "code": null, "e": 10175, "s": 10130, "text": "We can do that using the following command βˆ’" }, { "code": null, "e": 10276, "s": 10175, "text": "GET /todo/_search\n{\n \"query\":{\n \"match\":{\n \"title\":\"delectusautautem\"\n }\n }\n}\n" } ]
regex_replace in C++ | Replace the match of a string using regex_replace
04 Sep, 2018 std::regex_replace() is used to replace all matches in a string, Syntax: regex_replace(subject, regex_object, replace_text) Parameters: It accepts three parameters which are described below: Subject string as the first parameter.The regex object as the second parameter.The string with the replacement text as the third parameter. Subject string as the first parameter. The regex object as the second parameter. The string with the replacement text as the third parameter. Return Value: Function returns a new string with the replacements applied. $& or $0 is used to insert the whole regex match.$1, $2, ... up to $9 is used to insert the text matched by the first nine capturing groups.$` (back-tick) is used to insert the string that is left of the match.$’ (quote) is used to insert the string that is right of the match.If number of capturing group is less than the requested, then that will be replaced by nothing. $& or $0 is used to insert the whole regex match. $1, $2, ... up to $9 is used to insert the text matched by the first nine capturing groups. $` (back-tick) is used to insert the string that is left of the match. $’ (quote) is used to insert the string that is right of the match. If number of capturing group is less than the requested, then that will be replaced by nothing. Examples:Suppose a regex object re(β€œ(geeks)(.*)”) is created and the subject string is: subject(β€œits all about geeksforgeeks”), you want to replace the match by the content of any capturing group (eg $0, $1, ... upto 9). Example-1:Replace the match by the content of $1.Here match is β€œgeeksforgeeks” that will be replaced by $1(β€œgeeks”).Hence, result β€œits all about geeks”. Example-2:Replace the match by the content of $2.Here match is β€œgeeksforgeeks” that will be replaced by $2(β€œforgeeks”).Hence, result β€œits all about forgeeks”. Below is the program to show the working of regex_replace. // C++ program to show the working// of regex_replace#include <bits/stdc++.h>using namespace std; int main(){ string subject("its all about geeksforgeeks"); string result1, result2, result3, result4; string result5; // regex object regex re("(geeks)(.*)"); // $2 contains, 2nd capturing group which is (.*) means // string after "geeks" which is "forgeeks". hence // the match(geeksforgeeks) will be replaced by "forgeeks". // so the result1 = "its all about forgeeks" result1 = regex_replace(subject, re, "$2"); // similarly $1 contains, 1 st capturing group which is // "geeks" so the match(geeksforgeeks) will be replaced // by "geeks".so the result2 = "its all about geeks". result2 = regex_replace(subject, re, "$1"); // $0 contains the whole match // so result3 will remain same. result3 = regex_replace(subject, re, "$0"); // $0 and $& contains the whole match // so result3 will remain same result4 = regex_replace(subject, re, "$&"); // Here number of capturing group // is 2 so anything above 2 // will be replaced by nothing. result5 = regex_replace(subject, re, "$6"); cout << result1 << endl << result2 << endl; cout << result3 << endl << result4 << endl << result5; return 0;} its all about forgeeks its all about geeks its all about geeksforgeeks its all about geeksforgeeks its all about CPP-Library CPP-regex C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Sep, 2018" }, { "code": null, "e": 117, "s": 52, "text": "std::regex_replace() is used to replace all matches in a string," }, { "code": null, "e": 125, "s": 117, "text": "Syntax:" }, { "code": null, "e": 177, "s": 125, "text": "regex_replace(subject, regex_object, replace_text)\n" }, { "code": null, "e": 244, "s": 177, "text": "Parameters: It accepts three parameters which are described below:" }, { "code": null, "e": 384, "s": 244, "text": "Subject string as the first parameter.The regex object as the second parameter.The string with the replacement text as the third parameter." }, { "code": null, "e": 423, "s": 384, "text": "Subject string as the first parameter." }, { "code": null, "e": 465, "s": 423, "text": "The regex object as the second parameter." }, { "code": null, "e": 526, "s": 465, "text": "The string with the replacement text as the third parameter." }, { "code": null, "e": 601, "s": 526, "text": "Return Value: Function returns a new string with the replacements applied." }, { "code": null, "e": 974, "s": 601, "text": "$& or $0 is used to insert the whole regex match.$1, $2, ... up to $9 is used to insert the text matched by the first nine capturing groups.$` (back-tick) is used to insert the string that is left of the match.$’ (quote) is used to insert the string that is right of the match.If number of capturing group is less than the requested, then that will be replaced by nothing." }, { "code": null, "e": 1024, "s": 974, "text": "$& or $0 is used to insert the whole regex match." }, { "code": null, "e": 1116, "s": 1024, "text": "$1, $2, ... up to $9 is used to insert the text matched by the first nine capturing groups." }, { "code": null, "e": 1187, "s": 1116, "text": "$` (back-tick) is used to insert the string that is left of the match." }, { "code": null, "e": 1255, "s": 1187, "text": "$’ (quote) is used to insert the string that is right of the match." }, { "code": null, "e": 1351, "s": 1255, "text": "If number of capturing group is less than the requested, then that will be replaced by nothing." }, { "code": null, "e": 1572, "s": 1351, "text": "Examples:Suppose a regex object re(β€œ(geeks)(.*)”) is created and the subject string is: subject(β€œits all about geeksforgeeks”), you want to replace the match by the content of any capturing group (eg $0, $1, ... upto 9)." }, { "code": null, "e": 1725, "s": 1572, "text": "Example-1:Replace the match by the content of $1.Here match is β€œgeeksforgeeks” that will be replaced by $1(β€œgeeks”).Hence, result β€œits all about geeks”." }, { "code": null, "e": 1884, "s": 1725, "text": "Example-2:Replace the match by the content of $2.Here match is β€œgeeksforgeeks” that will be replaced by $2(β€œforgeeks”).Hence, result β€œits all about forgeeks”." }, { "code": null, "e": 1943, "s": 1884, "text": "Below is the program to show the working of regex_replace." }, { "code": "// C++ program to show the working// of regex_replace#include <bits/stdc++.h>using namespace std; int main(){ string subject(\"its all about geeksforgeeks\"); string result1, result2, result3, result4; string result5; // regex object regex re(\"(geeks)(.*)\"); // $2 contains, 2nd capturing group which is (.*) means // string after \"geeks\" which is \"forgeeks\". hence // the match(geeksforgeeks) will be replaced by \"forgeeks\". // so the result1 = \"its all about forgeeks\" result1 = regex_replace(subject, re, \"$2\"); // similarly $1 contains, 1 st capturing group which is // \"geeks\" so the match(geeksforgeeks) will be replaced // by \"geeks\".so the result2 = \"its all about geeks\". result2 = regex_replace(subject, re, \"$1\"); // $0 contains the whole match // so result3 will remain same. result3 = regex_replace(subject, re, \"$0\"); // $0 and $& contains the whole match // so result3 will remain same result4 = regex_replace(subject, re, \"$&\"); // Here number of capturing group // is 2 so anything above 2 // will be replaced by nothing. result5 = regex_replace(subject, re, \"$6\"); cout << result1 << endl << result2 << endl; cout << result3 << endl << result4 << endl << result5; return 0;}", "e": 3242, "s": 1943, "text": null }, { "code": null, "e": 3356, "s": 3242, "text": "its all about forgeeks\nits all about geeks\nits all about geeksforgeeks\nits all about geeksforgeeks\nits all about\n" }, { "code": null, "e": 3368, "s": 3356, "text": "CPP-Library" }, { "code": null, "e": 3378, "s": 3368, "text": "CPP-regex" }, { "code": null, "e": 3382, "s": 3378, "text": "C++" }, { "code": null, "e": 3386, "s": 3382, "text": "CPP" }, { "code": null, "e": 3484, "s": 3386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3508, "s": 3484, "text": "Sorting a vector in C++" }, { "code": null, "e": 3528, "s": 3508, "text": "Polymorphism in C++" }, { "code": null, "e": 3561, "s": 3528, "text": "Friend class and function in C++" }, { "code": null, "e": 3605, "s": 3561, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3630, "s": 3605, "text": "std::string class in C++" }, { "code": null, "e": 3675, "s": 3630, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3723, "s": 3675, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3740, "s": 3723, "text": "std::find in C++" }, { "code": null, "e": 3784, "s": 3740, "text": "List in C++ Standard Template Library (STL)" } ]
OffsetDateTime compareTo() method in Java with examples
04 Dec, 2021 The compareTo() method of OffsetDateTime class in Java compares this date-time to another date-time.Syntax : public int compareTo(OffsetDateTime other) Parameter : This method accepts a single parameter other which specifies the other date-time to compare to, not null.Return Value: It returns the comparator value, negative if less, positive if greater.Below programs illustrate the compareTo() method:Program 1 : Java // Java program to demonstrate the compareTo() method import java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); // Parses the date2 OffsetDateTime date2 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); // Prints both dates System.out.println("Date1: " + date1); System.out.println("Date2: " + date2); // Compare both System.out.println("On comparing we get " + date1.compareTo(date2)); }} Date1: 2018-12-12T13:30:30+05:00 Date2: 2018-12-12T13:30:30+05:00 On comparing we get 0 Program 2 : Java // Java program to demonstrate the compareTo() methodimport java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); // Parses the date2 OffsetDateTime date2 = OffsetDateTime.parse("2015-12-12T13:30:30+05:00"); // Prints both dates System.out.println("Date1: " + date1); System.out.println("Date2: " + date2); // Compare both System.out.println("On comparing we get " + date1.compareTo(date2)); }} Date1: 2018-12-12T13:30:30+05:00 Date2: 2015-12-12T13:30:30+05:00 On comparing we get 3 Program 3 : Java // Java program to demonstrate the compareTo() methodimport java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2013-12-12T13:30:30+05:00"); // Parses the date2 OffsetDateTime date2 = OffsetDateTime.parse("2015-12-12T13:30:30+05:00"); // Prints both dates System.out.println("Date1: " + date1); System.out.println("Date2: " + date2); // Compare both System.out.println("On comparing we get " + date1.compareTo(date2)); }} Date1: 2013-12-12T13:30:30+05:00 Date2: 2015-12-12T13:30:30+05:00 On comparing we get -2 Reference: https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjuster.html kapoorsagar226 Java-Functions Java-OffsetDateTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2021" }, { "code": null, "e": 139, "s": 28, "text": "The compareTo() method of OffsetDateTime class in Java compares this date-time to another date-time.Syntax : " }, { "code": null, "e": 182, "s": 139, "text": "public int compareTo(OffsetDateTime other)" }, { "code": null, "e": 446, "s": 182, "text": "Parameter : This method accepts a single parameter other which specifies the other date-time to compare to, not null.Return Value: It returns the comparator value, negative if less, positive if greater.Below programs illustrate the compareTo() method:Program 1 : " }, { "code": null, "e": 451, "s": 446, "text": "Java" }, { "code": "// Java program to demonstrate the compareTo() method import java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse(\"2018-12-12T13:30:30+05:00\"); // Parses the date2 OffsetDateTime date2 = OffsetDateTime.parse(\"2018-12-12T13:30:30+05:00\"); // Prints both dates System.out.println(\"Date1: \" + date1); System.out.println(\"Date2: \" + date2); // Compare both System.out.println(\"On comparing we get \" + date1.compareTo(date2)); }}", "e": 1080, "s": 451, "text": null }, { "code": null, "e": 1168, "s": 1080, "text": "Date1: 2018-12-12T13:30:30+05:00\nDate2: 2018-12-12T13:30:30+05:00\nOn comparing we get 0" }, { "code": null, "e": 1181, "s": 1168, "text": "Program 2 : " }, { "code": null, "e": 1186, "s": 1181, "text": "Java" }, { "code": "// Java program to demonstrate the compareTo() methodimport java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse(\"2018-12-12T13:30:30+05:00\"); // Parses the date2 OffsetDateTime date2 = OffsetDateTime.parse(\"2015-12-12T13:30:30+05:00\"); // Prints both dates System.out.println(\"Date1: \" + date1); System.out.println(\"Date2: \" + date2); // Compare both System.out.println(\"On comparing we get \" + date1.compareTo(date2)); }}", "e": 1814, "s": 1186, "text": null }, { "code": null, "e": 1902, "s": 1814, "text": "Date1: 2018-12-12T13:30:30+05:00\nDate2: 2015-12-12T13:30:30+05:00\nOn comparing we get 3" }, { "code": null, "e": 1915, "s": 1902, "text": "Program 3 : " }, { "code": null, "e": 1920, "s": 1915, "text": "Java" }, { "code": "// Java program to demonstrate the compareTo() methodimport java.time.OffsetDateTime;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse(\"2013-12-12T13:30:30+05:00\"); // Parses the date2 OffsetDateTime date2 = OffsetDateTime.parse(\"2015-12-12T13:30:30+05:00\"); // Prints both dates System.out.println(\"Date1: \" + date1); System.out.println(\"Date2: \" + date2); // Compare both System.out.println(\"On comparing we get \" + date1.compareTo(date2)); }}", "e": 2548, "s": 1920, "text": null }, { "code": null, "e": 2637, "s": 2548, "text": "Date1: 2013-12-12T13:30:30+05:00\nDate2: 2015-12-12T13:30:30+05:00\nOn comparing we get -2" }, { "code": null, "e": 2731, "s": 2637, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjuster.html" }, { "code": null, "e": 2746, "s": 2731, "text": "kapoorsagar226" }, { "code": null, "e": 2761, "s": 2746, "text": "Java-Functions" }, { "code": null, "e": 2781, "s": 2761, "text": "Java-OffsetDateTime" }, { "code": null, "e": 2799, "s": 2781, "text": "Java-time package" }, { "code": null, "e": 2804, "s": 2799, "text": "Java" }, { "code": null, "e": 2809, "s": 2804, "text": "Java" }, { "code": null, "e": 2907, "s": 2809, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2958, "s": 2907, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2989, "s": 2958, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3008, "s": 2989, "text": "Interfaces in Java" }, { "code": null, "e": 3038, "s": 3008, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3056, "s": 3038, "text": "ArrayList in Java" }, { "code": null, "e": 3076, "s": 3056, "text": "Collections in Java" }, { "code": null, "e": 3100, "s": 3076, "text": "Singleton Class in Java" }, { "code": null, "e": 3132, "s": 3100, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3144, "s": 3132, "text": "Set in Java" } ]
How to filter object array based on attributes?
02 Nov, 2020 One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array. The filter() function loops or iterate over each array element and pass each element to the callback function. Syntax: var newArray = array.filter(function(item) { return conditional_statement; }); Note: The filter() function does not change the original array. Example 1: We create an array of β€œstudents” and call the filter() function on array to derive the elements from array that satisfy the given condition. Javascript <script>var obj = { 'Students': [{ "name": "Raj", "Age":"15", "RollNumber": "123", "Marks": "99", }, { "name": "Aman", "Age":"14", "RollNumber": "223", "Marks": "69", }, { "name": "Vivek", "Age":"13", "RollNumber": "253", "Marks": "89", }, ]}; var newArray = obj.Students.filter(function (el){ return el.Age >=15 && el.RollNumber <= 200 && el.Marks >= 80 ;});console.log(newArray);</script> Output: After apply filter function on array, we get the first element of array as output as it satisfy the given condition. Example 2: The following example shows filtering invalid entries from array. We create an array of β€œid”s and call the filter() function on the array to derive the β€œid”s whose values are non-zero and numeric. Javascript <script>let array = [ { id: 3 }, { id: -1 }, { id: 0 }, { id: 15 }, { id: 12.2 }, { }, { id: null }, { id: NaN }, { id: 'undefined' }] let countInvalidEntries = 0 function filterById(obj) { if (Number.isFinite(obj.id) && obj.id !== 0) { return true } countInvalidEntries++ return false;} let arrayById = array.filter(filterById); console.log('Filtered Array with non-zero and numeric id: \n', arrayById); console.log('Number of Invalid Entries = ', countInvalidEntries); </script> Output: After applying filter() function on the array of size 9, we get 4 valid (non-zero and numeric) id and 5 invalid id JavaScript-Misc How To JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Nov, 2020" }, { "code": null, "e": 427, "s": 52, "text": "One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array. The filter() function loops or iterate over each array element and pass each element to the callback function." }, { "code": null, "e": 435, "s": 427, "text": "Syntax:" }, { "code": null, "e": 519, "s": 435, "text": "var newArray = array.filter(function(item)\n {\n return conditional_statement;\n });\n" }, { "code": null, "e": 583, "s": 519, "text": "Note: The filter() function does not change the original array." }, { "code": null, "e": 735, "s": 583, "text": "Example 1: We create an array of β€œstudents” and call the filter() function on array to derive the elements from array that satisfy the given condition." }, { "code": null, "e": 746, "s": 735, "text": "Javascript" }, { "code": "<script>var obj = { 'Students': [{ \"name\": \"Raj\", \"Age\":\"15\", \"RollNumber\": \"123\", \"Marks\": \"99\", }, { \"name\": \"Aman\", \"Age\":\"14\", \"RollNumber\": \"223\", \"Marks\": \"69\", }, { \"name\": \"Vivek\", \"Age\":\"13\", \"RollNumber\": \"253\", \"Marks\": \"89\", }, ]}; var newArray = obj.Students.filter(function (el){ return el.Age >=15 && el.RollNumber <= 200 && el.Marks >= 80 ;});console.log(newArray);</script>", "e": 1351, "s": 746, "text": null }, { "code": null, "e": 1476, "s": 1351, "text": "Output: After apply filter function on array, we get the first element of array as output as it satisfy the given condition." }, { "code": null, "e": 1685, "s": 1476, "text": "Example 2: The following example shows filtering invalid entries from array. We create an array of β€œid”s and call the filter() function on the array to derive the β€œid”s whose values are non-zero and numeric. " }, { "code": null, "e": 1696, "s": 1685, "text": "Javascript" }, { "code": "<script>let array = [ { id: 3 }, { id: -1 }, { id: 0 }, { id: 15 }, { id: 12.2 }, { }, { id: null }, { id: NaN }, { id: 'undefined' }] let countInvalidEntries = 0 function filterById(obj) { if (Number.isFinite(obj.id) && obj.id !== 0) { return true } countInvalidEntries++ return false;} let arrayById = array.filter(filterById); console.log('Filtered Array with non-zero and numeric id: \\n', arrayById); console.log('Number of Invalid Entries = ', countInvalidEntries); </script>", "e": 2209, "s": 1696, "text": null }, { "code": null, "e": 2332, "s": 2209, "text": "Output: After applying filter() function on the array of size 9, we get 4 valid (non-zero and numeric) id and 5 invalid id" }, { "code": null, "e": 2348, "s": 2332, "text": "JavaScript-Misc" }, { "code": null, "e": 2355, "s": 2348, "text": "How To" }, { "code": null, "e": 2366, "s": 2355, "text": "JavaScript" }, { "code": null, "e": 2383, "s": 2366, "text": "Web Technologies" } ]
Remove minimum number of characters so that two strings become anagram
06 Jul, 2022 Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples : Input : str1 = "bcadeh" str2 = "hea" Output: 3 We need to remove b, c and d from str1. Input : str1 = "cddgk" str2 = "gcd" Output: 2 Input : str1 = "bca" str2 = "acb" Output: 0 The idea is to make character count arrays for both the strings and store frequency of each character. Now iterate the count arrays of both strings and difference in frequency of any character abs(count1[str1[i]-β€˜a’] – count2[str2[i]-β€˜a’]) in both the strings is the number of character to be removed in either string. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find minimum number of characters// to be removed to make two strings anagram.#include<bits/stdc++.h>using namespace std;const int CHARS = 26; // function to calculate minimum numbers of characters// to be removed to make two strings anagramint remAnagram(string str1, string str2){ // make hash array for both string and calculate // frequency of each character int count1[CHARS] = {0}, count2[CHARS] = {0}; // count frequency of each character in first string for (int i=0; str1[i]!='\0'; i++) count1[str1[i]-'a']++; // count frequency of each character in second string for (int i=0; str2[i]!='\0'; i++) count2[str2[i]-'a']++; // traverse count arrays to find number of characters // to be removed int result = 0; for (int i=0; i<26; i++) result += abs(count1[i] - count2[i]); return result;} // Driver program to run the caseint main(){ string str1 = "bcadeh", str2 = "hea"; cout << remAnagram(str1, str2); return 0;} // Java program to find minimum number of// characters to be removed to make two// strings anagram.import java.util.*; class GFG { // function to calculate minimum numbers // of characters to be removed to make // two strings anagram static int remAnagram(String str1, String str2) { // make hash array for both string // and calculate frequency of each // character int count1[] = new int[26]; int count2[] = new int[26]; // count frequency of each character // in first string for (int i = 0; i < str1.length() ; i++) count1[str1.charAt(i) -'a']++; // count frequency of each character // in second string for (int i = 0; i < str2.length() ; i++) count2[str2.charAt(i) -'a']++; // traverse count arrays to find // number of characters to be removed int result = 0; for (int i = 0; i < 26; i++) result += Math.abs(count1[i] - count2[i]); return result; } // Driver program to run the case public static void main(String[] args) { String str1 = "bcadeh", str2 = "hea"; System.out.println(remAnagram(str1, str2)); }}// This code is contributed by Prerna Saini # Python 3 program to find minimum# number of characters# to be removed to make two# strings anagram. CHARS = 26 # function to calculate minimum# numbers of characters# to be removed to make two# strings anagramdef remAnagram(str1, str2): # make hash array for both string # and calculate # frequency of each character count1 = [0]*CHARS count2 = [0]*CHARS # count frequency of each character # in first string i = 0 while i < len(str1): count1[ord(str1[i])-ord('a')] += 1 i += 1 # count frequency of each character # in second string i =0 while i < len(str2): count2[ord(str2[i])-ord('a')] += 1 i += 1 # traverse count arrays to find # number of characters # to be removed result = 0 for i in range(26): result += abs(count1[i] - count2[i]) return result # Driver program to run the caseif __name__ == "__main__": str1 = "bcadeh" str2 = "hea" print(remAnagram(str1, str2)) # This code is contributed by# ChitraNayal // C# program to find minimum// number of characters to be// removed to make two strings// anagram.using System; class GFG{ // function to calculate // minimum numbers of // characters to be removed // to make two strings anagram static int remAnagram(string str1, string str2) { // make hash array for both // string and calculate frequency // of each character int []count1 = new int[26]; int []count2 = new int[26]; // count frequency of each // character in first string for (int i = 0; i < str1.Length ; i++) count1[str1[i] -'a']++; // count frequency of each // character in second string for (int i = 0; i < str2.Length ; i++) count2[str2[i] -'a']++; // traverse count arrays to // find number of characters // to be removed int result = 0; for (int i = 0; i < 26; i++) result += Math.Abs(count1[i] - count2[i]); return result; } // Driver Code public static void Main() { string str1 = "bcadeh", str2 = "hea"; Console.Write(remAnagram(str1, str2)); }} // This code is contributed// by nitin mittal. <?php// PHP program to find minimum number of// characters to be removed to make two// strings anagram. // function to calculate minimum numbers// of characters to be removed to make// two strings anagramfunction remAnagram($str1, $str2){ // make hash array for both string // and calculate frequency of each // character $count1 = array(26); $count2 = array(26); // count frequency of each character // in first string for ($i = 0; $i < strlen($str1) ; $i++) $count1[$str1[$i] - 'a']++; // count frequency of each character // in second string for ($i = 0; $i < strlen($str2) ; $i++) $count2[$str2[$i] -'a']++; // traverse count arrays to find // number of characters to be removed $result = 0; for ($i = 0; $i < 26; $i++) $result += abs($count1[$i] - $count2[$i]); return $result;} // Driver Code{ $str1 = "bcadeh"; $str2 = "hea"; echo(remAnagram($str1, $str2));} // This code is contributed by Code_Mech <script>// javascript program to find minimum number of// characters to be removed to make two// strings anagram. // function to calculate minimum numbers// of characters to be removed to make// two strings anagramfunction remAnagram(str1, str2){ // make hash array for both string // and calculate frequency of each // character var count1 = Array.from({length: 26}, (_, i) => 0); var count2 = Array.from({length: 26}, (_, i) => 0); // count frequency of each character // in first string for (i = 0; i < str1.length ; i++) count1[str1.charAt(i).charCodeAt(0) -'a'.charCodeAt(0)]++; // count frequency of each character // in second string for (i = 0; i < str2.length ; i++) count2[str2.charAt(i).charCodeAt(0) -'a'.charCodeAt(0)]++; // traverse count arrays to find // number of characters to be removed var result = 0; for (i = 0; i < 26; i++) result += Math.abs(count1[i] - count2[i]); return result;} // Driver program to run the casevar str1 = "bcadeh", str2 = "hea";document.write(remAnagram(str1, str2)); // This code is contributed by Amit Katiyar</script> Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 3 Time Complexity : O(n) Auxiliary space : O(ALPHABET-SIZE) The above solution can be optimized to work with single count array. C++ Java Python3 C# PHP Javascript // C++ implementation to count number of deletions// required from two strings to create an anagram#include <bits/stdc++.h>using namespace std;const int CHARS = 26; int countDeletions(string str1, string str2){ int arr[CHARS] = {0}; for (int i = 0; i < str1.length(); i++) arr[str1[i] - 'a']++; for (int i = 0; i < str2.length(); i++) arr[str2[i] - 'a']--; long long int ans = 0; for(int i = 0; i < CHARS; i++) ans +=abs(arr[i]); return ans;} int main() { string str1 = "bcadeh", str2 = "hea"; cout << countDeletions(str1, str2); return 0;} // Java implementation to count number of deletions// required from two strings to create an anagram class GFG { final static int CHARS = 26; static int countDeletions(String str1, String str2) { int arr[] = new int[CHARS]; for (int i = 0; i < str1.length(); i++) { arr[str1.charAt(i) - 'a']++; } for (int i = 0; i < str2.length(); i++) { arr[str2.charAt(i) - 'a']--; } int ans = 0; for (int i = 0; i < CHARS; i++) { ans += Math.abs(arr[i]); } return ans; } static public void main(String[] args) { String str1 = "bcadeh", str2 = "hea"; System.out.println(countDeletions(str1, str2)); }} // This code is contributed by 29AjayKumar # Python3 program to find minimum# number of characters to be# removed to make two strings# anagram. # function to calculate minimum# numbers of characters to be# removed to make two strings anagramdef makeAnagram(a, b): buffer = [0] * 26 for char in a: buffer[ord(char) - ord('a')] += 1 for char in b: buffer[ord(char) - ord('a')] -= 1 return sum(map(abs, buffer)) # Driver Codeif __name__ == "__main__" : str1 = "bcadeh" str2 = "hea" print(makeAnagram(str1, str2)) # This code is contributed# by Raghib Ahsan // C# implementation to count number of deletions// required from two strings to create an anagramusing System;public class GFG { readonly static int CHARS = 26; static int countDeletions(String str1, String str2) { int []arr = new int[CHARS]; for (int i = 0; i < str1.Length; i++) { arr[str1[i]- 'a']++; } for (int i = 0; i < str2.Length; i++) { arr[str2[i] - 'a']--; } int ans = 0; for (int i = 0; i < CHARS; i++) { ans += Math.Abs(arr[i]); } return ans; } static public void Main() { String str1 = "bcadeh", str2 = "hea"; Console.WriteLine(countDeletions(str1, str2)); }} //This code is contributed by PrinciRaj1992 <?php// PHP implementation to count number of deletions// required from two strings to create an anagram function countDeletions($str1, $str2){ $CHARS = 26; $arr = array(); for ($i = 0; $i < strlen($str1); $i++) { $arr[ord($str1[$i]) - ord('a')]++; } for ($i = 0; $i < strlen($str2); $i++) { $arr[ord($str2[$i]) - ord('a')]--; } $ans = 0; for ($i = 0; $i < $CHARS; $i++) { $ans += abs($arr[$i]); } return $ans;} // Driver Code$str1 = "bcadeh"; $str2 = "hea";echo(countDeletions($str1, $str2)); // This code is contributed by Code_Mech?> <script> // Javascript implementation to count// number of deletions required from// two strings to create an anagramCHARS = 26; function countDeletions(str1, str2){ var arr = Array.from({length: CHARS}, (_, i) => 0); for(i = 0; i < str1.length; i++) { arr[str1.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0)]++; } for(i = 0; i < str2.length; i++) { arr[str2.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0)]--; } var ans = 0; for(i = 0; i < CHARS; i++) { ans += Math.abs(arr[i]); } return ans;} // Driver codestr1 = "bcadeh", str2 = "hea"; document.write(countDeletions(str1, str2)); // This code is contributed by Rajput-Ji </script> 3 Thanks to vishal9619 for suggesting this optimized solution. This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal Raghib Ahsan ukasp 29AjayKumar princiraj1992 Code_Mech shubham_singh Rajput-Ji amit143katiyar hardikkoriintern Amazon anagram Strings Amazon Strings anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 355, "s": 52, "text": "Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. " }, { "code": null, "e": 368, "s": 355, "text": "Examples : " }, { "code": null, "e": 547, "s": 368, "text": "Input : str1 = \"bcadeh\" str2 = \"hea\"\nOutput: 3\nWe need to remove b, c and d from str1.\n\nInput : str1 = \"cddgk\" str2 = \"gcd\"\nOutput: 2\n\nInput : str1 = \"bca\" str2 = \"acb\"\nOutput: 0" }, { "code": null, "e": 868, "s": 547, "text": "The idea is to make character count arrays for both the strings and store frequency of each character. Now iterate the count arrays of both strings and difference in frequency of any character abs(count1[str1[i]-β€˜a’] – count2[str2[i]-β€˜a’]) in both the strings is the number of character to be removed in either string. " }, { "code": null, "e": 884, "s": 868, "text": "Implementation:" }, { "code": null, "e": 888, "s": 884, "text": "C++" }, { "code": null, "e": 893, "s": 888, "text": "Java" }, { "code": null, "e": 901, "s": 893, "text": "Python3" }, { "code": null, "e": 904, "s": 901, "text": "C#" }, { "code": null, "e": 908, "s": 904, "text": "PHP" }, { "code": null, "e": 919, "s": 908, "text": "Javascript" }, { "code": "// C++ program to find minimum number of characters// to be removed to make two strings anagram.#include<bits/stdc++.h>using namespace std;const int CHARS = 26; // function to calculate minimum numbers of characters// to be removed to make two strings anagramint remAnagram(string str1, string str2){ // make hash array for both string and calculate // frequency of each character int count1[CHARS] = {0}, count2[CHARS] = {0}; // count frequency of each character in first string for (int i=0; str1[i]!='\\0'; i++) count1[str1[i]-'a']++; // count frequency of each character in second string for (int i=0; str2[i]!='\\0'; i++) count2[str2[i]-'a']++; // traverse count arrays to find number of characters // to be removed int result = 0; for (int i=0; i<26; i++) result += abs(count1[i] - count2[i]); return result;} // Driver program to run the caseint main(){ string str1 = \"bcadeh\", str2 = \"hea\"; cout << remAnagram(str1, str2); return 0;}", "e": 1928, "s": 919, "text": null }, { "code": "// Java program to find minimum number of// characters to be removed to make two// strings anagram.import java.util.*; class GFG { // function to calculate minimum numbers // of characters to be removed to make // two strings anagram static int remAnagram(String str1, String str2) { // make hash array for both string // and calculate frequency of each // character int count1[] = new int[26]; int count2[] = new int[26]; // count frequency of each character // in first string for (int i = 0; i < str1.length() ; i++) count1[str1.charAt(i) -'a']++; // count frequency of each character // in second string for (int i = 0; i < str2.length() ; i++) count2[str2.charAt(i) -'a']++; // traverse count arrays to find // number of characters to be removed int result = 0; for (int i = 0; i < 26; i++) result += Math.abs(count1[i] - count2[i]); return result; } // Driver program to run the case public static void main(String[] args) { String str1 = \"bcadeh\", str2 = \"hea\"; System.out.println(remAnagram(str1, str2)); }}// This code is contributed by Prerna Saini", "e": 3215, "s": 1928, "text": null }, { "code": "# Python 3 program to find minimum# number of characters# to be removed to make two# strings anagram. CHARS = 26 # function to calculate minimum# numbers of characters# to be removed to make two# strings anagramdef remAnagram(str1, str2): # make hash array for both string # and calculate # frequency of each character count1 = [0]*CHARS count2 = [0]*CHARS # count frequency of each character # in first string i = 0 while i < len(str1): count1[ord(str1[i])-ord('a')] += 1 i += 1 # count frequency of each character # in second string i =0 while i < len(str2): count2[ord(str2[i])-ord('a')] += 1 i += 1 # traverse count arrays to find # number of characters # to be removed result = 0 for i in range(26): result += abs(count1[i] - count2[i]) return result # Driver program to run the caseif __name__ == \"__main__\": str1 = \"bcadeh\" str2 = \"hea\" print(remAnagram(str1, str2)) # This code is contributed by# ChitraNayal", "e": 4241, "s": 3215, "text": null }, { "code": "// C# program to find minimum// number of characters to be// removed to make two strings// anagram.using System; class GFG{ // function to calculate // minimum numbers of // characters to be removed // to make two strings anagram static int remAnagram(string str1, string str2) { // make hash array for both // string and calculate frequency // of each character int []count1 = new int[26]; int []count2 = new int[26]; // count frequency of each // character in first string for (int i = 0; i < str1.Length ; i++) count1[str1[i] -'a']++; // count frequency of each // character in second string for (int i = 0; i < str2.Length ; i++) count2[str2[i] -'a']++; // traverse count arrays to // find number of characters // to be removed int result = 0; for (int i = 0; i < 26; i++) result += Math.Abs(count1[i] - count2[i]); return result; } // Driver Code public static void Main() { string str1 = \"bcadeh\", str2 = \"hea\"; Console.Write(remAnagram(str1, str2)); }} // This code is contributed// by nitin mittal.", "e": 5526, "s": 4241, "text": null }, { "code": "<?php// PHP program to find minimum number of// characters to be removed to make two// strings anagram. // function to calculate minimum numbers// of characters to be removed to make// two strings anagramfunction remAnagram($str1, $str2){ // make hash array for both string // and calculate frequency of each // character $count1 = array(26); $count2 = array(26); // count frequency of each character // in first string for ($i = 0; $i < strlen($str1) ; $i++) $count1[$str1[$i] - 'a']++; // count frequency of each character // in second string for ($i = 0; $i < strlen($str2) ; $i++) $count2[$str2[$i] -'a']++; // traverse count arrays to find // number of characters to be removed $result = 0; for ($i = 0; $i < 26; $i++) $result += abs($count1[$i] - $count2[$i]); return $result;} // Driver Code{ $str1 = \"bcadeh\"; $str2 = \"hea\"; echo(remAnagram($str1, $str2));} // This code is contributed by Code_Mech", "e": 6533, "s": 5526, "text": null }, { "code": "<script>// javascript program to find minimum number of// characters to be removed to make two// strings anagram. // function to calculate minimum numbers// of characters to be removed to make// two strings anagramfunction remAnagram(str1, str2){ // make hash array for both string // and calculate frequency of each // character var count1 = Array.from({length: 26}, (_, i) => 0); var count2 = Array.from({length: 26}, (_, i) => 0); // count frequency of each character // in first string for (i = 0; i < str1.length ; i++) count1[str1.charAt(i).charCodeAt(0) -'a'.charCodeAt(0)]++; // count frequency of each character // in second string for (i = 0; i < str2.length ; i++) count2[str2.charAt(i).charCodeAt(0) -'a'.charCodeAt(0)]++; // traverse count arrays to find // number of characters to be removed var result = 0; for (i = 0; i < 26; i++) result += Math.abs(count1[i] - count2[i]); return result;} // Driver program to run the casevar str1 = \"bcadeh\", str2 = \"hea\";document.write(remAnagram(str1, str2)); // This code is contributed by Amit Katiyar</script>", "e": 7697, "s": 6533, "text": null }, { "code": null, "e": 7706, "s": 7697, "text": "Chapters" }, { "code": null, "e": 7733, "s": 7706, "text": "descriptions off, selected" }, { "code": null, "e": 7783, "s": 7733, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 7806, "s": 7783, "text": "captions off, selected" }, { "code": null, "e": 7814, "s": 7806, "text": "English" }, { "code": null, "e": 7838, "s": 7814, "text": "This is a modal window." }, { "code": null, "e": 7907, "s": 7838, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 7929, "s": 7907, "text": "End of dialog window." }, { "code": null, "e": 7931, "s": 7929, "text": "3" }, { "code": null, "e": 7989, "s": 7931, "text": "Time Complexity : O(n) Auxiliary space : O(ALPHABET-SIZE)" }, { "code": null, "e": 8060, "s": 7989, "text": "The above solution can be optimized to work with single count array. " }, { "code": null, "e": 8064, "s": 8060, "text": "C++" }, { "code": null, "e": 8069, "s": 8064, "text": "Java" }, { "code": null, "e": 8077, "s": 8069, "text": "Python3" }, { "code": null, "e": 8080, "s": 8077, "text": "C#" }, { "code": null, "e": 8084, "s": 8080, "text": "PHP" }, { "code": null, "e": 8095, "s": 8084, "text": "Javascript" }, { "code": "// C++ implementation to count number of deletions// required from two strings to create an anagram#include <bits/stdc++.h>using namespace std;const int CHARS = 26; int countDeletions(string str1, string str2){ int arr[CHARS] = {0}; for (int i = 0; i < str1.length(); i++) arr[str1[i] - 'a']++; for (int i = 0; i < str2.length(); i++) arr[str2[i] - 'a']--; long long int ans = 0; for(int i = 0; i < CHARS; i++) ans +=abs(arr[i]); return ans;} int main() { string str1 = \"bcadeh\", str2 = \"hea\"; cout << countDeletions(str1, str2); return 0;}", "e": 8694, "s": 8095, "text": null }, { "code": "// Java implementation to count number of deletions// required from two strings to create an anagram class GFG { final static int CHARS = 26; static int countDeletions(String str1, String str2) { int arr[] = new int[CHARS]; for (int i = 0; i < str1.length(); i++) { arr[str1.charAt(i) - 'a']++; } for (int i = 0; i < str2.length(); i++) { arr[str2.charAt(i) - 'a']--; } int ans = 0; for (int i = 0; i < CHARS; i++) { ans += Math.abs(arr[i]); } return ans; } static public void main(String[] args) { String str1 = \"bcadeh\", str2 = \"hea\"; System.out.println(countDeletions(str1, str2)); }} // This code is contributed by 29AjayKumar", "e": 9455, "s": 8694, "text": null }, { "code": "# Python3 program to find minimum# number of characters to be# removed to make two strings# anagram. # function to calculate minimum# numbers of characters to be# removed to make two strings anagramdef makeAnagram(a, b): buffer = [0] * 26 for char in a: buffer[ord(char) - ord('a')] += 1 for char in b: buffer[ord(char) - ord('a')] -= 1 return sum(map(abs, buffer)) # Driver Codeif __name__ == \"__main__\" : str1 = \"bcadeh\" str2 = \"hea\" print(makeAnagram(str1, str2)) # This code is contributed# by Raghib Ahsan", "e": 10006, "s": 9455, "text": null }, { "code": " // C# implementation to count number of deletions// required from two strings to create an anagramusing System;public class GFG { readonly static int CHARS = 26; static int countDeletions(String str1, String str2) { int []arr = new int[CHARS]; for (int i = 0; i < str1.Length; i++) { arr[str1[i]- 'a']++; } for (int i = 0; i < str2.Length; i++) { arr[str2[i] - 'a']--; } int ans = 0; for (int i = 0; i < CHARS; i++) { ans += Math.Abs(arr[i]); } return ans; } static public void Main() { String str1 = \"bcadeh\", str2 = \"hea\"; Console.WriteLine(countDeletions(str1, str2)); }} //This code is contributed by PrinciRaj1992", "e": 10766, "s": 10006, "text": null }, { "code": "<?php// PHP implementation to count number of deletions// required from two strings to create an anagram function countDeletions($str1, $str2){ $CHARS = 26; $arr = array(); for ($i = 0; $i < strlen($str1); $i++) { $arr[ord($str1[$i]) - ord('a')]++; } for ($i = 0; $i < strlen($str2); $i++) { $arr[ord($str2[$i]) - ord('a')]--; } $ans = 0; for ($i = 0; $i < $CHARS; $i++) { $ans += abs($arr[$i]); } return $ans;} // Driver Code$str1 = \"bcadeh\"; $str2 = \"hea\";echo(countDeletions($str1, $str2)); // This code is contributed by Code_Mech?>", "e": 11365, "s": 10766, "text": null }, { "code": "<script> // Javascript implementation to count// number of deletions required from// two strings to create an anagramCHARS = 26; function countDeletions(str1, str2){ var arr = Array.from({length: CHARS}, (_, i) => 0); for(i = 0; i < str1.length; i++) { arr[str1.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0)]++; } for(i = 0; i < str2.length; i++) { arr[str2.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0)]--; } var ans = 0; for(i = 0; i < CHARS; i++) { ans += Math.abs(arr[i]); } return ans;} // Driver codestr1 = \"bcadeh\", str2 = \"hea\"; document.write(countDeletions(str1, str2)); // This code is contributed by Rajput-Ji </script>", "e": 12101, "s": 11365, "text": null }, { "code": null, "e": 12103, "s": 12101, "text": "3" }, { "code": null, "e": 12164, "s": 12103, "text": "Thanks to vishal9619 for suggesting this optimized solution." }, { "code": null, "e": 12474, "s": 12164, "text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 12487, "s": 12474, "text": "nitin mittal" }, { "code": null, "e": 12500, "s": 12487, "text": "Raghib Ahsan" }, { "code": null, "e": 12506, "s": 12500, "text": "ukasp" }, { "code": null, "e": 12518, "s": 12506, "text": "29AjayKumar" }, { "code": null, "e": 12532, "s": 12518, "text": "princiraj1992" }, { "code": null, "e": 12542, "s": 12532, "text": "Code_Mech" }, { "code": null, "e": 12556, "s": 12542, "text": "shubham_singh" }, { "code": null, "e": 12566, "s": 12556, "text": "Rajput-Ji" }, { "code": null, "e": 12581, "s": 12566, "text": "amit143katiyar" }, { "code": null, "e": 12598, "s": 12581, "text": "hardikkoriintern" }, { "code": null, "e": 12605, "s": 12598, "text": "Amazon" }, { "code": null, "e": 12613, "s": 12605, "text": "anagram" }, { "code": null, "e": 12621, "s": 12613, "text": "Strings" }, { "code": null, "e": 12628, "s": 12621, "text": "Amazon" }, { "code": null, "e": 12636, "s": 12628, "text": "Strings" }, { "code": null, "e": 12644, "s": 12636, "text": "anagram" } ]
Sending email through Java with SSL / TLS authentication
22 Jul, 2021 The JavaMail API defines classes that represent the components of a mail system. JavaMail does not implement an email server, instead, it allows you to access an email server using a Java API. In order to test the code presented, you must have access to an email server. While the JavaMail API specification does not mandate support for specific protocols, JavaMail typically includes support for POP3, IMAP, and SMTP. How does Email Work? Prerequisite: Have access to an SMTP server. You must know the hostname, port number, and security settings for your SMTP server. Webmail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your username is often your full email address and not just the name that comes before the @ symbol. A Java EE IDE and Application Servers such as GlassFish or Oracle WebLogic Server. JavaMail can be downloaded as a library in a Java SE application but this tutorial assumes the use of a Java EE application server which would already include JavaMail. There are the following three steps to send email using JavaMail. They are as follows: Get the session object – javax.mail.Session class provides object of session, Session.getDefaultInstance() method and Session.getInstance() method. // Setup mail server properties.setProperty("mail.smtp.host", host); // mail username and password properties.setProperty("mail.user", "user"); properties.setProperty("mail.password", "password$$"); Compose the message– javax.mail.Transport class provides method to send the message. // javax.mail.internet.MimeMessage class is // mostly used for abstraction. MimeMessage message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("subject"); message.setText("Hello, aas is sending email "); Send the message Transport.send(message); Following is the Send Mail in Java using SMTP without authentication full implementation in java- Java import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendEmail { public static void main(String[] args) { // change below lines accordingly String to = "got@gmail.com"; String from = "akash@gmail.com"; String host = "localhost"; // or IP address // Get the session object // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object Session session = Session.getDefaultInstance(properties); // compose the message try { // javax.mail.internet.MimeMessage class // is mostly used for abstraction. MimeMessage message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("subject"); message.setText("Hello, aas is sending email "); // Send message Transport.send(message); System.out.println("Yo it has been sent.."); } catch (MessagingException mex) { mex.printStackTrace(); } }} Output Yo it has been sent... The program is simple to understand and works well, but in real life, most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So, we will now see how to create a Session object for these authentication protocols. For TLS & SSL you can know the port in which the mail server running those services. We will provide you code taking Gmail into consideration. Following is the Send Mail in Java using SMTP with TLS authentication full implementation in java- Java import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendMail { public static void main(String[] args) { // change accordingly final String username = "username@gmail.com"; // change accordingly final String password = "password"; // or IP address final String host = "localhost"; // Get system properties Properties props = new Properties(); // enable authentication props.put("mail.smtp.auth", "true"); // enable STARTTLS props.put("mail.smtp.starttls.enable", "true"); // Setup mail server props.put("mail.smtp.host", "smtp.gmail.com"); // TLS Port props.put("mail.smtp.port", "587"); // creating Session instance referenced to // Authenticator object to pass in // Session.getInstance argument Session session = Session.getInstance(props, new javax.mail.Authenticator() { //override the getPasswordAuthentication method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // compose the message // javax.mail.internet.MimeMessage class is // mostly used for abstraction. Message message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress("from-email@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to-email@gmail.com")); message.setSubject("hello"); message.setText("Yo it has been sent"); Transport.send(message); //send Message System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } }} Following is the Send Mail in Java using SMTP with SSL authentication full implementation in java- Java import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendEmail {public static void main(String[] args) { // change accordingly String to = "got@gmail.com"; // change accordingly String from = "akash@gmail.com"; // or IP address String host = "localhost"; // mail id final String username = "username@gmail.com" // correct password for gmail id final String password = "mypassword"; System.out.println("TLSEmail Start"); // Get the session object // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // SSL Port properties.put("mail.smtp.port", "465"); // enable authentication properties.put("mail.smtp.auth", "true"); // SSL Factory properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // creating Session instance referenced to // Authenticator object to pass in // Session.getInstance argument Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { // override the getPasswordAuthentication // method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password"); } });} //compose the messagetry { // javax.mail.internet.MimeMessage class is mostly // used for abstraction. MimeMessage message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("subject"); message.setText("Hello, aas is sending email "); // Send message Transport.send(message); System.out.println("Yo it has been sent..");}catch (MessagingException mex) { mex.printStackTrace();}}} Multiple clients we can have the following changes in the above code Java // This is an array of e-mail ID. You would// need to use InternetAddress() method// while specifying email IDsvoid addRecipients(Message.RecipientType type, Address[] addresses) 1twai4lin0mmv4jnz005gz9c2i76cq79ix6dz0og Anshul_Aggarwal Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jul, 2021" }, { "code": null, "e": 473, "s": 53, "text": "The JavaMail API defines classes that represent the components of a mail system. JavaMail does not implement an email server, instead, it allows you to access an email server using a Java API. In order to test the code presented, you must have access to an email server. While the JavaMail API specification does not mandate support for specific protocols, JavaMail typically includes support for POP3, IMAP, and SMTP. " }, { "code": null, "e": 494, "s": 473, "text": "How does Email Work?" }, { "code": null, "e": 510, "s": 494, "text": "Prerequisite: " }, { "code": null, "e": 854, "s": 510, "text": "Have access to an SMTP server. You must know the hostname, port number, and security settings for your SMTP server. Webmail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your username is often your full email address and not just the name that comes before the @ symbol. " }, { "code": null, "e": 1106, "s": 854, "text": "A Java EE IDE and Application Servers such as GlassFish or Oracle WebLogic Server. JavaMail can be downloaded as a library in a Java SE application but this tutorial assumes the use of a Java EE application server which would already include JavaMail." }, { "code": null, "e": 1195, "s": 1106, "text": "There are the following three steps to send email using JavaMail. They are as follows: " }, { "code": null, "e": 1344, "s": 1195, "text": "Get the session object – javax.mail.Session class provides object of session, Session.getDefaultInstance() method and Session.getInstance() method. " }, { "code": null, "e": 1578, "s": 1344, "text": "// Setup mail server\nproperties.setProperty(\"mail.smtp.host\", host); \n\n// mail username and password \nproperties.setProperty(\"mail.user\", \"user\"); \nproperties.setProperty(\"mail.password\", \"password$$\"); " }, { "code": null, "e": 1665, "s": 1578, "text": "Compose the message– javax.mail.Transport class provides method to send the message. " }, { "code": null, "e": 2050, "s": 1665, "text": "// javax.mail.internet.MimeMessage class is\n// mostly used for abstraction. \nMimeMessage message = new MimeMessage(session);\n\n// header field of the header. \nmessage.setFrom(new InternetAddress(from)); \nmessage.addRecipient(Message.RecipientType.TO, \n new InternetAddress(to)); \nmessage.setSubject(\"subject\"); \nmessage.setText(\"Hello, aas is sending email \"); " }, { "code": null, "e": 2067, "s": 2050, "text": "Send the message" }, { "code": null, "e": 2092, "s": 2067, "text": "Transport.send(message);" }, { "code": null, "e": 2191, "s": 2092, "text": "Following is the Send Mail in Java using SMTP without authentication full implementation in java- " }, { "code": null, "e": 2196, "s": 2191, "text": "Java" }, { "code": "import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendEmail { public static void main(String[] args) { // change below lines accordingly String to = \"got@gmail.com\"; String from = \"akash@gmail.com\"; String host = \"localhost\"; // or IP address // Get the session object // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(\"mail.smtp.host\", host); // Get the default Session object Session session = Session.getDefaultInstance(properties); // compose the message try { // javax.mail.internet.MimeMessage class // is mostly used for abstraction. MimeMessage message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(\"subject\"); message.setText(\"Hello, aas is sending email \"); // Send message Transport.send(message); System.out.println(\"Yo it has been sent..\"); } catch (MessagingException mex) { mex.printStackTrace(); } }}", "e": 3583, "s": 2196, "text": null }, { "code": null, "e": 3592, "s": 3583, "text": "Output " }, { "code": null, "e": 3615, "s": 3592, "text": "Yo it has been sent..." }, { "code": null, "e": 4108, "s": 3615, "text": "The program is simple to understand and works well, but in real life, most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So, we will now see how to create a Session object for these authentication protocols. For TLS & SSL you can know the port in which the mail server running those services. We will provide you code taking Gmail into consideration. Following is the Send Mail in Java using SMTP with TLS authentication full implementation in java- " }, { "code": null, "e": 4113, "s": 4108, "text": "Java" }, { "code": "import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendMail { public static void main(String[] args) { // change accordingly final String username = \"username@gmail.com\"; // change accordingly final String password = \"password\"; // or IP address final String host = \"localhost\"; // Get system properties Properties props = new Properties(); // enable authentication props.put(\"mail.smtp.auth\", \"true\"); // enable STARTTLS props.put(\"mail.smtp.starttls.enable\", \"true\"); // Setup mail server props.put(\"mail.smtp.host\", \"smtp.gmail.com\"); // TLS Port props.put(\"mail.smtp.port\", \"587\"); // creating Session instance referenced to // Authenticator object to pass in // Session.getInstance argument Session session = Session.getInstance(props, new javax.mail.Authenticator() { //override the getPasswordAuthentication method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // compose the message // javax.mail.internet.MimeMessage class is // mostly used for abstraction. Message message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(\"from-email@gmail.com\")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(\"to-email@gmail.com\")); message.setSubject(\"hello\"); message.setText(\"Yo it has been sent\"); Transport.send(message); //send Message System.out.println(\"Done\"); } catch (MessagingException e) { throw new RuntimeException(e); } }}", "e": 6334, "s": 4113, "text": null }, { "code": null, "e": 6434, "s": 6334, "text": "Following is the Send Mail in Java using SMTP with SSL authentication full implementation in java- " }, { "code": null, "e": 6439, "s": 6434, "text": "Java" }, { "code": "import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendEmail {public static void main(String[] args) { // change accordingly String to = \"got@gmail.com\"; // change accordingly String from = \"akash@gmail.com\"; // or IP address String host = \"localhost\"; // mail id final String username = \"username@gmail.com\" // correct password for gmail id final String password = \"mypassword\"; System.out.println(\"TLSEmail Start\"); // Get the session object // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(\"mail.smtp.host\", host); // SSL Port properties.put(\"mail.smtp.port\", \"465\"); // enable authentication properties.put(\"mail.smtp.auth\", \"true\"); // SSL Factory properties.put(\"mail.smtp.socketFactory.class\", \"javax.net.ssl.SSLSocketFactory\"); // creating Session instance referenced to // Authenticator object to pass in // Session.getInstance argument Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { // override the getPasswordAuthentication // method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(\"username\", \"password\"); } });} //compose the messagetry { // javax.mail.internet.MimeMessage class is mostly // used for abstraction. MimeMessage message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(\"subject\"); message.setText(\"Hello, aas is sending email \"); // Send message Transport.send(message); System.out.println(\"Yo it has been sent..\");}catch (MessagingException mex) { mex.printStackTrace();}}}", "e": 8751, "s": 6439, "text": null }, { "code": null, "e": 8821, "s": 8751, "text": "Multiple clients we can have the following changes in the above code " }, { "code": null, "e": 8826, "s": 8821, "text": "Java" }, { "code": "// This is an array of e-mail ID. You would// need to use InternetAddress() method// while specifying email IDsvoid addRecipients(Message.RecipientType type, Address[] addresses)", "e": 9028, "s": 8826, "text": null }, { "code": null, "e": 9069, "s": 9028, "text": "1twai4lin0mmv4jnz005gz9c2i76cq79ix6dz0og" }, { "code": null, "e": 9085, "s": 9069, "text": "Anshul_Aggarwal" }, { "code": null, "e": 9090, "s": 9085, "text": "Java" }, { "code": null, "e": 9095, "s": 9090, "text": "Java" } ]
How to implement a gradient descent in Python to find a local minimum ?
18 Jan, 2022 Gradient Descent is an iterative algorithm that is used to minimize a function by finding the optimal parameters. Gradient Descent can be applied to any dimension function i.e. 1-D, 2-D, 3-D. In this article, we will be working on finding global minima for parabolic function (2-D) and will be implementing gradient descent in python to find the optimal parameters for the linear regression equation (1-D). Before diving into the implementation part, let us make sure the set of parameters required to implement the gradient descent algorithm. To implement a gradient descent algorithm, we require a cost function that needs to be minimized, the number of iterations, a learning rate to determine the step size at each iteration while moving towards the minimum, partial derivates for weight & bias to update the parameters at each iteration, and a prediction function. Till now we have seen the parameters required for gradient descent. Now let us map the parameters with the gradient descent algorithm and work on an example to better understand gradient descent. Let us consider a parabolic equation y=4x2. By looking at the equation we can identify that the parabolic function is minimum at x = 0 i.e. at x=0, y=0. Therefore x=0 is the local minima of the parabolic function y=4x2. Now let us see the algorithm for gradient descent and how we can obtain the local minima by applying gradient descent: Steps should be made in proportion to the negative of the function gradient (move away from the gradient) at the current point to find local minima. Gradient Ascent is the procedure for approaching a local maximum of a function by taking steps proportional to the positive of the gradient (moving towards the gradient). repeat until convergence { w = w - (learning_rate * (dJ/dw)) b = b - (learning_rate * (dJ/db)) } Step 1: Initializing all the necessary parameters and deriving the gradient function for the parabolic equation 4x2. The derivate of x2 is 2x, so the derivative of the parabolic equation 4x2 will be 8x. x0 = 3 (random initialization of x) learning_rate = 0.01 (to determine the step size while moving towards local minima) gradient = (Calculating the gradient function) Step 2: Let us perform 3 iterations of gradient descent: For each iteration keep on updating the value of x based on the gradient descent formula. Iteration 1: x1 = x0 - (learning_rate * gradient) x1 = 3 - (0.01 * (8 * 3)) x1 = 3 - 0.24 x1 = 2.76 Iteration 2: x2 = x1 - (learning_rate * gradient) x2 = 2.76 - (0.01 * (8 * 2.76)) x2 = 2.76 - 0.2208 x2 = 2.5392 Iteration 3: x3 = x2 - (learning_rate * gradient) x3 = 2.5392 - (0.01 * (8 * 2.5392)) x3 = 2.5392 - 0.203136 x3 = 2.3360 From the above three iterations of gradient descent, we can notice that the value of x is decreasing iteration by iteration and will slowly converge to 0 (local minima) by running the gradient descent for more iterations. Now you might have a question, for how many iterations we should run gradient descent? We can set a stopping threshold i.e. when the difference between the previous and the present value of x becomes less than the stopping threshold we stop the iterations. When it comes to the implementation of gradient descent for machine learning algorithms and deep learning algorithms we try to minimize the cost function in the algorithms using gradient descent. Now that we are clear with the gradient descent’s internal working, let us look into the python implementation of gradient descent where we will be minimizing the cost function of the linear regression algorithm and finding the best fit line. In our case the parameters are below mentioned: The prediction function for the linear regression algorithm is a linear equation given by y=wx+b. prediction_function (y) = (w * x) + b Here, x is the independent variable y is the dependent variable w is the weight associated with input variable b is the bias The cost function is used to calculate the loss based on the predictions made. In linear regression, we use mean squared error to calculate the loss. Mean Squared Error is the sum of the squared differences between the actual and predicted values. Cost Function (J) = Here, n is the number of samples Calculating the partial derivates for weight and bias using the cost function. We get: Updating the weight and bias by subtracting the multiplication of learning rates and their respective gradients. w = w - (learning_rate * (dJ/dw)) b = b - (learning_rate * (dJ/db)) Python Implementation for Gradient Descent In the implementation part, we will be writing two functions, one will be the cost functions that take the actual output and the predicted output as input and returns the loss, the second will be the actual gradient descent function which takes the independent variable, target variable as input and finds the best fit line using gradient descent algorithm. The iterations, learning_rate, and stopping threshold are the tuning parameters for the gradient descent algorithm and can be tuned by the user. In the main function, we will be initializing linearly related random data and applying the gradient descent algorithm on the data to find the best fit line. The optimal weight and bias found by using the gradient descent algorithm are later used to plot the best fit line in the main function. The iterations specify the number of times the update of parameters must be done, the stopping threshold is the minimum change of loss between two successive iterations to stop the gradient descent algorithm. Python3 # Importing Librariesimport numpy as npimport matplotlib.pyplot as plt def mean_squared_error(y_true, y_predicted): # Calculating the loss or cost cost = np.sum((y_true-y_predicted)**2) / len(y_true) return cost # Gradient Descent Function# Here iterations, learning_rate, stopping_threshold# are hyperparameters that can be tuneddef gradient_descent(x, y, iterations = 1000, learning_rate = 0.0001, stopping_threshold = 1e-6): # Initializing weight, bias, learning rate and iterations current_weight = 0.1 current_bias = 0.01 iterations = iterations learning_rate = learning_rate n = float(len(x)) costs = [] weights = [] previous_cost = None # Estimation of optimal parameters for i in range(iterations): # Making predictions y_predicted = (current_weight * x) + current_bias # Calculationg the current cost current_cost = mean_squared_error(y, y_predicted) # If the change in cost is less than or equal to # stopping_threshold we stop the gradient descent if previous_cost and abs(previous_cost-current_cost)<=stopping_threshold: break previous_cost = current_cost costs.append(current_cost) weights.append(current_weight) # Calculating the gradients weight_derivative = -(2/n) * sum(x * (y-y_predicted)) bias_derivative = -(2/n) * sum(y-y_predicted) # Updating weights and bias current_weight = current_weight - (learning_rate * weight_derivative) current_bias = current_bias - (learning_rate * bias_derivative) # Printing the parameters for each 1000th iteration print(f"Iteration {i+1}: Cost {current_cost}, Weight \ {current_weight}, Bias {current_bias}") # Visualizing the weights and cost at for all iterations plt.figure(figsize = (8,6)) plt.plot(weights, costs) plt.scatter(weights, costs, marker='o', color='red') plt.title("Cost vs Weights") plt.ylabel("Cost") plt.xlabel("Weight") plt.show() return current_weight, current_bias def main(): # Data X = np.array([32.50234527, 53.42680403, 61.53035803, 47.47563963, 59.81320787, 55.14218841, 52.21179669, 39.29956669, 48.10504169, 52.55001444, 45.41973014, 54.35163488, 44.1640495 , 58.16847072, 56.72720806, 48.95588857, 44.68719623, 60.29732685, 45.61864377, 38.81681754]) Y = np.array([31.70700585, 68.77759598, 62.5623823 , 71.54663223, 87.23092513, 78.21151827, 79.64197305, 59.17148932, 75.3312423 , 71.30087989, 55.16567715, 82.47884676, 62.00892325, 75.39287043, 81.43619216, 60.72360244, 82.89250373, 97.37989686, 48.84715332, 56.87721319]) # Estimating weight and bias using gradient descent estimated_weight, eatimated_bias = gradient_descent(X, Y, iterations=2000) print(f"Estimated Weight: {estimated_weight}\nEstimated Bias: {eatimated_bias}") # Making predictions using estimated parameters Y_pred = estimated_weight*X + eatimated_bias # Plotting the regression line plt.figure(figsize = (8,6)) plt.scatter(X, Y, marker='o', color='red') plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='blue',markerfacecolor='red', markersize=10,linestyle='dashed') plt.xlabel("X") plt.ylabel("Y") plt.show() if __name__=="__main__": main() Output: Iteration 1: Cost 4352.088931274409, Weight 0.7593291142562117, Bias 0.02288558130709 Iteration 2: Cost 1114.8561474350017, Weight 1.081602958862324, Bias 0.02918014748569513 Iteration 3: Cost 341.42912086804455, Weight 1.2391274084945083, Bias 0.03225308846928192 Iteration 4: Cost 156.64495290904443, Weight 1.3161239281746984, Bias 0.03375132986012604 Iteration 5: Cost 112.49704004742098, Weight 1.3537591652024805, Bias 0.034479873154934775 Iteration 6: Cost 101.9493925395456, Weight 1.3721549833978113, Bias 0.034832195392868505 Iteration 7: Cost 99.4293893333546, Weight 1.3811467575154601, Bias 0.03500062439068245 Iteration 8: Cost 98.82731958262897, Weight 1.3855419247507244, Bias 0.03507916814736111 Iteration 9: Cost 98.68347500997261, Weight 1.3876903144657764, Bias 0.035113776874486774 Iteration 10: Cost 98.64910780902792, Weight 1.3887405007983562, Bias 0.035126910596389935 Iteration 11: Cost 98.64089651459352, Weight 1.389253895811451, Bias 0.03512954755833985 Iteration 12: Cost 98.63893428729509, Weight 1.38950491235671, Bias 0.035127053821718185 Iteration 13: Cost 98.63846506273883, Weight 1.3896276808137857, Bias 0.035122052266051224 Iteration 14: Cost 98.63835254057648, Weight 1.38968776283053, Bias 0.03511582492978764 Iteration 15: Cost 98.63832524036214, Weight 1.3897172043139192, Bias 0.03510899846107016 Iteration 16: Cost 98.63831830104695, Weight 1.389731668997059, Bias 0.035101879159522745 Iteration 17: Cost 98.63831622628217, Weight 1.389738813163012, Bias 0.03509461674147458 Estimated Weight: 1.389738813163012 Estimated Bias: 0.03509461674147458 Cost function approaching local minima The best fit line obtained using gradient descent nnr223442 Picked Python-numpy Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Information Retrieval? Introduction to Recurrent Neural Network Support Vector Machine Algorithm Sequential Covering Algorithm ML | Expectation-Maximization Algorithm Iterate over a list in Python Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Taking input in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2022" }, { "code": null, "e": 899, "s": 28, "text": "Gradient Descent is an iterative algorithm that is used to minimize a function by finding the optimal parameters. Gradient Descent can be applied to any dimension function i.e. 1-D, 2-D, 3-D. In this article, we will be working on finding global minima for parabolic function (2-D) and will be implementing gradient descent in python to find the optimal parameters for the linear regression equation (1-D). Before diving into the implementation part, let us make sure the set of parameters required to implement the gradient descent algorithm. To implement a gradient descent algorithm, we require a cost function that needs to be minimized, the number of iterations, a learning rate to determine the step size at each iteration while moving towards the minimum, partial derivates for weight & bias to update the parameters at each iteration, and a prediction function. " }, { "code": null, "e": 1434, "s": 899, "text": "Till now we have seen the parameters required for gradient descent. Now let us map the parameters with the gradient descent algorithm and work on an example to better understand gradient descent. Let us consider a parabolic equation y=4x2. By looking at the equation we can identify that the parabolic function is minimum at x = 0 i.e. at x=0, y=0. Therefore x=0 is the local minima of the parabolic function y=4x2. Now let us see the algorithm for gradient descent and how we can obtain the local minima by applying gradient descent:" }, { "code": null, "e": 1754, "s": 1434, "text": "Steps should be made in proportion to the negative of the function gradient (move away from the gradient) at the current point to find local minima. Gradient Ascent is the procedure for approaching a local maximum of a function by taking steps proportional to the positive of the gradient (moving towards the gradient)." }, { "code": null, "e": 1859, "s": 1754, "text": "repeat until convergence\n{\n w = w - (learning_rate * (dJ/dw))\n b = b - (learning_rate * (dJ/db))\n}" }, { "code": null, "e": 2063, "s": 1859, "text": "Step 1: Initializing all the necessary parameters and deriving the gradient function for the parabolic equation 4x2. The derivate of x2 is 2x, so the derivative of the parabolic equation 4x2 will be 8x. " }, { "code": null, "e": 2099, "s": 2063, "text": "x0 = 3 (random initialization of x)" }, { "code": null, "e": 2183, "s": 2099, "text": "learning_rate = 0.01 (to determine the step size while moving towards local minima)" }, { "code": null, "e": 2231, "s": 2183, "text": "gradient = (Calculating the gradient function)" }, { "code": null, "e": 2288, "s": 2231, "text": "Step 2: Let us perform 3 iterations of gradient descent:" }, { "code": null, "e": 2378, "s": 2288, "text": "For each iteration keep on updating the value of x based on the gradient descent formula." }, { "code": null, "e": 2762, "s": 2378, "text": "Iteration 1:\n x1 = x0 - (learning_rate * gradient)\n x1 = 3 - (0.01 * (8 * 3))\n x1 = 3 - 0.24\n x1 = 2.76\n\nIteration 2:\n x2 = x1 - (learning_rate * gradient)\n x2 = 2.76 - (0.01 * (8 * 2.76))\n x2 = 2.76 - 0.2208\n x2 = 2.5392\n\nIteration 3:\n x3 = x2 - (learning_rate * gradient)\n x3 = 2.5392 - (0.01 * (8 * 2.5392))\n x3 = 2.5392 - 0.203136\n x3 = 2.3360" }, { "code": null, "e": 3071, "s": 2762, "text": "From the above three iterations of gradient descent, we can notice that the value of x is decreasing iteration by iteration and will slowly converge to 0 (local minima) by running the gradient descent for more iterations. Now you might have a question, for how many iterations we should run gradient descent?" }, { "code": null, "e": 3728, "s": 3071, "text": "We can set a stopping threshold i.e. when the difference between the previous and the present value of x becomes less than the stopping threshold we stop the iterations. When it comes to the implementation of gradient descent for machine learning algorithms and deep learning algorithms we try to minimize the cost function in the algorithms using gradient descent. Now that we are clear with the gradient descent’s internal working, let us look into the python implementation of gradient descent where we will be minimizing the cost function of the linear regression algorithm and finding the best fit line. In our case the parameters are below mentioned:" }, { "code": null, "e": 3827, "s": 3728, "text": "The prediction function for the linear regression algorithm is a linear equation given by y=wx+b. " }, { "code": null, "e": 4008, "s": 3827, "text": "prediction_function (y) = (w * x) + b\nHere, x is the independent variable\n y is the dependent variable\n w is the weight associated with input variable\n b is the bias" }, { "code": null, "e": 4256, "s": 4008, "text": "The cost function is used to calculate the loss based on the predictions made. In linear regression, we use mean squared error to calculate the loss. Mean Squared Error is the sum of the squared differences between the actual and predicted values." }, { "code": null, "e": 4277, "s": 4256, "text": "Cost Function (J) = " }, { "code": null, "e": 4310, "s": 4277, "text": "Here, n is the number of samples" }, { "code": null, "e": 4397, "s": 4310, "text": "Calculating the partial derivates for weight and bias using the cost function. We get:" }, { "code": null, "e": 4510, "s": 4397, "text": "Updating the weight and bias by subtracting the multiplication of learning rates and their respective gradients." }, { "code": null, "e": 4578, "s": 4510, "text": "w = w - (learning_rate * (dJ/dw))\nb = b - (learning_rate * (dJ/db))" }, { "code": null, "e": 4621, "s": 4578, "text": "Python Implementation for Gradient Descent" }, { "code": null, "e": 5628, "s": 4621, "text": "In the implementation part, we will be writing two functions, one will be the cost functions that take the actual output and the predicted output as input and returns the loss, the second will be the actual gradient descent function which takes the independent variable, target variable as input and finds the best fit line using gradient descent algorithm. The iterations, learning_rate, and stopping threshold are the tuning parameters for the gradient descent algorithm and can be tuned by the user. In the main function, we will be initializing linearly related random data and applying the gradient descent algorithm on the data to find the best fit line. The optimal weight and bias found by using the gradient descent algorithm are later used to plot the best fit line in the main function. The iterations specify the number of times the update of parameters must be done, the stopping threshold is the minimum change of loss between two successive iterations to stop the gradient descent algorithm." }, { "code": null, "e": 5636, "s": 5628, "text": "Python3" }, { "code": "# Importing Librariesimport numpy as npimport matplotlib.pyplot as plt def mean_squared_error(y_true, y_predicted): # Calculating the loss or cost cost = np.sum((y_true-y_predicted)**2) / len(y_true) return cost # Gradient Descent Function# Here iterations, learning_rate, stopping_threshold# are hyperparameters that can be tuneddef gradient_descent(x, y, iterations = 1000, learning_rate = 0.0001, stopping_threshold = 1e-6): # Initializing weight, bias, learning rate and iterations current_weight = 0.1 current_bias = 0.01 iterations = iterations learning_rate = learning_rate n = float(len(x)) costs = [] weights = [] previous_cost = None # Estimation of optimal parameters for i in range(iterations): # Making predictions y_predicted = (current_weight * x) + current_bias # Calculationg the current cost current_cost = mean_squared_error(y, y_predicted) # If the change in cost is less than or equal to # stopping_threshold we stop the gradient descent if previous_cost and abs(previous_cost-current_cost)<=stopping_threshold: break previous_cost = current_cost costs.append(current_cost) weights.append(current_weight) # Calculating the gradients weight_derivative = -(2/n) * sum(x * (y-y_predicted)) bias_derivative = -(2/n) * sum(y-y_predicted) # Updating weights and bias current_weight = current_weight - (learning_rate * weight_derivative) current_bias = current_bias - (learning_rate * bias_derivative) # Printing the parameters for each 1000th iteration print(f\"Iteration {i+1}: Cost {current_cost}, Weight \\ {current_weight}, Bias {current_bias}\") # Visualizing the weights and cost at for all iterations plt.figure(figsize = (8,6)) plt.plot(weights, costs) plt.scatter(weights, costs, marker='o', color='red') plt.title(\"Cost vs Weights\") plt.ylabel(\"Cost\") plt.xlabel(\"Weight\") plt.show() return current_weight, current_bias def main(): # Data X = np.array([32.50234527, 53.42680403, 61.53035803, 47.47563963, 59.81320787, 55.14218841, 52.21179669, 39.29956669, 48.10504169, 52.55001444, 45.41973014, 54.35163488, 44.1640495 , 58.16847072, 56.72720806, 48.95588857, 44.68719623, 60.29732685, 45.61864377, 38.81681754]) Y = np.array([31.70700585, 68.77759598, 62.5623823 , 71.54663223, 87.23092513, 78.21151827, 79.64197305, 59.17148932, 75.3312423 , 71.30087989, 55.16567715, 82.47884676, 62.00892325, 75.39287043, 81.43619216, 60.72360244, 82.89250373, 97.37989686, 48.84715332, 56.87721319]) # Estimating weight and bias using gradient descent estimated_weight, eatimated_bias = gradient_descent(X, Y, iterations=2000) print(f\"Estimated Weight: {estimated_weight}\\nEstimated Bias: {eatimated_bias}\") # Making predictions using estimated parameters Y_pred = estimated_weight*X + eatimated_bias # Plotting the regression line plt.figure(figsize = (8,6)) plt.scatter(X, Y, marker='o', color='red') plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='blue',markerfacecolor='red', markersize=10,linestyle='dashed') plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.show() if __name__==\"__main__\": main()", "e": 9116, "s": 5636, "text": null }, { "code": null, "e": 9128, "s": 9120, "text": "Output:" }, { "code": null, "e": 9216, "s": 9130, "text": "Iteration 1: Cost 4352.088931274409, Weight 0.7593291142562117, Bias 0.02288558130709" }, { "code": null, "e": 9307, "s": 9216, "text": "Iteration 2: Cost 1114.8561474350017, Weight 1.081602958862324, Bias 0.02918014748569513 " }, { "code": null, "e": 9398, "s": 9307, "text": "Iteration 3: Cost 341.42912086804455, Weight 1.2391274084945083, Bias 0.03225308846928192 " }, { "code": null, "e": 9489, "s": 9398, "text": "Iteration 4: Cost 156.64495290904443, Weight 1.3161239281746984, Bias 0.03375132986012604 " }, { "code": null, "e": 9580, "s": 9489, "text": "Iteration 5: Cost 112.49704004742098, Weight 1.3537591652024805, Bias 0.034479873154934775" }, { "code": null, "e": 9671, "s": 9580, "text": "Iteration 6: Cost 101.9493925395456, Weight 1.3721549833978113, Bias 0.034832195392868505 " }, { "code": null, "e": 9762, "s": 9671, "text": "Iteration 7: Cost 99.4293893333546, Weight 1.3811467575154601, Bias 0.03500062439068245 " }, { "code": null, "e": 9853, "s": 9762, "text": "Iteration 8: Cost 98.82731958262897, Weight 1.3855419247507244, Bias 0.03507916814736111 " }, { "code": null, "e": 9944, "s": 9853, "text": "Iteration 9: Cost 98.68347500997261, Weight 1.3876903144657764, Bias 0.035113776874486774 " }, { "code": null, "e": 10035, "s": 9944, "text": "Iteration 10: Cost 98.64910780902792, Weight 1.3887405007983562, Bias 0.035126910596389935" }, { "code": null, "e": 10126, "s": 10035, "text": "Iteration 11: Cost 98.64089651459352, Weight 1.389253895811451, Bias 0.03512954755833985 " }, { "code": null, "e": 10217, "s": 10126, "text": "Iteration 12: Cost 98.63893428729509, Weight 1.38950491235671, Bias 0.035127053821718185 " }, { "code": null, "e": 10308, "s": 10217, "text": "Iteration 13: Cost 98.63846506273883, Weight 1.3896276808137857, Bias 0.035122052266051224" }, { "code": null, "e": 10399, "s": 10308, "text": "Iteration 14: Cost 98.63835254057648, Weight 1.38968776283053, Bias 0.03511582492978764 " }, { "code": null, "e": 10490, "s": 10399, "text": "Iteration 15: Cost 98.63832524036214, Weight 1.3897172043139192, Bias 0.03510899846107016 " }, { "code": null, "e": 10581, "s": 10490, "text": "Iteration 16: Cost 98.63831830104695, Weight 1.389731668997059, Bias 0.035101879159522745 " }, { "code": null, "e": 10672, "s": 10581, "text": "Iteration 17: Cost 98.63831622628217, Weight 1.389738813163012, Bias 0.03509461674147458 " }, { "code": null, "e": 10708, "s": 10672, "text": "Estimated Weight: 1.389738813163012" }, { "code": null, "e": 10744, "s": 10708, "text": "Estimated Bias: 0.03509461674147458" }, { "code": null, "e": 10783, "s": 10744, "text": "Cost function approaching local minima" }, { "code": null, "e": 10833, "s": 10783, "text": "The best fit line obtained using gradient descent" }, { "code": null, "e": 10845, "s": 10835, "text": "nnr223442" }, { "code": null, "e": 10852, "s": 10845, "text": "Picked" }, { "code": null, "e": 10865, "s": 10852, "text": "Python-numpy" }, { "code": null, "e": 10882, "s": 10865, "text": "Machine Learning" }, { "code": null, "e": 10889, "s": 10882, "text": "Python" }, { "code": null, "e": 10906, "s": 10889, "text": "Machine Learning" }, { "code": null, "e": 11004, "s": 10906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11035, "s": 11004, "text": "What is Information Retrieval?" }, { "code": null, "e": 11076, "s": 11035, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 11109, "s": 11076, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 11139, "s": 11109, "text": "Sequential Covering Algorithm" }, { "code": null, "e": 11179, "s": 11139, "text": "ML | Expectation-Maximization Algorithm" }, { "code": null, "e": 11209, "s": 11179, "text": "Iterate over a list in Python" }, { "code": null, "e": 11237, "s": 11209, "text": "Read JSON file using Python" }, { "code": null, "e": 11259, "s": 11237, "text": "Python map() function" }, { "code": null, "e": 11309, "s": 11259, "text": "Adding new column to existing DataFrame in Pandas" } ]
Python – Itertools.islice()
27 Feb, 2020 In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is islice(). Note: For more information, refer to Python Itertools This iterator selectively prints the values mentioned in its iterable container passed as an argument. Syntax: islice(iterable, start, stop, step) Example 1: # Python program to demonstrate# the working of islice from itertools import islice # Slicing the range functionfor i in islice(range(20), 5): print(i) li = [2, 4, 5, 7, 8, 10, 20] # Slicing the listprint(list(itertools.islice(li, 1, 6, 2))) Output: 0 1 2 3 4 [4, 7, 10] Example 2: from itertools import islice for i in islice(range(20), 1, 5): print(i) Output: 1 2 3 4 Here we have provide the three-parameter that is range(), 1 and 5. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value. Example 3: from itertools import islice for i in islice(range(20), 1, 5, 2): print(i) Output: 1 3 Here we provide the four-parameter that is range() as iterable, 1, 5 and 2 as stop value. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value and 2 will be considered as step value of how many steps to skip while iterating values. Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n27 Feb, 2020" }, { "code": null, "e": 275, "s": 53, "text": "In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is islice()." }, { "code": null, "e": 329, "s": 275, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 432, "s": 329, "text": "This iterator selectively prints the values mentioned in its iterable container passed as an argument." }, { "code": null, "e": 440, "s": 432, "text": "Syntax:" }, { "code": null, "e": 477, "s": 440, "text": "islice(iterable, start, stop, step)\n" }, { "code": null, "e": 488, "s": 477, "text": "Example 1:" }, { "code": "# Python program to demonstrate# the working of islice from itertools import islice # Slicing the range functionfor i in islice(range(20), 5): print(i) li = [2, 4, 5, 7, 8, 10, 20] # Slicing the listprint(list(itertools.islice(li, 1, 6, 2))) ", "e": 753, "s": 488, "text": null }, { "code": null, "e": 761, "s": 753, "text": "Output:" }, { "code": null, "e": 783, "s": 761, "text": "0\n1\n2\n3\n4\n[4, 7, 10]\n" }, { "code": null, "e": 794, "s": 783, "text": "Example 2:" }, { "code": "from itertools import islice for i in islice(range(20), 1, 5): print(i)", "e": 873, "s": 794, "text": null }, { "code": null, "e": 881, "s": 873, "text": "Output:" }, { "code": null, "e": 890, "s": 881, "text": "1\n2\n3\n4\n" }, { "code": null, "e": 1103, "s": 890, "text": "Here we have provide the three-parameter that is range(), 1 and 5. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value." }, { "code": null, "e": 1114, "s": 1103, "text": "Example 3:" }, { "code": "from itertools import islice for i in islice(range(20), 1, 5, 2): print(i)", "e": 1195, "s": 1114, "text": null }, { "code": null, "e": 1203, "s": 1195, "text": "Output:" }, { "code": null, "e": 1208, "s": 1203, "text": "1\n3\n" }, { "code": null, "e": 1532, "s": 1208, "text": "Here we provide the four-parameter that is range() as iterable, 1, 5 and 2 as stop value. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value and 2 will be considered as step value of how many steps to skip while iterating values." }, { "code": null, "e": 1549, "s": 1532, "text": "Python-itertools" }, { "code": null, "e": 1556, "s": 1549, "text": "Python" }, { "code": null, "e": 1654, "s": 1556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1672, "s": 1654, "text": "Python Dictionary" }, { "code": null, "e": 1714, "s": 1672, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1749, "s": 1714, "text": "Read a file line by line in Python" }, { "code": null, "e": 1775, "s": 1749, "text": "Python String | replace()" }, { "code": null, "e": 1807, "s": 1775, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1836, "s": 1807, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1863, "s": 1836, "text": "Python Classes and Objects" }, { "code": null, "e": 1893, "s": 1863, "text": "Iterate over a list in Python" }, { "code": null, "e": 1914, "s": 1893, "text": "Python OOPs Concepts" } ]
Hello World in Scala
11 Feb, 2019 The Hello World! the program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In Scala, a basic program consists of the following: object Main Method Statements or Expressions Example: // Scala program to print Hello World! object Geeks { // Main Method def main(args: Array[String]) { // prints Hello World println("Hello World!") }} Output: Hello World! Explanation: object Geeks: object is the keyword which is used to create the objects. Objects are the instance of a class. Here β€œGeeks” is the name of the object. def main(args: Array[String]): def is the keyword in Scala which is used to define the function and β€œmain” is the name of Main Method. args: Array[String] are used for the command line arguments. println(β€œHello World!”): println is a method in Scala which is used to display the Output on console. To use an online Scala compiler: We can use various online IDE. which can be used to run Scala programs without installing. Using Command-Line: Make sure we have the Java 8 JDK (also known as 1.8). run javac -version in the command line and make sure we see javac 1.8.___ If we don’t have version 1.8 or higher, Install the JDK Firstly, open a text editor Notepad or Notepad++. write the code in the text editor and save the file with (.scala) extension. open the command prompt follow step by step process on your system.// Scala program to print Hello World! object Geeks { // Main Method def main(args: Array[String]) { // prints Hello World println("Hello World!") } }Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Geeks.class file and class file name is same as Object name(Here Object name is Geeks).Step 2: Now open the command with object name scala Geeks. It will give the result. // Scala program to print Hello World! object Geeks { // Main Method def main(args: Array[String]) { // prints Hello World println("Hello World!") } } Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Geeks.class file and class file name is same as Object name(Here Object name is Geeks).Step 2: Now open the command with object name scala Geeks. It will give the result. Using Scala IDE: IDE like IntelliJ IDEA, ENSIME run scala program easily. write the code in the text editor and press to run it. Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Feb, 2019" }, { "code": null, "e": 251, "s": 28, "text": "The Hello World! the program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In Scala, a basic program consists of the following:" }, { "code": null, "e": 258, "s": 251, "text": "object" }, { "code": null, "e": 270, "s": 258, "text": "Main Method" }, { "code": null, "e": 296, "s": 270, "text": "Statements or Expressions" }, { "code": null, "e": 305, "s": 296, "text": "Example:" }, { "code": "// Scala program to print Hello World! object Geeks { // Main Method def main(args: Array[String]) { // prints Hello World println(\"Hello World!\") }}", "e": 484, "s": 305, "text": null }, { "code": null, "e": 492, "s": 484, "text": "Output:" }, { "code": null, "e": 505, "s": 492, "text": "Hello World!" }, { "code": null, "e": 518, "s": 505, "text": "Explanation:" }, { "code": null, "e": 668, "s": 518, "text": "object Geeks: object is the keyword which is used to create the objects. Objects are the instance of a class. Here β€œGeeks” is the name of the object." }, { "code": null, "e": 864, "s": 668, "text": "def main(args: Array[String]): def is the keyword in Scala which is used to define the function and β€œmain” is the name of Main Method. args: Array[String] are used for the command line arguments." }, { "code": null, "e": 966, "s": 864, "text": "println(β€œHello World!”): println is a method in Scala which is used to display the Output on console." }, { "code": null, "e": 1090, "s": 966, "text": "To use an online Scala compiler: We can use various online IDE. which can be used to run Scala programs without installing." }, { "code": null, "e": 1935, "s": 1090, "text": "Using Command-Line: Make sure we have the Java 8 JDK (also known as 1.8). run javac -version in the command line and make sure we see javac 1.8.___ If we don’t have version 1.8 or higher, Install the JDK Firstly, open a text editor Notepad or Notepad++. write the code in the text editor and save the file with (.scala) extension. open the command prompt follow step by step process on your system.// Scala program to print Hello World! \nobject Geeks \n{\n // Main Method \n def main(args: Array[String]) \n {\n // prints Hello World\n println(\"Hello World!\") \n }\n}Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Geeks.class file and class file name is same as Object name(Here Object name is Geeks).Step 2: Now open the command with object name scala Geeks. It will give the result." }, { "code": null, "e": 2123, "s": 1935, "text": "// Scala program to print Hello World! \nobject Geeks \n{\n // Main Method \n def main(args: Array[String]) \n {\n // prints Hello World\n println(\"Hello World!\") \n }\n}" }, { "code": null, "e": 2383, "s": 2123, "text": "Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Geeks.class file and class file name is same as Object name(Here Object name is Geeks).Step 2: Now open the command with object name scala Geeks. It will give the result." }, { "code": null, "e": 2512, "s": 2383, "text": "Using Scala IDE: IDE like IntelliJ IDEA, ENSIME run scala program easily. write the code in the text editor and press to run it." }, { "code": null, "e": 2518, "s": 2512, "text": "Scala" }, { "code": null, "e": 2531, "s": 2518, "text": "Scala-Basics" }, { "code": null, "e": 2537, "s": 2531, "text": "Scala" } ]
Getting System and Process Information Using C Programming and Shell in Linux
17 May, 2020 Whenever you start a new process in Linux it creates a file in /proc/ folder with the same name as that of the process id of the process. In that folder, there is a file named β€œstatus” which has all the details of the process. We can get those Process Information Through shell as follows: cat /proc/1/status As can be seen, it displays most of the information about the process. Note:, In this case, the process id is 1, it may be changed as per need. You can get the System Information through the shell. The basic system information is stored in a file named os-release in /etc/ folder. cat /etc/os-release You can also get the System Information using C programming. The below code is used to get the details of the system. In this code, utsname maintains a structure that has the details of the system like sysname nodename, release, version, etc. #include<stdio.h>#include<stdlib.h>#include<errno.h>#include<sys/utsname.h>int main(){ struct utsname buf1; errno =0; if(uname(&buf1)!=0) { perror("uname doesn't return 0, so there is an error"); exit(EXIT_FAILURE); } printf("System Name = %s\n", buf1.sysname); printf("Node Name = %s\n", buf1.nodename); printf("Version = %s\n", buf1.version); printf("Release = %s\n", buf1.release); printf("Machine = %s\n", buf1.machine);} On execution the above code will give the following output: To get Process Information using C programming, use the below code. In this code, we execute the Linux command through a c program to get the details of the process. #include<stdio.h>#include<stdlib.h>int main(){ int r=system("cat /proc/1/status");} On execution the above code will give the following output: C Language Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ TCP Server-Client implementation in C Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 53, "s": 25, "text": "\n17 May, 2020" }, { "code": null, "e": 343, "s": 53, "text": "Whenever you start a new process in Linux it creates a file in /proc/ folder with the same name as that of the process id of the process. In that folder, there is a file named β€œstatus” which has all the details of the process. We can get those Process Information Through shell as follows:" }, { "code": null, "e": 363, "s": 343, "text": "cat /proc/1/status\n" }, { "code": null, "e": 434, "s": 363, "text": "As can be seen, it displays most of the information about the process." }, { "code": null, "e": 507, "s": 434, "text": "Note:, In this case, the process id is 1, it may be changed as per need." }, { "code": null, "e": 644, "s": 507, "text": "You can get the System Information through the shell. The basic system information is stored in a file named os-release in /etc/ folder." }, { "code": null, "e": 665, "s": 644, "text": "cat /etc/os-release\n" }, { "code": null, "e": 908, "s": 665, "text": "You can also get the System Information using C programming. The below code is used to get the details of the system. In this code, utsname maintains a structure that has the details of the system like sysname nodename, release, version, etc." }, { "code": "#include<stdio.h>#include<stdlib.h>#include<errno.h>#include<sys/utsname.h>int main(){ struct utsname buf1; errno =0; if(uname(&buf1)!=0) { perror(\"uname doesn't return 0, so there is an error\"); exit(EXIT_FAILURE); } printf(\"System Name = %s\\n\", buf1.sysname); printf(\"Node Name = %s\\n\", buf1.nodename); printf(\"Version = %s\\n\", buf1.version); printf(\"Release = %s\\n\", buf1.release); printf(\"Machine = %s\\n\", buf1.machine);}", "e": 1364, "s": 908, "text": null }, { "code": null, "e": 1424, "s": 1364, "text": "On execution the above code will give the following output:" }, { "code": null, "e": 1590, "s": 1424, "text": "To get Process Information using C programming, use the below code. In this code, we execute the Linux command through a c program to get the details of the process." }, { "code": "#include<stdio.h>#include<stdlib.h>int main(){ int r=system(\"cat /proc/1/status\");}", "e": 1676, "s": 1590, "text": null }, { "code": null, "e": 1736, "s": 1676, "text": "On execution the above code will give the following output:" }, { "code": null, "e": 1747, "s": 1736, "text": "C Language" }, { "code": null, "e": 1758, "s": 1747, "text": "Linux-Unix" }, { "code": null, "e": 1767, "s": 1758, "text": "TechTips" }, { "code": null, "e": 1865, "s": 1767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1913, "s": 1865, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1958, "s": 1913, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 1979, "s": 1958, "text": "Operators in C / C++" }, { "code": null, "e": 2005, "s": 1979, "text": "Exception Handling in C++" }, { "code": null, "e": 2043, "s": 2005, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2083, "s": 2043, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 2123, "s": 2083, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 2150, "s": 2123, "text": "grep command in Unix/Linux" }, { "code": null, "e": 2185, "s": 2150, "text": "cut command in Linux with examples" } ]
Internal working of Set in Python
12 Apr, 2022 Sets and their working Set in Python can be defined as the collection of items. In Python, these are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion and traversal in O(1) on average. The operations on Hash Table are some what similar to Linked List. Sets in python are unordered list with duplicate elements removed. Basic Methods on Sets are:- Creating Set:- In Python, Sets are created through set() function. An Empty list is created. Note that empty Set cannot be created through {}, it creates dictionary. Checking if an item is in : Time complexity of this operation is O(1) on average. However in worst case it can become O(n). Adding elements:- Insertion in set is done through set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However in worst case it can become O(n). Union:- Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done. Intersection:- This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done. Difference:- To find difference in between sets. Similar to find difference in linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1)) Symmetric Difference:- To find element in both the sets except the common elements. ^ operator is used. Time complexity of s1^s2 is O(len(s1)) Symmetric Difference Update: Returns a new set which contains symmetric difference of two sets. Time complexity is O(len(s2)) clear:- Clears the set or Hash Table. Time complexity source : Python Wiki If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity. Set Implementation:- Sets with Numerous operations on a single HashTable:- Examples: # empty set, avoid using {} in creating set or dictionary is created x = set() # set {'e', 'h', 'l', 'o'} is created in unordered way B = set('hello') # set{'a', 'c', 'd', 'b', 'e', 'f', 'g'} is created A = set('abcdefg') # set{'a', 'b', 'h', 'c', 'd', 'e', 'f', 'g'} A.add('h') fruit ={'orange', 'banana', 'pear', 'apple'} # True fast membership testing in sets 'pear' in fruit 'mango' in fruit # False A == B # A is equivalent to B A != B # A is not equivalent to B A <= B # A is subset of B A <B>= B A > B # A is proper superset of B A | B # the union of A and B A & B # the intersection of A and B A - B # the set of elements in A but not B A Λ† B # the symmetric difference a = {x for x in A if x not in 'abc'} # Set Comprehension COMMITMENT anukoolsrivastava Picked python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Apr, 2022" }, { "code": null, "e": 499, "s": 54, "text": "Sets and their working Set in Python can be defined as the collection of items. In Python, these are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion and traversal in O(1) on average. The operations on Hash Table are some what similar to Linked List. Sets in python are unordered list with duplicate elements removed. " }, { "code": null, "e": 527, "s": 499, "text": "Basic Methods on Sets are:-" }, { "code": null, "e": 694, "s": 527, "text": "Creating Set:- In Python, Sets are created through set() function. An Empty list is created. Note that empty Set cannot be created through {}, it creates dictionary. " }, { "code": null, "e": 819, "s": 694, "text": "Checking if an item is in : Time complexity of this operation is O(1) on average. However in worst case it can become O(n). " }, { "code": null, "e": 1059, "s": 819, "text": "Adding elements:- Insertion in set is done through set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However in worst case it can become O(n). " }, { "code": null, "e": 1389, "s": 1059, "text": "Union:- Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done. " }, { "code": null, "e": 1699, "s": 1389, "text": "Intersection:- This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done. " }, { "code": null, "e": 1901, "s": 1699, "text": "Difference:- To find difference in between sets. Similar to find difference in linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1)) " }, { "code": null, "e": 2045, "s": 1901, "text": "Symmetric Difference:- To find element in both the sets except the common elements. ^ operator is used. Time complexity of s1^s2 is O(len(s1)) " }, { "code": null, "e": 2210, "s": 2045, "text": "Symmetric Difference Update: Returns a new set which contains symmetric difference of two sets. Time complexity is O(len(s2)) clear:- Clears the set or Hash Table. " }, { "code": null, "e": 2248, "s": 2210, "text": "Time complexity source : Python Wiki " }, { "code": null, "e": 2624, "s": 2248, "text": "If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity. Set Implementation:- Sets with Numerous operations on a single HashTable:- Examples:" }, { "code": null, "e": 3443, "s": 2624, "text": "# empty set, avoid using {} in creating set or dictionary is created\nx = set() \n\n# set {'e', 'h', 'l', 'o'} is created in unordered way\nB = set('hello') \n\n# set{'a', 'c', 'd', 'b', 'e', 'f', 'g'} is created\nA = set('abcdefg') \n\n# set{'a', 'b', 'h', 'c', 'd', 'e', 'f', 'g'} \nA.add('h') \n\nfruit ={'orange', 'banana', 'pear', 'apple'}\n\n# True fast membership testing in sets\n'pear' in fruit \n\n'mango' in fruit # False\n\nA == B # A is equivalent to B\n\nA != B # A is not equivalent to B\n\nA <= B # A is subset of B A <B>= B \n\nA > B # A is proper superset of B\n\nA | B # the union of A and B\n\nA & B # the intersection of A and B\n\nA - B # the set of elements in A but not B\n\nA Λ† B # the symmetric difference\n\na = {x for x in A if x not in 'abc'} # Set Comprehension" }, { "code": null, "e": 3454, "s": 3443, "text": "COMMITMENT" }, { "code": null, "e": 3472, "s": 3454, "text": "anukoolsrivastava" }, { "code": null, "e": 3479, "s": 3472, "text": "Picked" }, { "code": null, "e": 3490, "s": 3479, "text": "python-set" }, { "code": null, "e": 3497, "s": 3490, "text": "Python" }, { "code": null, "e": 3508, "s": 3497, "text": "python-set" }, { "code": null, "e": 3606, "s": 3508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3648, "s": 3606, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3670, "s": 3648, "text": "Enumerate() in Python" }, { "code": null, "e": 3702, "s": 3670, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3728, "s": 3702, "text": "Python String | replace()" }, { "code": null, "e": 3757, "s": 3728, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3784, "s": 3757, "text": "Python Classes and Objects" }, { "code": null, "e": 3805, "s": 3784, "text": "Python OOPs Concepts" }, { "code": null, "e": 3828, "s": 3805, "text": "Introduction To PYTHON" }, { "code": null, "e": 3859, "s": 3828, "text": "Python | os.path.join() method" } ]
Node.js process.chdir() Method
10 Jun, 2022 The process.chdir() method is an inbuilt application programming interface of the process module which is used to change the current working directory. Syntax: process.chdir( directory ) Parameters: This method accepts single parameter as mentioned above and described below: directory: It is required parameter that specifies the path to the directory to which current working directory to be changed. Return Value: This method does not return any value on success but throws an exception if fails to change directory specifying that β€œno such file or directory”. Below examples illustrate the use of process.chdir() method in Node.js: Example 1: javascript // Node.js program to demonstrate the // process.chdir() Method // Include process moduleconst process = require('process'); try { // Change the directory process.chdir('../os'); console.log("directory has successfully been changed");} catch (err) { // Printing error if occurs console.error("error while changing directory");} Output: directory has successfully been changed Example 2: javascript // Node.js program to demonstrate the // process.chdir() Method // Include process moduleconst process = require('process'); // Printing current directoryconsole.log("current working directory: " + process.cwd());try { // Change the directory process.chdir('../os'); console.log("working directory after " + "changing: " + process.cwd());} catch (err) { // Printing error if occurs console.error("error occurred while " + "changing directory: " + err);} Output: current working directory: C:\nodejs\g\process working directory after changing: C:\nodejs\g\os Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/process.html#process_process_chdir_directory nikhatkhan11 Node.js-process-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2022" }, { "code": null, "e": 188, "s": 28, "text": "The process.chdir() method is an inbuilt application programming interface of the process module which is used to change the current working directory. Syntax:" }, { "code": null, "e": 215, "s": 188, "text": "process.chdir( directory )" }, { "code": null, "e": 304, "s": 215, "text": "Parameters: This method accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 431, "s": 304, "text": "directory: It is required parameter that specifies the path to the directory to which current working directory to be changed." }, { "code": null, "e": 676, "s": 431, "text": "Return Value: This method does not return any value on success but throws an exception if fails to change directory specifying that β€œno such file or directory”. Below examples illustrate the use of process.chdir() method in Node.js: Example 1: " }, { "code": null, "e": 687, "s": 676, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // process.chdir() Method // Include process moduleconst process = require('process'); try { // Change the directory process.chdir('../os'); console.log(\"directory has successfully been changed\");} catch (err) { // Printing error if occurs console.error(\"error while changing directory\");}", "e": 1030, "s": 687, "text": null }, { "code": null, "e": 1038, "s": 1030, "text": "Output:" }, { "code": null, "e": 1078, "s": 1038, "text": "directory has successfully been changed" }, { "code": null, "e": 1090, "s": 1078, "text": "Example 2: " }, { "code": null, "e": 1101, "s": 1090, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // process.chdir() Method // Include process moduleconst process = require('process'); // Printing current directoryconsole.log(\"current working directory: \" + process.cwd());try { // Change the directory process.chdir('../os'); console.log(\"working directory after \" + \"changing: \" + process.cwd());} catch (err) { // Printing error if occurs console.error(\"error occurred while \" + \"changing directory: \" + err);}", "e": 1597, "s": 1101, "text": null }, { "code": null, "e": 1605, "s": 1597, "text": "Output:" }, { "code": null, "e": 1701, "s": 1605, "text": "current working directory: C:\\nodejs\\g\\process\nworking directory after changing: C:\\nodejs\\g\\os" }, { "code": null, "e": 1864, "s": 1701, "text": "Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/process.html#process_process_chdir_directory" }, { "code": null, "e": 1877, "s": 1864, "text": "nikhatkhan11" }, { "code": null, "e": 1900, "s": 1877, "text": "Node.js-process-module" }, { "code": null, "e": 1908, "s": 1900, "text": "Node.js" }, { "code": null, "e": 1925, "s": 1908, "text": "Web Technologies" }, { "code": null, "e": 2023, "s": 1925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2071, "s": 2023, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2104, "s": 2071, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 2134, "s": 2104, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 2154, "s": 2134, "text": "How to update NPM ?" }, { "code": null, "e": 2208, "s": 2154, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 2270, "s": 2208, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2331, "s": 2270, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2381, "s": 2331, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2424, "s": 2381, "text": "How to fetch data from an API in ReactJS ?" } ]
turtle.sety() function in Python
30 Jun, 2021 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This method is used to set the turtle’s second coordinate to y, leaving the first coordinate unchanged. Here, whatever the position of the turtle is, it set the y coordinate to given input keeping the x coordinate unchanged. Syntax : turtle.sety(y) Parameter: y: a number (integer or float), it is the only one required argument. Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # check the turtle positionprint(turtle.position()) # set the y coordinateturtle.sety(30) # check the turtle positionprint(turtle.position()) # set the y coordinateturtle.sety(-50) # check the turtle positionprint(turtle.position()) Output : (0.0, 0.0) (0.0, 30.0) (0.0, -50.0) Example 2 : Python3 # import packageimport turtle # loop for patternfor i in range(4): # motion turtle.forward(100) turtle.right(90) turtle.forward(20) turtle.right(90) turtle.forward(100) # set the y coordinate turtle.up() turtle.sety(-40*(i+1)) turtle.down() # change the direction turtle.left(180) Output : as5853535 Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 470, "s": 245, "text": "This method is used to set the turtle’s second coordinate to y, leaving the first coordinate unchanged. Here, whatever the position of the turtle is, it set the y coordinate to given input keeping the x coordinate unchanged." }, { "code": null, "e": 496, "s": 470, "text": "Syntax : turtle.sety(y) " }, { "code": null, "e": 508, "s": 496, "text": "Parameter: " }, { "code": null, "e": 578, "s": 508, "text": "y: a number (integer or float), it is the only one required argument." }, { "code": null, "e": 647, "s": 578, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 659, "s": 647, "text": "Example 1 :" }, { "code": null, "e": 667, "s": 659, "text": "Python3" }, { "code": "# import packageimport turtle # check the turtle positionprint(turtle.position()) # set the y coordinateturtle.sety(30) # check the turtle positionprint(turtle.position()) # set the y coordinateturtle.sety(-50) # check the turtle positionprint(turtle.position())", "e": 931, "s": 667, "text": null }, { "code": null, "e": 944, "s": 935, "text": "Output :" }, { "code": null, "e": 982, "s": 946, "text": "(0.0, 0.0)\n(0.0, 30.0)\n(0.0, -50.0)" }, { "code": null, "e": 996, "s": 984, "text": "Example 2 :" }, { "code": null, "e": 1006, "s": 998, "text": "Python3" }, { "code": "# import packageimport turtle # loop for patternfor i in range(4): # motion turtle.forward(100) turtle.right(90) turtle.forward(20) turtle.right(90) turtle.forward(100) # set the y coordinate turtle.up() turtle.sety(-40*(i+1)) turtle.down() # change the direction turtle.left(180)", "e": 1308, "s": 1006, "text": null }, { "code": null, "e": 1321, "s": 1312, "text": "Output :" }, { "code": null, "e": 1335, "s": 1325, "text": "as5853535" }, { "code": null, "e": 1349, "s": 1335, "text": "Python-turtle" }, { "code": null, "e": 1356, "s": 1349, "text": "Python" }, { "code": null, "e": 1454, "s": 1356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1486, "s": 1454, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1513, "s": 1486, "text": "Python Classes and Objects" }, { "code": null, "e": 1544, "s": 1513, "text": "Python | os.path.join() method" }, { "code": null, "e": 1567, "s": 1544, "text": "Introduction To PYTHON" }, { "code": null, "e": 1588, "s": 1567, "text": "Python OOPs Concepts" }, { "code": null, "e": 1644, "s": 1588, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1686, "s": 1644, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1728, "s": 1686, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1767, "s": 1728, "text": "Python | Get unique values from a list" } ]
TensorFlow 2.0
16 May, 2020 TensorFlow the massively popular open-source platform to develop and integrate large scale AI and Deep Learning Models has recently been updated to its newer form TensorFlow 2.0. This brings a massive boost in features in the originally feature-rich ML ecosystem created by the TensorFlow community. What is Open-Source and how is it made TensorFlow so successful?Open-Source means something that the people(mainly developers) can modify, share, integrate because all the original design features are open to all. This makes it very easy for a particular software, product to expand easily, effectively, and in a very little time. This feature allowed the original creator of TensorFlow i.e Google to easily port this into every platform available in the market that includes Web, Mobile, Internet of Things, Embedded Systems, Edge Computing and included support of various other languages such JavaScript, Node.js, F#, C++, C#, React.js, Go, Julia, Rust, Android, Swift, Kotlin and many other.Along with this came the support for hardware acceleration for running large scale Machine Learning codes. These include CUDA(library for running ML code on GPUs), TPUs(Tensor Processing Unit- Custom hardware provided by Google specially designed and developed to process tensors using TensorFlow) for multiple machine configuration, GPU, GPGPU, Cloud-based TPU’s, ASIC (Application Specific Integrated Circuits) FPGAs(Field-Programmable Gate Arrays- These are exclusively used for custom Programmable Hardware). This also includes new additions such as NVIDIA’s Jetson TX2 and Intel’s Movidius chips.Now coming back to the newer and much feature rich TensorFlow2.0:This is a graphical implementation of the changes: Model Diagram The things which are added include: The main API is now non-other than the Keras: The fluid layer of Keras is now integrated on top of the raw TensorFlow code make it simple and easy to use. This would help bring a lot of progress and productivity in the field of Machine Learning and AI. Eager Command-line : This simple command line helps us to execute operation immediately without using Session.run command. Simplified and Integrated Workflow:Using tf.data for data loading(Or NumPy).Use Keras for model construction.(We can also use any premade Estimators).Use tf.function for DAG graph execution or use eager execution.Utilize distribution strategy for high-performance-computing and deep learning models. (For TPUs, GPUs etc).TF 2.0 standardizes Saved Model as a serialized version of a TensorFlow graph for a variety of different platforms ranging from Mobile, JavaScript, TensorBoard, TensorHub..etc. Using tf.data for data loading(Or NumPy).Use Keras for model construction.(We can also use any premade Estimators).Use tf.function for DAG graph execution or use eager execution.Utilize distribution strategy for high-performance-computing and deep learning models. (For TPUs, GPUs etc).TF 2.0 standardizes Saved Model as a serialized version of a TensorFlow graph for a variety of different platforms ranging from Mobile, JavaScript, TensorBoard, TensorHub..etc. Using tf.data for data loading(Or NumPy). Use Keras for model construction.(We can also use any premade Estimators). Use tf.function for DAG graph execution or use eager execution. Utilize distribution strategy for high-performance-computing and deep learning models. (For TPUs, GPUs etc). TF 2.0 standardizes Saved Model as a serialized version of a TensorFlow graph for a variety of different platforms ranging from Mobile, JavaScript, TensorBoard, TensorHub..etc. Support for TensorFlow Lite and TensorFlow Edge Computing: This would help the developers to give effective Machine Learning and AI services to the end devices. This would require very less computing power along with faster model implementation and end-users The new extensions for Web Applications and Node.js using TensorFlow.js for new and interactive AI-based websites and applications. TensorFlow optimization for Android. TensorFlow Integration for Swift and IOS based applications. Support for the most-awaited upcoming WebGPU Chrome RFC proposal. Unified Programming Paradigms(Directed Acyclic Graph/Functional and Stack/Sequential). TensorFlow AIY(Artificial Intelligence for Yourself) support. Integration of tf.contrib into separate repositories. Improved TPU and TPU support and distributed computation support and support for the same up to v3. Improved HPC integration for Parallel Computing. Community Integration for Development, Support and Research. Integration of tf.contrib best package implementation into the core package. Domain-Specific Community Support. Extra Support for Model Validation and Reuse. End-to-End ML Pipelines and Products available at TensorFlow Hub. At last we can now build big ML and Deep Learning models easily, effectively on TensorFlow2.0 for end-users, and implement them on a large scale. Examples:Training a neural network to categorize MNSIT data # Write Python3 code hereimport tensorflow as tf """The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this:""" mnist = tf.keras.datasets.fashion_mnist """Calling load_data on this object will give you two sets of two lists, these will be the training and testing values for the graphics that contain the clothing items and their labels.""" (training_images, training_labels), (test_images, test_labels) = mnist.load_data()"""You'll notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it's easier if wetreat all values as between 0 and 1, a process called '**normalizing**'...andfortunately in Python it's easy to normalize a list like this without looping.So, perform it like - """ training_images = training_images / 255.0test_images = test_images / 255.0 """Now you might be wondering why there are 2 sets...training and testing-- remember we spoke about this in the intro? The idea is to have 1 set ofdata for training, and then another set of data...that the model hasn't yetseen...to see how good it would be at classifying values. After all, whenyou're done, you're going to want to try it out with data that it hadn't previously seen! Let's now design the model. There are quite a few new concepts here, but don't worry, you'll get the hang of them.""" model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense( 128, activation=tf.nn.relu), tf.keras.layers.Dense( 10, activation=tf.nn.softmax)]) """**Sequential**: That defines a SEQUENCE of layers in the neural network **Flatten**: Remember earlier where our images were a square whenyou printed them out? Flatten just takes that square and turns itinto a 1-dimensional set. **Dense**: Adds a layer of neurons Each layer of neurons needs an **activation function** to tell them what todo. There are lots of options, but just use these for now. **Relu** effectively means "If X>0 return X, else return 0" -- so what it does it only passes values 0 or greater to the next layer in the network. **Softmax** takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0,0,0,0,1,0,0,0,0] -- The goal is to save a lot of coding! The next thing to do, now the model is defined, is to actually build it.You do this by compiling it with an optimizer and loss function as before -- and then you train it by calling **model.fit ** asking it to fit your trainingdata to your training labels -- i.e. have it figure out the relationship betweenthe training data and its actual labels, so in future, if you have data thatlooks like the training data, then it can make a prediction for what that datawould look like.""" model.compile(optimizer = tf.keras.optimizers.Adam(), loss = 'sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(training_images, training_labels, epochs=5) """Once it's done training -- you should see an accuracy value at the end of thefinal epoch. It might look something like 0.9098. This tells you that yourneural network is about 91% accurate in classifying the training data. I.E.,it figured out a pattern match between the image and the labels that worked91% of the time. Not great, but not bad considering it was only trained for 5epochs and done quite quickly. But how would it work with unseen data? That's why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back theloss for each. Let's give it a try:""" model.evaluate(test_images, test_labels) """ For me, that returned an accuracy of about .8838, which means it was about 88% accurate. As expected it probably would not do as well with *unseen*data as it did with data it was trained on! """ Output: Expected Accuracy 88-91% Eager Execution : import tensorflow as tfimport tensorflow.contrib.eager as tfe tfe.enable_eager_execution() x = [[2.]]m = tf.matmul(x, x) print(m) Output : tf.Tensor([[4.]], shape=(1, 1), dtype=float32) ADARSHSINGH9 data-science Advanced Computer Subject Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2020" }, { "code": null, "e": 328, "s": 28, "text": "TensorFlow the massively popular open-source platform to develop and integrate large scale AI and Deep Learning Models has recently been updated to its newer form TensorFlow 2.0. This brings a massive boost in features in the originally feature-rich ML ecosystem created by the TensorFlow community." }, { "code": null, "e": 1739, "s": 328, "text": "What is Open-Source and how is it made TensorFlow so successful?Open-Source means something that the people(mainly developers) can modify, share, integrate because all the original design features are open to all. This makes it very easy for a particular software, product to expand easily, effectively, and in a very little time. This feature allowed the original creator of TensorFlow i.e Google to easily port this into every platform available in the market that includes Web, Mobile, Internet of Things, Embedded Systems, Edge Computing and included support of various other languages such JavaScript, Node.js, F#, C++, C#, React.js, Go, Julia, Rust, Android, Swift, Kotlin and many other.Along with this came the support for hardware acceleration for running large scale Machine Learning codes. These include CUDA(library for running ML code on GPUs), TPUs(Tensor Processing Unit- Custom hardware provided by Google specially designed and developed to process tensors using TensorFlow) for multiple machine configuration, GPU, GPGPU, Cloud-based TPU’s, ASIC (Application Specific Integrated Circuits) FPGAs(Field-Programmable Gate Arrays- These are exclusively used for custom Programmable Hardware). This also includes new additions such as NVIDIA’s Jetson TX2 and Intel’s Movidius chips.Now coming back to the newer and much feature rich TensorFlow2.0:This is a graphical implementation of the changes:" }, { "code": null, "e": 1753, "s": 1739, "text": "Model Diagram" }, { "code": null, "e": 1789, "s": 1753, "text": "The things which are added include:" }, { "code": null, "e": 2042, "s": 1789, "text": "The main API is now non-other than the Keras: The fluid layer of Keras is now integrated on top of the raw TensorFlow code make it simple and easy to use. This would help bring a lot of progress and productivity in the field of Machine Learning and AI." }, { "code": null, "e": 2165, "s": 2042, "text": "Eager Command-line : This simple command line helps us to execute operation immediately without using Session.run command." }, { "code": null, "e": 2663, "s": 2165, "text": "Simplified and Integrated Workflow:Using tf.data for data loading(Or NumPy).Use Keras for model construction.(We can also use any premade Estimators).Use tf.function for DAG graph execution or use eager execution.Utilize distribution strategy for high-performance-computing and deep learning models. (For TPUs, GPUs etc).TF 2.0 standardizes Saved Model as a serialized version of a TensorFlow graph for a variety of different platforms ranging from Mobile, JavaScript, TensorBoard, TensorHub..etc." }, { "code": null, "e": 3126, "s": 2663, "text": "Using tf.data for data loading(Or NumPy).Use Keras for model construction.(We can also use any premade Estimators).Use tf.function for DAG graph execution or use eager execution.Utilize distribution strategy for high-performance-computing and deep learning models. (For TPUs, GPUs etc).TF 2.0 standardizes Saved Model as a serialized version of a TensorFlow graph for a variety of different platforms ranging from Mobile, JavaScript, TensorBoard, TensorHub..etc." }, { "code": null, "e": 3168, "s": 3126, "text": "Using tf.data for data loading(Or NumPy)." }, { "code": null, "e": 3243, "s": 3168, "text": "Use Keras for model construction.(We can also use any premade Estimators)." }, { "code": null, "e": 3307, "s": 3243, "text": "Use tf.function for DAG graph execution or use eager execution." }, { "code": null, "e": 3416, "s": 3307, "text": "Utilize distribution strategy for high-performance-computing and deep learning models. (For TPUs, GPUs etc)." }, { "code": null, "e": 3593, "s": 3416, "text": "TF 2.0 standardizes Saved Model as a serialized version of a TensorFlow graph for a variety of different platforms ranging from Mobile, JavaScript, TensorBoard, TensorHub..etc." }, { "code": null, "e": 3852, "s": 3593, "text": "Support for TensorFlow Lite and TensorFlow Edge Computing: This would help the developers to give effective Machine Learning and AI services to the end devices. This would require very less computing power along with faster model implementation and end-users" }, { "code": null, "e": 3984, "s": 3852, "text": "The new extensions for Web Applications and Node.js using TensorFlow.js for new and interactive AI-based websites and applications." }, { "code": null, "e": 4021, "s": 3984, "text": "TensorFlow optimization for Android." }, { "code": null, "e": 4082, "s": 4021, "text": "TensorFlow Integration for Swift and IOS based applications." }, { "code": null, "e": 4148, "s": 4082, "text": "Support for the most-awaited upcoming WebGPU Chrome RFC proposal." }, { "code": null, "e": 4235, "s": 4148, "text": "Unified Programming Paradigms(Directed Acyclic Graph/Functional and Stack/Sequential)." }, { "code": null, "e": 4297, "s": 4235, "text": "TensorFlow AIY(Artificial Intelligence for Yourself) support." }, { "code": null, "e": 4351, "s": 4297, "text": "Integration of tf.contrib into separate repositories." }, { "code": null, "e": 4451, "s": 4351, "text": "Improved TPU and TPU support and distributed computation support and support for the same up to v3." }, { "code": null, "e": 4500, "s": 4451, "text": "Improved HPC integration for Parallel Computing." }, { "code": null, "e": 4561, "s": 4500, "text": "Community Integration for Development, Support and Research." }, { "code": null, "e": 4638, "s": 4561, "text": "Integration of tf.contrib best package implementation into the core package." }, { "code": null, "e": 4673, "s": 4638, "text": "Domain-Specific Community Support." }, { "code": null, "e": 4719, "s": 4673, "text": "Extra Support for Model Validation and Reuse." }, { "code": null, "e": 4785, "s": 4719, "text": "End-to-End ML Pipelines and Products available at TensorFlow Hub." }, { "code": null, "e": 4931, "s": 4785, "text": "At last we can now build big ML and Deep Learning models easily, effectively on TensorFlow2.0 for end-users, and implement them on a large scale." }, { "code": null, "e": 4991, "s": 4931, "text": "Examples:Training a neural network to categorize MNSIT data" }, { "code": "# Write Python3 code hereimport tensorflow as tf \"\"\"The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this:\"\"\" mnist = tf.keras.datasets.fashion_mnist \"\"\"Calling load_data on this object will give you two sets of two lists, these will be the training and testing values for the graphics that contain the clothing items and their labels.\"\"\" (training_images, training_labels), (test_images, test_labels) = mnist.load_data()\"\"\"You'll notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it's easier if wetreat all values as between 0 and 1, a process called '**normalizing**'...andfortunately in Python it's easy to normalize a list like this without looping.So, perform it like - \"\"\" training_images = training_images / 255.0test_images = test_images / 255.0 \"\"\"Now you might be wondering why there are 2 sets...training and testing-- remember we spoke about this in the intro? The idea is to have 1 set ofdata for training, and then another set of data...that the model hasn't yetseen...to see how good it would be at classifying values. After all, whenyou're done, you're going to want to try it out with data that it hadn't previously seen! Let's now design the model. There are quite a few new concepts here, but don't worry, you'll get the hang of them.\"\"\" model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense( 128, activation=tf.nn.relu), tf.keras.layers.Dense( 10, activation=tf.nn.softmax)]) \"\"\"**Sequential**: That defines a SEQUENCE of layers in the neural network **Flatten**: Remember earlier where our images were a square whenyou printed them out? Flatten just takes that square and turns itinto a 1-dimensional set. **Dense**: Adds a layer of neurons Each layer of neurons needs an **activation function** to tell them what todo. There are lots of options, but just use these for now. **Relu** effectively means \"If X>0 return X, else return 0\" -- so what it does it only passes values 0 or greater to the next layer in the network. **Softmax** takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0,0,0,0,1,0,0,0,0] -- The goal is to save a lot of coding! The next thing to do, now the model is defined, is to actually build it.You do this by compiling it with an optimizer and loss function as before -- and then you train it by calling **model.fit ** asking it to fit your trainingdata to your training labels -- i.e. have it figure out the relationship betweenthe training data and its actual labels, so in future, if you have data thatlooks like the training data, then it can make a prediction for what that datawould look like.\"\"\" model.compile(optimizer = tf.keras.optimizers.Adam(), loss = 'sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(training_images, training_labels, epochs=5) \"\"\"Once it's done training -- you should see an accuracy value at the end of thefinal epoch. It might look something like 0.9098. This tells you that yourneural network is about 91% accurate in classifying the training data. I.E.,it figured out a pattern match between the image and the labels that worked91% of the time. Not great, but not bad considering it was only trained for 5epochs and done quite quickly. But how would it work with unseen data? That's why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back theloss for each. Let's give it a try:\"\"\" model.evaluate(test_images, test_labels) \"\"\" For me, that returned an accuracy of about .8838, which means it was about 88% accurate. As expected it probably would not do as well with *unseen*data as it did with data it was trained on! \"\"\"", "e": 9126, "s": 4991, "text": null }, { "code": null, "e": 9134, "s": 9126, "text": "Output:" }, { "code": null, "e": 9160, "s": 9134, "text": "Expected Accuracy 88-91%\n" }, { "code": null, "e": 9178, "s": 9160, "text": "Eager Execution :" }, { "code": "import tensorflow as tfimport tensorflow.contrib.eager as tfe tfe.enable_eager_execution() x = [[2.]]m = tf.matmul(x, x) print(m)", "e": 9314, "s": 9178, "text": null }, { "code": null, "e": 9323, "s": 9314, "text": "Output :" }, { "code": null, "e": 9370, "s": 9323, "text": "tf.Tensor([[4.]], shape=(1, 1), dtype=float32)" }, { "code": null, "e": 9383, "s": 9370, "text": "ADARSHSINGH9" }, { "code": null, "e": 9396, "s": 9383, "text": "data-science" }, { "code": null, "e": 9422, "s": 9396, "text": "Advanced Computer Subject" }, { "code": null, "e": 9431, "s": 9422, "text": "Articles" } ]
How to use Google material icon as list-style in a webpage using HTML and CSS ?
18 Jan, 2021 Icons can be added to our HTML page from the icon library. All the icons in the library can be formatted using CSS. They can be customized according to size, colour, shadow, etc. They play a considerate part in materialize CSS. Materialize CSS provides a rich set of material icons of google which can be downloaded from Material Design specs. Library and Usage: To use these icons, the following line is added in the <head> part of the HTML code. HTML <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> Then to use the icons, the name of the icon is provided in the <i> part of HTML element. <i class="material-icons">add</i> To learn more about materialize CSS follow the article below: Materialize CSS Icons In this article, we will learn how to use these icons as a list-style. Firstly, we will remove the default list style by setting list-style-type to none.HTMLHTML<style> ul{ list-style-type: none; }</style> HTML <style> ul{ list-style-type: none; }</style> Then we will use the li:before style to add content before the list value and add material icons as content.HTMLHTML<style> li:before{ content: 'arrow_right'; font-family: 'Material Icons'; }</style> HTML <style> li:before{ content: 'arrow_right'; font-family: 'Material Icons'; }</style> This style will add the right arrow icon to all the list contents. Final Code: HTML <!DOCTYPE> <html> <head> <!-- Google Material Icon Script --> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <style> /* Removing the list style of list gfg */ .gfg{ list-style-type:none; } /* Adding icon before each list icon */ .gfg > li:before{ content: 'arrow_right'; font-family: 'Material Icons'; font-size: 25px; vertical-align: -30%; } </style></head> <body> <center> <h1 style="color:forestgreen;"> GeeksForGeeks </h1> </center> <!-- This is a list with bullet style --> <h3 style="color:crimson;"> List with bullet style: </h3> <ul style="color:dodgerblue;"> <li>Geek 1</li> <li>Geek 2</li> <li>Geek 3</li> </ul> <!-- This is the list with icon as its style --> <h3 style="color:crimson;"> List with icon as style: </h3> <ul class="gfg" style="color:dodgerblue;"> <li>Geek 1</li> <li>Geek 2</li> <li>Geek 3</li> </ul> </body> </html> Output: CSS-Misc HTML-Misc Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2021" }, { "code": null, "e": 372, "s": 28, "text": "Icons can be added to our HTML page from the icon library. All the icons in the library can be formatted using CSS. They can be customized according to size, colour, shadow, etc. They play a considerate part in materialize CSS. Materialize CSS provides a rich set of material icons of google which can be downloaded from Material Design specs." }, { "code": null, "e": 476, "s": 372, "text": "Library and Usage: To use these icons, the following line is added in the <head> part of the HTML code." }, { "code": null, "e": 481, "s": 476, "text": "HTML" }, { "code": "<link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">", "e": 568, "s": 481, "text": null }, { "code": null, "e": 657, "s": 568, "text": "Then to use the icons, the name of the icon is provided in the <i> part of HTML element." }, { "code": null, "e": 691, "s": 657, "text": "<i class=\"material-icons\">add</i>" }, { "code": null, "e": 753, "s": 691, "text": "To learn more about materialize CSS follow the article below:" }, { "code": null, "e": 846, "s": 753, "text": "Materialize CSS Icons In this article, we will learn how to use these icons as a list-style." }, { "code": null, "e": 988, "s": 846, "text": "Firstly, we will remove the default list style by setting list-style-type to none.HTMLHTML<style> ul{ list-style-type: none; }</style>" }, { "code": null, "e": 993, "s": 988, "text": "HTML" }, { "code": "<style> ul{ list-style-type: none; }</style>", "e": 1045, "s": 993, "text": null }, { "code": null, "e": 1253, "s": 1045, "text": "Then we will use the li:before style to add content before the list value and add material icons as content.HTMLHTML<style> li:before{ content: 'arrow_right'; font-family: 'Material Icons'; }</style>" }, { "code": null, "e": 1258, "s": 1253, "text": "HTML" }, { "code": "<style> li:before{ content: 'arrow_right'; font-family: 'Material Icons'; }</style>", "e": 1350, "s": 1258, "text": null }, { "code": null, "e": 1417, "s": 1350, "text": "This style will add the right arrow icon to all the list contents." }, { "code": null, "e": 1429, "s": 1417, "text": "Final Code:" }, { "code": null, "e": 1434, "s": 1429, "text": "HTML" }, { "code": "<!DOCTYPE> <html> <head> <!-- Google Material Icon Script --> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\"> <style> /* Removing the list style of list gfg */ .gfg{ list-style-type:none; } /* Adding icon before each list icon */ .gfg > li:before{ content: 'arrow_right'; font-family: 'Material Icons'; font-size: 25px; vertical-align: -30%; } </style></head> <body> <center> <h1 style=\"color:forestgreen;\"> GeeksForGeeks </h1> </center> <!-- This is a list with bullet style --> <h3 style=\"color:crimson;\"> List with bullet style: </h3> <ul style=\"color:dodgerblue;\"> <li>Geek 1</li> <li>Geek 2</li> <li>Geek 3</li> </ul> <!-- This is the list with icon as its style --> <h3 style=\"color:crimson;\"> List with icon as style: </h3> <ul class=\"gfg\" style=\"color:dodgerblue;\"> <li>Geek 1</li> <li>Geek 2</li> <li>Geek 3</li> </ul> </body> </html>", "e": 2587, "s": 1434, "text": null }, { "code": null, "e": 2595, "s": 2587, "text": "Output:" }, { "code": null, "e": 2604, "s": 2595, "text": "CSS-Misc" }, { "code": null, "e": 2614, "s": 2604, "text": "HTML-Misc" }, { "code": null, "e": 2638, "s": 2614, "text": "Technical Scripter 2020" }, { "code": null, "e": 2642, "s": 2638, "text": "CSS" }, { "code": null, "e": 2647, "s": 2642, "text": "HTML" }, { "code": null, "e": 2666, "s": 2647, "text": "Technical Scripter" }, { "code": null, "e": 2683, "s": 2666, "text": "Web Technologies" }, { "code": null, "e": 2688, "s": 2683, "text": "HTML" }, { "code": null, "e": 2786, "s": 2688, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2825, "s": 2786, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2864, "s": 2825, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2903, "s": 2864, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2940, "s": 2903, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2969, "s": 2940, "text": "Form validation using jQuery" }, { "code": null, "e": 2993, "s": 2969, "text": "REST API (Introduction)" }, { "code": null, "e": 3046, "s": 2993, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3106, "s": 3046, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3167, "s": 3106, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How do you empty an array in C#?
To empty an array in C#, use the Array Clear() method: The Array.Clear method in C# clears i.e.zeros out all elements. In the below example, we have first considered an array with three elements βˆ’ int[] arr = new int[] {88, 45, 76}; Now we have used the Array.Clear method to zero out all the arrays βˆ’ Array.Clear(arr, 0, arr.Length); Let us see an example of Array.Clear method in c# βˆ’ Live Demo using System; class Program { static void Main() { int[] arr = new int[] {88, 45, 76}; Console.WriteLine("Array (Old):"); foreach (int val in arr) { Console.WriteLine(val); } Array.Clear(arr, 0, arr.Length); Console.WriteLine("Array (After using Clear):"); foreach (int val in arr) { Console.WriteLine(val); } } } Array (Old): 88 45 76 Array (After using Clear): 0 0 0
[ { "code": null, "e": 1306, "s": 1187, "text": "To empty an array in C#, use the Array Clear() method: The Array.Clear method in C# clears i.e.zeros out all elements." }, { "code": null, "e": 1384, "s": 1306, "text": "In the below example, we have first considered an array with three elements βˆ’" }, { "code": null, "e": 1420, "s": 1384, "text": "int[] arr = new int[] {88, 45, 76};" }, { "code": null, "e": 1489, "s": 1420, "text": "Now we have used the Array.Clear method to zero out all the arrays βˆ’" }, { "code": null, "e": 1522, "s": 1489, "text": "Array.Clear(arr, 0, arr.Length);" }, { "code": null, "e": 1574, "s": 1522, "text": "Let us see an example of Array.Clear method in c# βˆ’" }, { "code": null, "e": 1585, "s": 1574, "text": " Live Demo" }, { "code": null, "e": 1972, "s": 1585, "text": "using System;\nclass Program {\n static void Main() {\n int[] arr = new int[] {88, 45, 76};\n Console.WriteLine(\"Array (Old):\");\n foreach (int val in arr) {\n Console.WriteLine(val);\n }\n\n Array.Clear(arr, 0, arr.Length);\n Console.WriteLine(\"Array (After using Clear):\");\n foreach (int val in arr) {\n Console.WriteLine(val);\n }\n }\n}" }, { "code": null, "e": 2027, "s": 1972, "text": "Array (Old):\n88\n45\n76\nArray (After using Clear):\n0\n0\n0" } ]
Implementing Artificial Neural Network training process in Python
08 Jul, 2022 An Artificial Neural Network (ANN) is an information processing paradigm that is inspired the brain. ANNs, like people, learn by example. An ANN is configured for a specific application, such as pattern recognition or data classification, through a learning process. Learning largely involves adjustments to the synaptic connections that exist between the neurons. The brain consists of hundreds of billions of cells called neurons. These neurons are connected together by synapses which are nothing but the connections across which a neuron can send an impulse to another neuron. When a neuron sends an excitatory signal to another neuron, then this signal will be added to all of the other inputs of that neuron. If it exceeds a given threshold then it will cause the target neuron to fire an action signal forward β€” this is how the thinking process works internally.In Computer Science, we model this process by creating β€œnetworks” on a computer using matrices. These networks can be understood as an abstraction of neurons without all the biological complexities taken into account. To keep things simple, we will just model a simple NN, with two layers capable of solving a linear classification problem. Let’s say we have a problem where we want to predict output given a set of inputs and outputs as training example like so: Note that the output is directly related to the third column i.e. the values of input 3 is what the output is in every training example in fig. 2. So for the test example output value should be 1. The training process consists of the following steps: Forward Propagation: Take the inputs, multiply by the weights (just use random numbers as weights) Let Y = WiIi = W1I1+W2I2+W3I3 Pass the result through a sigmoid formula to calculate the neuron’s output. The Sigmoid function is used to normalize the result between 0 and 1: 1/1 + e-yBack Propagation Calculate the error i.e the difference between the actual output and the expected output. Depending on the error, adjust the weights by multiplying the error with the input and again with the gradient of the Sigmoid curve: Weight += Error Input Output (1-Output) ,here Output (1-Output) is derivative of sigmoid curve. Forward Propagation: Take the inputs, multiply by the weights (just use random numbers as weights) Let Y = WiIi = W1I1+W2I2+W3I3 Pass the result through a sigmoid formula to calculate the neuron’s output. The Sigmoid function is used to normalize the result between 0 and 1: 1/1 + e-y Back Propagation Calculate the error i.e the difference between the actual output and the expected output. Depending on the error, adjust the weights by multiplying the error with the input and again with the gradient of the Sigmoid curve: Weight += Error Input Output (1-Output) ,here Output (1-Output) is derivative of sigmoid curve. Note: Repeat the whole process for a few thousand iterations.Let’s code up the whole process in Python. We’ll be using the Numpy library to help us with all the calculations on matrices easily. You’d need to install a numpy library on your system to run the code Command to install numpy: sudo apt -get install python-numpy Implementation: Python3 from joblib.numpy_pickle_utils import xrangefrom numpy import * class NeuralNet(object): def __init__(self): # Generate random numbers random.seed(1) # Assign random weights to a 3 x 1 matrix, self.synaptic_weights = 2 * random.random((3, 1)) - 1 # The Sigmoid function def __sigmoid(self, x): return 1 / (1 + exp(-x)) # The derivative of the Sigmoid function. # This is the gradient of the Sigmoid curve. def __sigmoid_derivative(self, x): return x * (1 - x) # Train the neural network and adjust the weights each time. def train(self, inputs, outputs, training_iterations): for iteration in xrange(training_iterations): # Pass the training set through the network. output = self.learn(inputs) # Calculate the error error = outputs - output # Adjust the weights by a factor factor = dot(inputs.T, error * self.__sigmoid_derivative(output)) self.synaptic_weights += factor # The neural network thinks. def learn(self, inputs): return self.__sigmoid(dot(inputs, self.synaptic_weights)) if __name__ == "__main__": # Initialize neural_network = NeuralNet() # The training set. inputs = array([[0, 1, 1], [1, 0, 0], [1, 0, 1]]) outputs = array([[1, 0, 1]]).T # Train the neural network neural_network.train(inputs, outputs, 10000) # Test the neural network with a test example. print(neural_network.learn(array([1, 0, 1]))) Expected Output: After 10 iterations our neural network predicts the value to be 0.65980921. It looks not good as the answer should really be 1. If we increase the number of iterations to 100, we get 0.87680541. Our network is getting smarter! Subsequently, for 10000 iterations we get 0.9897704 which is pretty close and indeed a satisfactory output.References: NEURAL NETWORKS by Christos Stergiou and Dimitrios Siganos Fundamentals of Deep Learning – Starting with Artificial Neural Network Tinker With a Neural Network Right Here in Your Browser Neural Networks Demystified This article is contributed by Vivek Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shayanpal0 tanwarsinghvaibhav amartyaghoshgfg Neural Network Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 422, "s": 54, "text": "An Artificial Neural Network (ANN) is an information processing paradigm that is inspired the brain. ANNs, like people, learn by example. An ANN is configured for a specific application, such as pattern recognition or data classification, through a learning process. Learning largely involves adjustments to the synaptic connections that exist between the neurons. " }, { "code": null, "e": 1268, "s": 422, "text": "The brain consists of hundreds of billions of cells called neurons. These neurons are connected together by synapses which are nothing but the connections across which a neuron can send an impulse to another neuron. When a neuron sends an excitatory signal to another neuron, then this signal will be added to all of the other inputs of that neuron. If it exceeds a given threshold then it will cause the target neuron to fire an action signal forward β€” this is how the thinking process works internally.In Computer Science, we model this process by creating β€œnetworks” on a computer using matrices. These networks can be understood as an abstraction of neurons without all the biological complexities taken into account. To keep things simple, we will just model a simple NN, with two layers capable of solving a linear classification problem. " }, { "code": null, "e": 1391, "s": 1268, "text": "Let’s say we have a problem where we want to predict output given a set of inputs and outputs as training example like so:" }, { "code": null, "e": 1589, "s": 1391, "text": "Note that the output is directly related to the third column i.e. the values of input 3 is what the output is in every training example in fig. 2. So for the test example output value should be 1. " }, { "code": null, "e": 1644, "s": 1589, "text": "The training process consists of the following steps: " }, { "code": null, "e": 2264, "s": 1644, "text": "Forward Propagation: Take the inputs, multiply by the weights (just use random numbers as weights) Let Y = WiIi = W1I1+W2I2+W3I3 Pass the result through a sigmoid formula to calculate the neuron’s output. The Sigmoid function is used to normalize the result between 0 and 1: 1/1 + e-yBack Propagation Calculate the error i.e the difference between the actual output and the expected output. Depending on the error, adjust the weights by multiplying the error with the input and again with the gradient of the Sigmoid curve: Weight += Error Input Output (1-Output) ,here Output (1-Output) is derivative of sigmoid curve." }, { "code": null, "e": 2549, "s": 2264, "text": "Forward Propagation: Take the inputs, multiply by the weights (just use random numbers as weights) Let Y = WiIi = W1I1+W2I2+W3I3 Pass the result through a sigmoid formula to calculate the neuron’s output. The Sigmoid function is used to normalize the result between 0 and 1: 1/1 + e-y" }, { "code": null, "e": 2885, "s": 2549, "text": "Back Propagation Calculate the error i.e the difference between the actual output and the expected output. Depending on the error, adjust the weights by multiplying the error with the input and again with the gradient of the Sigmoid curve: Weight += Error Input Output (1-Output) ,here Output (1-Output) is derivative of sigmoid curve." }, { "code": null, "e": 3175, "s": 2885, "text": "Note: Repeat the whole process for a few thousand iterations.Let’s code up the whole process in Python. We’ll be using the Numpy library to help us with all the calculations on matrices easily. You’d need to install a numpy library on your system to run the code Command to install numpy: " }, { "code": null, "e": 3211, "s": 3175, "text": " sudo apt -get install python-numpy" }, { "code": null, "e": 3227, "s": 3211, "text": "Implementation:" }, { "code": null, "e": 3235, "s": 3227, "text": "Python3" }, { "code": "from joblib.numpy_pickle_utils import xrangefrom numpy import * class NeuralNet(object): def __init__(self): # Generate random numbers random.seed(1) # Assign random weights to a 3 x 1 matrix, self.synaptic_weights = 2 * random.random((3, 1)) - 1 # The Sigmoid function def __sigmoid(self, x): return 1 / (1 + exp(-x)) # The derivative of the Sigmoid function. # This is the gradient of the Sigmoid curve. def __sigmoid_derivative(self, x): return x * (1 - x) # Train the neural network and adjust the weights each time. def train(self, inputs, outputs, training_iterations): for iteration in xrange(training_iterations): # Pass the training set through the network. output = self.learn(inputs) # Calculate the error error = outputs - output # Adjust the weights by a factor factor = dot(inputs.T, error * self.__sigmoid_derivative(output)) self.synaptic_weights += factor # The neural network thinks. def learn(self, inputs): return self.__sigmoid(dot(inputs, self.synaptic_weights)) if __name__ == \"__main__\": # Initialize neural_network = NeuralNet() # The training set. inputs = array([[0, 1, 1], [1, 0, 0], [1, 0, 1]]) outputs = array([[1, 0, 1]]).T # Train the neural network neural_network.train(inputs, outputs, 10000) # Test the neural network with a test example. print(neural_network.learn(array([1, 0, 1])))", "e": 4777, "s": 3235, "text": null }, { "code": null, "e": 5143, "s": 4777, "text": "Expected Output: After 10 iterations our neural network predicts the value to be 0.65980921. It looks not good as the answer should really be 1. If we increase the number of iterations to 100, we get 0.87680541. Our network is getting smarter! Subsequently, for 10000 iterations we get 0.9897704 which is pretty close and indeed a satisfactory output.References: " }, { "code": null, "e": 5202, "s": 5143, "text": "NEURAL NETWORKS by Christos Stergiou and Dimitrios Siganos" }, { "code": null, "e": 5274, "s": 5202, "text": "Fundamentals of Deep Learning – Starting with Artificial Neural Network" }, { "code": null, "e": 5330, "s": 5274, "text": "Tinker With a Neural Network Right Here in Your Browser" }, { "code": null, "e": 5358, "s": 5330, "text": "Neural Networks Demystified" }, { "code": null, "e": 5776, "s": 5358, "text": "This article is contributed by Vivek Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5787, "s": 5776, "text": "shayanpal0" }, { "code": null, "e": 5806, "s": 5787, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 5822, "s": 5806, "text": "amartyaghoshgfg" }, { "code": null, "e": 5837, "s": 5822, "text": "Neural Network" }, { "code": null, "e": 5844, "s": 5837, "text": "Python" }, { "code": null, "e": 5942, "s": 5844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5984, "s": 5942, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6006, "s": 5984, "text": "Enumerate() in Python" }, { "code": null, "e": 6032, "s": 6006, "text": "Python String | replace()" }, { "code": null, "e": 6064, "s": 6032, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6093, "s": 6064, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6120, "s": 6093, "text": "Python Classes and Objects" }, { "code": null, "e": 6141, "s": 6120, "text": "Python OOPs Concepts" }, { "code": null, "e": 6164, "s": 6141, "text": "Introduction To PYTHON" }, { "code": null, "e": 6200, "s": 6164, "text": "Convert integer to string in Python" } ]
How to open a new window by the user pressing a button in a tkinter GUI?
Tkinter creates a default window (i.e., master or root window) for every application. In tkinter, we can create a Popup window or a child window by defining a Toplevel(master) constructor. This will allow the tkinter application to create another window which can be resized dynamically by defining its size property. In this example, we have created a button widget that will open the new window with a text label. #Import tkinter library from tkinter import * from tkinter import ttk #Create an instance of tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Define a new function to open the window def open_win(): new= Toplevel(win) new.geometry("750x250") new.title("New Window") #Create a Label in New window Label(new, text="Hey, Howdy?", font=('Helvetica 17 bold')).pack(pady=30) #Create a label Label(win, text= "Click the below button to Open a New Window", font= ('Helvetica 17 bold')).pack(pady=30) #Create a button to open a New Window ttk.Button(win, text="Open", command=open_win).pack() win.mainloop() Running the above code will display a window that contains a button widget. When we click the button, it will open a new Window. Now, click the "Open" button to open a new Window.
[ { "code": null, "e": 1505, "s": 1187, "text": "Tkinter creates a default window (i.e., master or root window) for every application. In tkinter, we can create a Popup window or a child window by defining a Toplevel(master) constructor. This will allow the tkinter application to create another window which can be resized dynamically by defining its size property." }, { "code": null, "e": 1603, "s": 1505, "text": "In this example, we have created a button widget that will open the new window with a text label." }, { "code": null, "e": 2262, "s": 1603, "text": "#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n#Define a new function to open the window\ndef open_win():\n new= Toplevel(win)\n new.geometry(\"750x250\")\n new.title(\"New Window\")\n #Create a Label in New window\n Label(new, text=\"Hey, Howdy?\", font=('Helvetica 17 bold')).pack(pady=30)\n#Create a label\nLabel(win, text= \"Click the below button to Open a New Window\", font= ('Helvetica 17 bold')).pack(pady=30)\n#Create a button to open a New Window\nttk.Button(win, text=\"Open\", command=open_win).pack()\nwin.mainloop()" }, { "code": null, "e": 2391, "s": 2262, "text": "Running the above code will display a window that contains a button widget. When we click the button, it will open a new Window." }, { "code": null, "e": 2442, "s": 2391, "text": "Now, click the \"Open\" button to open a new Window." } ]
Tcl - Lists
List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of items. It can include different types of items in the same list. Further, a list can contain another list. An important thing that needs to be noted is that these lists are represented as strings completely and processed to form individual items when required. So, avoid large lists and in such cases; use array. The general syntax for list is given below βˆ’ set listName { item1 item2 item3 .. itemn } # or set listName [list item1 item2 item3] # or set listName [split "items separated by a character" split_character] Some examples are given below βˆ’ #!/usr/bin/tclsh set colorList1 {red green blue} set colorList2 [list red green blue] set colorList3 [split "red_green_blue" _] puts $colorList1 puts $colorList2 puts $colorList3 When the above code is executed, it produces the following result βˆ’ red green blue red green blue red green blue The syntax for appending item to a list is given below βˆ’ append listName split_character value # or lappend listName value Some examples are given below βˆ’ #!/usr/bin/tclsh set var orange append var " " "blue" lappend var "red" lappend var "green" puts $var When the above code is executed, it produces the following result βˆ’ orange blue red green The syntax for length of list is given below βˆ’ llength listName Example for length of list is given below βˆ’ #!/usr/bin/tclsh set var {orange blue red green} puts [llength $var] When the above code is executed, it produces the following result βˆ’ 4 The syntax for selecting list item at specific index is given below βˆ’ lindex listname index Example for list item at index is given below βˆ’ #!/usr/bin/tclsh set var {orange blue red green} puts [lindex $var 1] When the above code is executed, it produces the following result βˆ’ blue The syntax for inserting list items at specific index is given below. linsert listname index value1 value2..valuen Example for inserting list item at specific index is given below. #!/usr/bin/tclsh set var {orange blue red green} set var [linsert $var 3 black white] puts $var When the above code is executed, it produces the following result βˆ’ orange blue red black white green The syntax for replacing list items at specific indices is given below βˆ’ lreplace listname firstindex lastindex value1 value2..valuen Example for replacing list items at specific indices is given below. #!/usr/bin/tclsh set var {orange blue red green} set var [lreplace $var 2 3 black white] puts $var When the above code is executed, it produces the following result βˆ’ orange blue black white The syntax for setting list item at specific index is given below βˆ’ lset listname index value Example for setting list item at specific index is given below βˆ’ #!/usr/bin/tclsh set var {orange blue red green} lset var 0 black puts $var When the above code is executed, it produces the following result βˆ’ black blue red green The syntax for copying values to variables is given below βˆ’ lassign listname variable1 variable2.. variablen Example for transforming list into variables is given below βˆ’ #!/usr/bin/tclsh set var {orange blue red green} lassign $var colour1 colour2 puts $colour1 puts $colour2 When the above code is executed, it produces the following result βˆ’ orange blue The syntax for sorting a list is given below βˆ’ lsort listname An example for sorting a list is given below βˆ’ #!/usr/bin/tclsh set var {orange blue red green} set var [lsort $var] puts $var When the above code is executed, it produces the following result βˆ’ blue green orange red
[ { "code": null, "e": 2548, "s": 2335, "text": "List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of items. It can include different types of items in the same list. Further, a list can contain another list." }, { "code": null, "e": 2754, "s": 2548, "text": "An important thing that needs to be noted is that these lists are represented as strings completely and processed to form individual items when required. So, avoid large lists and in such cases; use array." }, { "code": null, "e": 2799, "s": 2754, "text": "The general syntax for list is given below βˆ’" }, { "code": null, "e": 2963, "s": 2799, "text": "set listName { item1 item2 item3 .. itemn }\n# or\nset listName [list item1 item2 item3]\n# or \nset listName [split \"items separated by a character\" split_character]\n" }, { "code": null, "e": 2995, "s": 2963, "text": "Some examples are given below βˆ’" }, { "code": null, "e": 3175, "s": 2995, "text": "#!/usr/bin/tclsh\n\nset colorList1 {red green blue}\nset colorList2 [list red green blue]\nset colorList3 [split \"red_green_blue\" _]\nputs $colorList1\nputs $colorList2\nputs $colorList3" }, { "code": null, "e": 3243, "s": 3175, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 3289, "s": 3243, "text": "red green blue\nred green blue\nred green blue\n" }, { "code": null, "e": 3346, "s": 3289, "text": "The syntax for appending item to a list is given below βˆ’" }, { "code": null, "e": 3413, "s": 3346, "text": "append listName split_character value\n# or\nlappend listName value\n" }, { "code": null, "e": 3445, "s": 3413, "text": "Some examples are given below βˆ’" }, { "code": null, "e": 3550, "s": 3445, "text": "#!/usr/bin/tclsh\n\nset var orange\nappend var \" \" \"blue\"\nlappend var \"red\" \nlappend var \"green\" \nputs $var" }, { "code": null, "e": 3618, "s": 3550, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 3641, "s": 3618, "text": "orange blue red green\n" }, { "code": null, "e": 3688, "s": 3641, "text": "The syntax for length of list is given below βˆ’" }, { "code": null, "e": 3706, "s": 3688, "text": "llength listName\n" }, { "code": null, "e": 3750, "s": 3706, "text": "Example for length of list is given below βˆ’" }, { "code": null, "e": 3821, "s": 3750, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nputs [llength $var] " }, { "code": null, "e": 3889, "s": 3821, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 3892, "s": 3889, "text": "4\n" }, { "code": null, "e": 3962, "s": 3892, "text": "The syntax for selecting list item at specific index is given below βˆ’" }, { "code": null, "e": 3985, "s": 3962, "text": "lindex listname index\n" }, { "code": null, "e": 4033, "s": 3985, "text": "Example for list item at index is given below βˆ’" }, { "code": null, "e": 4105, "s": 4033, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nputs [lindex $var 1]" }, { "code": null, "e": 4173, "s": 4105, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 4179, "s": 4173, "text": "blue\n" }, { "code": null, "e": 4249, "s": 4179, "text": "The syntax for inserting list items at specific index is given below." }, { "code": null, "e": 4295, "s": 4249, "text": "linsert listname index value1 value2..valuen\n" }, { "code": null, "e": 4361, "s": 4295, "text": "Example for inserting list item at specific index is given below." }, { "code": null, "e": 4459, "s": 4361, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nset var [linsert $var 3 black white]\nputs $var" }, { "code": null, "e": 4527, "s": 4459, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 4562, "s": 4527, "text": "orange blue red black white green\n" }, { "code": null, "e": 4635, "s": 4562, "text": "The syntax for replacing list items at specific indices is given below βˆ’" }, { "code": null, "e": 4697, "s": 4635, "text": "lreplace listname firstindex lastindex value1 value2..valuen\n" }, { "code": null, "e": 4766, "s": 4697, "text": "Example for replacing list items at specific indices is given below." }, { "code": null, "e": 4866, "s": 4766, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nset var [lreplace $var 2 3 black white]\nputs $var" }, { "code": null, "e": 4934, "s": 4866, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 4959, "s": 4934, "text": "orange blue black white\n" }, { "code": null, "e": 5027, "s": 4959, "text": "The syntax for setting list item at specific index is given below βˆ’" }, { "code": null, "e": 5055, "s": 5027, "text": "lset listname index value \n" }, { "code": null, "e": 5120, "s": 5055, "text": "Example for setting list item at specific index is given below βˆ’" }, { "code": null, "e": 5198, "s": 5120, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nlset var 0 black \nputs $var" }, { "code": null, "e": 5266, "s": 5198, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 5288, "s": 5266, "text": "black blue red green\n" }, { "code": null, "e": 5348, "s": 5288, "text": "The syntax for copying values to variables is given below βˆ’" }, { "code": null, "e": 5398, "s": 5348, "text": "lassign listname variable1 variable2.. variablen\n" }, { "code": null, "e": 5460, "s": 5398, "text": "Example for transforming list into variables is given below βˆ’" }, { "code": null, "e": 5567, "s": 5460, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nlassign $var colour1 colour2\nputs $colour1\nputs $colour2" }, { "code": null, "e": 5635, "s": 5567, "text": "When the above code is executed, it produces the following result βˆ’" }, { "code": null, "e": 5648, "s": 5635, "text": "orange\nblue\n" }, { "code": null, "e": 5695, "s": 5648, "text": "The syntax for sorting a list is given below βˆ’" }, { "code": null, "e": 5711, "s": 5695, "text": "lsort listname\n" }, { "code": null, "e": 5758, "s": 5711, "text": "An example for sorting a list is given below βˆ’" }, { "code": null, "e": 5839, "s": 5758, "text": "#!/usr/bin/tclsh\n\nset var {orange blue red green}\nset var [lsort $var]\nputs $var" }, { "code": null, "e": 5907, "s": 5839, "text": "When the above code is executed, it produces the following result βˆ’" } ]
Node.js fs.unlink() Method
08 Oct, 2021 The fs.unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.Syntax: fs.unlink( path, callback ) Parameters: This method accepts two parameters as mentioned above and described below: path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed. callback: It is a function that would be called when the method is executed. err: It is an error that would be thrown if the method fails. Below examples illustrate the fs.unlink() method in Node.js:Example 1: This example removes a file from the filesystem. javascript // Node.js program to demonstrate the// fs.unlink() method // Import the filesystem moduleconst fs = require('fs'); // Get the files in current directory// before deletiongetFilesInDirectory(); // Delete example_file.txtfs.unlink("example_file.txt", (err => { if (err) console.log(err); else { console.log("\nDeleted file: example_file.txt"); // Get the files in current directory // after deletion getFilesInDirectory(); }})); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log("\nFiles present in directory:"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });} Output: Files present in directory: example_file.txt index.js package.json Deleted file: example_file.txt Files present in directory: index.js package.json Example 2: This example removes a symbolic link from the filesystem. javascript // Node.js program to demonstrate the// fs.unlink() method // Import the filesystem moduleconst fs = require('fs'); // Creating symlink to filefs.symlinkSync(__dirname + "\\example_file.txt", "symlinkToFile");console.log("\nSymbolic link to example_file.txt created"); // Function to get current filenames// in directory with specific extensiongetFilesInDirectory(); // Deleting symbolic link to example_file.txt// Delete example_file.txtfs.unlink("symlinkToFile", (err => { if (err) console.log(err); else { console.log("\nDeleted Symbolic Link: symlinkToFile"); // Get the files in current directory // after deletion getFilesInDirectory(); }})); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log("\nFiles present in directory:"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });} Output: Symbolic link to example_file.txt created Files present in directory: example_file.txt index.js package.json symlinkToFile Deleted Symbolic Link: symlinkToFile Files present in directory: example_file.txt index.js package.json Reference: https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback simmytarika5 Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 235, "s": 28, "text": "The fs.unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.Syntax: " }, { "code": null, "e": 263, "s": 235, "text": "fs.unlink( path, callback )" }, { "code": null, "e": 351, "s": 263, "text": "Parameters: This method accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 455, "s": 351, "text": "path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed." }, { "code": null, "e": 533, "s": 455, "text": "callback: It is a function that would be called when the method is executed. " }, { "code": null, "e": 595, "s": 533, "text": "err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 715, "s": 595, "text": "Below examples illustrate the fs.unlink() method in Node.js:Example 1: This example removes a file from the filesystem." }, { "code": null, "e": 726, "s": 715, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.unlink() method // Import the filesystem moduleconst fs = require('fs'); // Get the files in current directory// before deletiongetFilesInDirectory(); // Delete example_file.txtfs.unlink(\"example_file.txt\", (err => { if (err) console.log(err); else { console.log(\"\\nDeleted file: example_file.txt\"); // Get the files in current directory // after deletion getFilesInDirectory(); }})); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log(\"\\nFiles present in directory:\"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });}", "e": 1423, "s": 726, "text": null }, { "code": null, "e": 1432, "s": 1423, "text": "Output: " }, { "code": null, "e": 1582, "s": 1432, "text": "Files present in directory:\nexample_file.txt\nindex.js\npackage.json\n\nDeleted file: example_file.txt\n\nFiles present in directory:\nindex.js\npackage.json" }, { "code": null, "e": 1651, "s": 1582, "text": "Example 2: This example removes a symbolic link from the filesystem." }, { "code": null, "e": 1662, "s": 1651, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.unlink() method // Import the filesystem moduleconst fs = require('fs'); // Creating symlink to filefs.symlinkSync(__dirname + \"\\\\example_file.txt\", \"symlinkToFile\");console.log(\"\\nSymbolic link to example_file.txt created\"); // Function to get current filenames// in directory with specific extensiongetFilesInDirectory(); // Deleting symbolic link to example_file.txt// Delete example_file.txtfs.unlink(\"symlinkToFile\", (err => { if (err) console.log(err); else { console.log(\"\\nDeleted Symbolic Link: symlinkToFile\"); // Get the files in current directory // after deletion getFilesInDirectory(); }})); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log(\"\\nFiles present in directory:\"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });}", "e": 2581, "s": 1662, "text": null }, { "code": null, "e": 2590, "s": 2581, "text": "Output: " }, { "code": null, "e": 2820, "s": 2590, "text": "Symbolic link to example_file.txt created\n\nFiles present in directory:\nexample_file.txt\nindex.js\npackage.json\nsymlinkToFile\n\nDeleted Symbolic Link: symlinkToFile\n\nFiles present in directory:\nexample_file.txt\nindex.js\npackage.json" }, { "code": null, "e": 2889, "s": 2820, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback" }, { "code": null, "e": 2902, "s": 2889, "text": "simmytarika5" }, { "code": null, "e": 2920, "s": 2902, "text": "Node.js-fs-module" }, { "code": null, "e": 2928, "s": 2920, "text": "Node.js" }, { "code": null, "e": 2945, "s": 2928, "text": "Web Technologies" }, { "code": null, "e": 3043, "s": 2945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3100, "s": 3043, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3154, "s": 3100, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3194, "s": 3154, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3226, "s": 3194, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3261, "s": 3226, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3323, "s": 3261, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3384, "s": 3323, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3434, "s": 3384, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3477, "s": 3434, "text": "How to fetch data from an API in ReactJS ?" } ]
How to take user input for two dimensional (2D) array in PHP ?
23 Dec, 2021 There are two methods to take user input in PHP in two dimensional (2D) array.Approach 1: Use HTML forms through PHP GET & POST method to take user input in two dimensional (2D) array. First, input data to HTML forms. Then use GET or POST method of PHP to get or post those input data into a variables. Finally, use those variable which holds input data and process using for loop. Though it is form two dimensional array so, you need two indices/variables for processing in for loop. Enter input one below another to state as two variables. Example 1: Below example illustrate how to input user data for 2D-array using Form POST method. php <?php echo "Enter n for nxn : <br>";echo "<form method='POST'> Row:<input type='number' min='2' max='5' name='1d' value='1'/> Column:<input type='number' min='2' max='5' name='2d' value='1'/> <input type='submit' name='submit' value='Submit'/></form>"; // Submit user input data for 2D arrayif (isset($_POST['submit'])) { // POST submitted data $dimention1 = $_POST["1d"]; // POST submitted data $dimention2 = $_POST["2d"]; echo "Entered 2d nxn: " . $dimention1 . "x" . $dimention2 . " <br>"; $d = []; $k = 0; for($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { $d[$row][$col]= $k++; } } for ($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { echo $d[$row][$col]." "; } echo "<br>"; }}?> Output: Approach 2: To take user input in php for two dimensional (2D) by using fopen() function which helps to get user input either at runtime or by external input file. First, assign those input data to variables. Finally, use those variable which holds input data and process using for loop. Though it is form two dimensional array so, you need two indices/variables for processing in for loop. Example: Below example illustrate how to input user data for 2D array using fopen() function. php <?php // fopen() using standard input$stdin = fopen('php://stdin', 'r');?><?phperror_reporting(0);echo "\n\n\nEnter row and column: \n"; // Right trim fgets(user input)$dimention1 = rtrim(fgets($stdin)); // Right trim fgets(user input)$dimention2 = rtrim(fgets($stdin)); echo "Entered row and column: " . $dimention1 . "x" . $dimention1 . " \n"; $d = [];$k = 0; for ($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { $d[$row][$col]= $k++; }} for ($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { echo $d[$row][$col]." "; } echo "\n";} ?> Output: Reference: https://www.geeksforgeeks.org/php-fopen-function-open-file-or-url/ khushboogoyal499 abhishek0719kadiyan PHP-Misc Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 119, "s": 28, "text": "There are two methods to take user input in PHP in two dimensional (2D) array.Approach 1: " }, { "code": null, "e": 214, "s": 119, "text": "Use HTML forms through PHP GET & POST method to take user input in two dimensional (2D) array." }, { "code": null, "e": 247, "s": 214, "text": "First, input data to HTML forms." }, { "code": null, "e": 332, "s": 247, "text": "Then use GET or POST method of PHP to get or post those input data into a variables." }, { "code": null, "e": 411, "s": 332, "text": "Finally, use those variable which holds input data and process using for loop." }, { "code": null, "e": 514, "s": 411, "text": "Though it is form two dimensional array so, you need two indices/variables for processing in for loop." }, { "code": null, "e": 571, "s": 514, "text": "Enter input one below another to state as two variables." }, { "code": null, "e": 667, "s": 571, "text": "Example 1: Below example illustrate how to input user data for 2D-array using Form POST method." }, { "code": null, "e": 671, "s": 667, "text": "php" }, { "code": "<?php echo \"Enter n for nxn : <br>\";echo \"<form method='POST'> Row:<input type='number' min='2' max='5' name='1d' value='1'/> Column:<input type='number' min='2' max='5' name='2d' value='1'/> <input type='submit' name='submit' value='Submit'/></form>\"; // Submit user input data for 2D arrayif (isset($_POST['submit'])) { // POST submitted data $dimention1 = $_POST[\"1d\"]; // POST submitted data $dimention2 = $_POST[\"2d\"]; echo \"Entered 2d nxn: \" . $dimention1 . \"x\" . $dimention2 . \" <br>\"; $d = []; $k = 0; for($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { $d[$row][$col]= $k++; } } for ($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { echo $d[$row][$col].\" \"; } echo \"<br>\"; }}?>", "e": 1599, "s": 671, "text": null }, { "code": null, "e": 1608, "s": 1599, "text": "Output: " }, { "code": null, "e": 1621, "s": 1608, "text": "Approach 2: " }, { "code": null, "e": 1773, "s": 1621, "text": "To take user input in php for two dimensional (2D) by using fopen() function which helps to get user input either at runtime or by external input file." }, { "code": null, "e": 1818, "s": 1773, "text": "First, assign those input data to variables." }, { "code": null, "e": 1897, "s": 1818, "text": "Finally, use those variable which holds input data and process using for loop." }, { "code": null, "e": 2000, "s": 1897, "text": "Though it is form two dimensional array so, you need two indices/variables for processing in for loop." }, { "code": null, "e": 2095, "s": 2000, "text": "Example: Below example illustrate how to input user data for 2D array using fopen() function. " }, { "code": null, "e": 2099, "s": 2095, "text": "php" }, { "code": "<?php // fopen() using standard input$stdin = fopen('php://stdin', 'r');?><?phperror_reporting(0);echo \"\\n\\n\\nEnter row and column: \\n\"; // Right trim fgets(user input)$dimention1 = rtrim(fgets($stdin)); // Right trim fgets(user input)$dimention2 = rtrim(fgets($stdin)); echo \"Entered row and column: \" . $dimention1 . \"x\" . $dimention1 . \" \\n\"; $d = [];$k = 0; for ($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { $d[$row][$col]= $k++; }} for ($row = 0; $row < $dimention1; $row++) { for ($col = 0; $col < $dimention2; $col++) { echo $d[$row][$col].\" \"; } echo \"\\n\";} ?>", "e": 2740, "s": 2099, "text": null }, { "code": null, "e": 2749, "s": 2740, "text": "Output: " }, { "code": null, "e": 2828, "s": 2749, "text": "Reference: https://www.geeksforgeeks.org/php-fopen-function-open-file-or-url/ " }, { "code": null, "e": 2845, "s": 2828, "text": "khushboogoyal499" }, { "code": null, "e": 2865, "s": 2845, "text": "abhishek0719kadiyan" }, { "code": null, "e": 2874, "s": 2865, "text": "PHP-Misc" }, { "code": null, "e": 2881, "s": 2874, "text": "Picked" }, { "code": null, "e": 2885, "s": 2881, "text": "PHP" }, { "code": null, "e": 2902, "s": 2885, "text": "Web Technologies" }, { "code": null, "e": 2929, "s": 2902, "text": "Web technologies Questions" }, { "code": null, "e": 2933, "s": 2929, "text": "PHP" } ]