title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C# ToLower() Method
The ToLower() method in C# is used to return a copy of this string converted to lowercase. The syntax is as follows - public string ToLower (); Let us now see an example - Live Demo using System; public class Demo { public static void Main(String[] args) { string str1 = "WELCOME!"; string str2 = "Thisisit!"; char[] arr1 = str1.ToCharArray(3,2); char[] arr2 = str2.ToCharArray(2,2); Console.WriteLine("String1 = "+str1); Console.WriteLine("String1 ToLower = "+str1.ToLower()); Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4, 4)); Console.Write("Character array...String1 ="); for (int i = 0; i < arr1.Length; i++) Console.Write(" " + arr1[i]); Console.WriteLine("\n\nString2 = "+str2); Console.WriteLine("String2 ToLower = "+str2.ToLower()); Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5)); Console.Write("Character array...String2 ="); for (int i = 0; i < arr2.Length; i++) Console.Write(" " + arr2[i]); } } String1 = WELCOME! String1 ToLower = welcome! String1 Substring from index4 = OME! Character array...String1 = C O String2 = Thisisit! String2 ToLower = thisisit! String2 Substring from index2 = Thisi Character array...String2 = i s Let us now see another example - Live Demo using System; using System.Globalization; public class Demo { public static void Main(String[] args) { string str1 = "ABCD!"; string str2 = "@#$PQRSTUV!"; Console.WriteLine("String1 = "+str1); Console.WriteLine("String1 ToLower = "+str1.ToLower(new CultureInfo("en-US", false))); Console.WriteLine("String1 Substring from index4 = " + str1.Substring(2, 2)); Console.WriteLine("\n\nString2 = "+str2); Console.WriteLine("String2 ToLower = "+str2.ToLower(new CultureInfo("en-US", false))); Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5)); } } String1 = ABCD! String1 ToLower = abcd! String1 Substring from index4 = CD String2 = @#$PQRSTUV! String2 ToLower = @#$pqrstuv! String2 Substring from index2 = @#$PQ
[ { "code": null, "e": 1153, "s": 1062, "text": "The ToLower() method in C# is used to return a copy of this string converted to lowercase." }, { "code": null, "e": 1180, "s": 1153, "text": "The syntax is as follows -" }, { "code": null, "e": 1206, "s": 1180, "text": "public string ToLower ();" }, { "code": null, "e": 1234, "s": 1206, "text": "Let us now see an example -" }, { "code": null, "e": 1245, "s": 1234, "text": " Live Demo" }, { "code": null, "e": 2135, "s": 1245, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"WELCOME!\";\n string str2 = \"Thisisit!\";\n char[] arr1 = str1.ToCharArray(3,2);\n char[] arr2 = str2.ToCharArray(2,2);\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String1 ToLower = \"+str1.ToLower());\n Console.WriteLine(\"String1 Substring from index4 = \" + str1.Substring(4, 4));\n Console.Write(\"Character array...String1 =\");\n for (int i = 0; i < arr1.Length; i++)\n Console.Write(\" \" + arr1[i]);\n Console.WriteLine(\"\\n\\nString2 = \"+str2);\n Console.WriteLine(\"String2 ToLower = \"+str2.ToLower());\n Console.WriteLine(\"String2 Substring from index2 = \" + str2.Substring(0, 5));\n Console.Write(\"Character array...String2 =\");\n for (int i = 0; i < arr2.Length; i++)\n Console.Write(\" \" + arr2[i]);\n }\n}" }, { "code": null, "e": 2368, "s": 2135, "text": "String1 = WELCOME!\nString1 ToLower = welcome!\nString1 Substring from index4 = OME!\nCharacter array...String1 = C O\nString2 = Thisisit!\nString2 ToLower = thisisit!\nString2 Substring from index2 = Thisi\nCharacter array...String2 = i s" }, { "code": null, "e": 2401, "s": 2368, "text": "Let us now see another example -" }, { "code": null, "e": 2412, "s": 2401, "text": " Live Demo" }, { "code": null, "e": 3035, "s": 2412, "text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"ABCD!\";\n string str2 = \"@#$PQRSTUV!\";\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String1 ToLower = \"+str1.ToLower(new CultureInfo(\"en-US\", false)));\n Console.WriteLine(\"String1 Substring from index4 = \" + str1.Substring(2, 2));\n Console.WriteLine(\"\\n\\nString2 = \"+str2);\n Console.WriteLine(\"String2 ToLower = \"+str2.ToLower(new CultureInfo(\"en-US\", false)));\n Console.WriteLine(\"String2 Substring from index2 = \" + str2.Substring(0, 5));\n }\n}" }, { "code": null, "e": 3200, "s": 3035, "text": "String1 = ABCD!\nString1 ToLower = abcd!\nString1 Substring from index4 = CD\nString2 = @#$PQRSTUV!\nString2 ToLower = @#$pqrstuv!\nString2 Substring from index2 = @#$PQ" } ]
Program to print triangular number series till n - GeeksforGeeks
19 Mar, 2021 A triangular number or triangle number counts objects arranged in an equilateral triangle, as in the diagram on the right. The n-th triangular number is the number of dots composing a triangle with n dots on a side, and is equal to the sum of the n natural numbers from 1 to n. Examples : Input : 5 Output : 1 3 6 10 15 Input : 10 Output : 1 3 6 10 15 21 28 36 45 55 Explanation : For k = 1 and j = 1 -> print k ( i.e. 1); increase j by 1 and add into k then print k ( i.e 3 ) update k increase j by 1 and add into k then print k ( i.e 6 ) update k increase j by 1 and add into k then print k ( i.e 10 ) update k increase j by 1 and add into k then print k ( i.e 15 ) update k increase j by 1 and add into k then print k ( i.e 21 ) update k . . and so on. Approach used is very simple. Iterate for loop till the value given n and for each iteration increase j by 1 and add it into k, which will simply print the triangular number series till n. Below is the program implementing above approach: C Java Python3 C# PHP Javascript // C Program to find Triangular Number Series#include <stdio.h> // Function to find triangular numbervoid triangular_series(int n){ int i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { printf(" %d ", k); j = j + 1; // Increasing j by 1 k = k + j; // Add value of j into k and update k }}// Driven Functionint main(){ int n = 5; triangular_series(n); return 0;} // Java Program to print triangular number series till nimport java.util.*; class GFG { // Function to find triangular number static void triangular_series(int n) { int i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { System.out.printf("%d ", k); j = j + 1; // Increasing j by 1 k = k + j; // Add value of j into k and update k } } // Driver function public static void main(String[] args) { int n = 5; triangular_series(n); }} // This code is contributed by Arnav Kr. Mandal. # Python3 code to find Triangular# Number Series # Function to find triangular numberdef triangular_series( n ): j = 1 k = 1 # For each iteration increase j # by 1 and add it into k for i in range(1, n + 1): print(k, end = ' ') j = j + 1 # Increasing j by 1 # Add value of j into k and update k k = k + j # Driven Coden = 5triangular_series(n) # This code is contributed by "Sharad_Bhardwaj" // C# Program to print triangular// number series till nusing System; class GFG { // Function to find triangular number static void triangular_series(int n) { int i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { Console.Write(k +" "); j += 1; // Increasing j by 1 k += j; // Add value of j into k and update k } } // Driver Code public static void Main() { int n = 5; triangular_series(n); }} // This code is contributed by vt_m. <?php// PHP Program to find// Triangular Number Series // Function to find// triangular numberfunction triangular_series($n){ $i; $j = 1; $k = 1; // For each iteration increase j // by 1 and add it into k for ($i = 1; $i <= $n; $i++) { echo(" " . $k . " "); // Increasing j by 1 $j = $j + 1; // Add value of j into k and update k $k = $k + $j; }} // Driver Code$n = 5;triangular_series($n); // This code is contributed by Ajit.?> <script>// javascript Program to find Triangular Number Series // Function to find triangular numberfunction triangular_series( n){ let i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { document.write(k+" "); j = j + 1; // Increasing j by 1 k = k + j; // Add value of j into k and update k }} // Driven Function let n = 5; triangular_series(n); // This code is contributed by Rajput-Ji </script> Output : 1 3 6 10 15 Alternate Solution : The solution is based on the fact that i-th Triangular number is sum of first i natural numbers, i.e., i * (i + 1)/2 C Java Python3 C# PHP Javascript // C Program to find Triangular Number Series#include <stdio.h> // Function to find triangular numbervoid triangular_series(int n){ for (int i = 1; i <= n; i++) printf(" %d ", i*(i+1)/2);} // Driven Functionint main(){ int n = 5; triangular_series(n); return 0;} //Java program to print triangular number series till nimport java.util.*; class GFG { // Function to find triangular number static void triangular_series(int n) { for (int i = 1; i <= n; i++) System.out.printf("%d ";, i*(i+1)/2); } // Driver function public static void main(String[] args) { int n = 5; triangular_series(n); }} //This code is contributed by Arnav Kr. Mandal. # Python3 code to find Triangular# Number Series def triangular_series(n): for i in range(1, n + 1): print( i*(i+1)//2,end=' ') # Driver coden = 5triangular_series(n)# This code is contributed by ihritik // C# program to print triangular// number series till nusing System; class GFG { // Function to find triangular number static void triangular_series(int n) { for (int i = 1; i <= n; i++) Console.Write(i * (i + 1) / 2 + " "); } // Driver Code public static void Main() { int n = 5; triangular_series(n); }} // This code is contributed by vt_m. <?php// PHP Program to find// Triangular Number Series // Function to find// triangular numberfunction triangular_series($n){ for ($i = 1; $i <= $n; $i++) echo(" " . $i * ($i + 1) / 2 . " ");} // Driver Code$n = 5;triangular_series($n); // This code is contributed by Ajit.?> <script>// javascript Program to find Triangular Number Series // Function to find triangular numberfunction triangular_series( n){ for (let i = 1; i <= n; i++) document.write(" "+ i * (i + 1)/2);} // Driven Function let n = 5; triangular_series(n); // This code is contributed by gauravrajput1</script> Output : 1 3 6 10 15 jit_t ihritik Rajput-Ji GauravRajput1 series triangular-number Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Euclidean algorithms (Basic and Extended) Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n Efficient program to print all prime factors of a given number The Knight's tour problem | Backtracking-1 Minimum number of jumps to reach end
[ { "code": null, "e": 25259, "s": 25231, "text": "\n19 Mar, 2021" }, { "code": null, "e": 25538, "s": 25259, "text": "A triangular number or triangle number counts objects arranged in an equilateral triangle, as in the diagram on the right. The n-th triangular number is the number of dots composing a triangle with n dots on a side, and is equal to the sum of the n natural numbers from 1 to n. " }, { "code": null, "e": 25551, "s": 25538, "text": "Examples : " }, { "code": null, "e": 26024, "s": 25551, "text": "Input : 5\nOutput : 1 3 6 10 15\n\nInput : 10 \nOutput : 1 3 6 10 15 21 28 36 45 55\n\nExplanation :\nFor k = 1 and j = 1 -> print k ( i.e. 1);\nincrease j by 1 and add into k then print k ( i.e 3 ) update k\nincrease j by 1 and add into k then print k ( i.e 6 ) update k\nincrease j by 1 and add into k then print k ( i.e 10 ) update k \nincrease j by 1 and add into k then print k ( i.e 15 ) update k\nincrease j by 1 and add into k then print k ( i.e 21 ) update k\n.\n.\nand so on." }, { "code": null, "e": 26267, "s": 26026, "text": "Approach used is very simple. Iterate for loop till the value given n and for each iteration increase j by 1 and add it into k, which will simply print the triangular number series till n. Below is the program implementing above approach: " }, { "code": null, "e": 26269, "s": 26267, "text": "C" }, { "code": null, "e": 26274, "s": 26269, "text": "Java" }, { "code": null, "e": 26282, "s": 26274, "text": "Python3" }, { "code": null, "e": 26285, "s": 26282, "text": "C#" }, { "code": null, "e": 26289, "s": 26285, "text": "PHP" }, { "code": null, "e": 26300, "s": 26289, "text": "Javascript" }, { "code": "// C Program to find Triangular Number Series#include <stdio.h> // Function to find triangular numbervoid triangular_series(int n){ int i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { printf(\" %d \", k); j = j + 1; // Increasing j by 1 k = k + j; // Add value of j into k and update k }}// Driven Functionint main(){ int n = 5; triangular_series(n); return 0;}", "e": 26761, "s": 26300, "text": null }, { "code": "// Java Program to print triangular number series till nimport java.util.*; class GFG { // Function to find triangular number static void triangular_series(int n) { int i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { System.out.printf(\"%d \", k); j = j + 1; // Increasing j by 1 k = k + j; // Add value of j into k and update k } } // Driver function public static void main(String[] args) { int n = 5; triangular_series(n); }} // This code is contributed by Arnav Kr. Mandal.", "e": 27431, "s": 26761, "text": null }, { "code": "# Python3 code to find Triangular# Number Series # Function to find triangular numberdef triangular_series( n ): j = 1 k = 1 # For each iteration increase j # by 1 and add it into k for i in range(1, n + 1): print(k, end = ' ') j = j + 1 # Increasing j by 1 # Add value of j into k and update k k = k + j # Driven Coden = 5triangular_series(n) # This code is contributed by \"Sharad_Bhardwaj\"", "e": 27888, "s": 27431, "text": null }, { "code": "// C# Program to print triangular// number series till nusing System; class GFG { // Function to find triangular number static void triangular_series(int n) { int i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { Console.Write(k +\" \"); j += 1; // Increasing j by 1 k += j; // Add value of j into k and update k } } // Driver Code public static void Main() { int n = 5; triangular_series(n); }} // This code is contributed by vt_m.", "e": 28510, "s": 27888, "text": null }, { "code": "<?php// PHP Program to find// Triangular Number Series // Function to find// triangular numberfunction triangular_series($n){ $i; $j = 1; $k = 1; // For each iteration increase j // by 1 and add it into k for ($i = 1; $i <= $n; $i++) { echo(\" \" . $k . \" \"); // Increasing j by 1 $j = $j + 1; // Add value of j into k and update k $k = $k + $j; }} // Driver Code$n = 5;triangular_series($n); // This code is contributed by Ajit.?>", "e": 29012, "s": 28510, "text": null }, { "code": "<script>// javascript Program to find Triangular Number Series // Function to find triangular numberfunction triangular_series( n){ let i, j = 1, k = 1; // For each iteration increase j by 1 // and add it into k for (i = 1; i <= n; i++) { document.write(k+\" \"); j = j + 1; // Increasing j by 1 k = k + j; // Add value of j into k and update k }} // Driven Function let n = 5; triangular_series(n); // This code is contributed by Rajput-Ji </script>", "e": 29514, "s": 29012, "text": null }, { "code": null, "e": 29525, "s": 29514, "text": "Output : " }, { "code": null, "e": 29537, "s": 29525, "text": "1 3 6 10 15" }, { "code": null, "e": 29676, "s": 29537, "text": "Alternate Solution : The solution is based on the fact that i-th Triangular number is sum of first i natural numbers, i.e., i * (i + 1)/2 " }, { "code": null, "e": 29678, "s": 29676, "text": "C" }, { "code": null, "e": 29683, "s": 29678, "text": "Java" }, { "code": null, "e": 29691, "s": 29683, "text": "Python3" }, { "code": null, "e": 29694, "s": 29691, "text": "C#" }, { "code": null, "e": 29698, "s": 29694, "text": "PHP" }, { "code": null, "e": 29709, "s": 29698, "text": "Javascript" }, { "code": "// C Program to find Triangular Number Series#include <stdio.h> // Function to find triangular numbervoid triangular_series(int n){ for (int i = 1; i <= n; i++) printf(\" %d \", i*(i+1)/2);} // Driven Functionint main(){ int n = 5; triangular_series(n); return 0;}", "e": 29991, "s": 29709, "text": null }, { "code": "//Java program to print triangular number series till nimport java.util.*; class GFG { // Function to find triangular number static void triangular_series(int n) { for (int i = 1; i <= n; i++) System.out.printf(\"%d \";, i*(i+1)/2); } // Driver function public static void main(String[] args) { int n = 5; triangular_series(n); }} //This code is contributed by Arnav Kr. Mandal.", "e": 30450, "s": 29991, "text": null }, { "code": "# Python3 code to find Triangular# Number Series def triangular_series(n): for i in range(1, n + 1): print( i*(i+1)//2,end=' ') # Driver coden = 5triangular_series(n)# This code is contributed by ihritik", "e": 30670, "s": 30450, "text": null }, { "code": "// C# program to print triangular// number series till nusing System; class GFG { // Function to find triangular number static void triangular_series(int n) { for (int i = 1; i <= n; i++) Console.Write(i * (i + 1) / 2 + \" \"); } // Driver Code public static void Main() { int n = 5; triangular_series(n); }} // This code is contributed by vt_m.", "e": 31096, "s": 30670, "text": null }, { "code": "<?php// PHP Program to find// Triangular Number Series // Function to find// triangular numberfunction triangular_series($n){ for ($i = 1; $i <= $n; $i++) echo(\" \" . $i * ($i + 1) / 2 . \" \");} // Driver Code$n = 5;triangular_series($n); // This code is contributed by Ajit.?>", "e": 31406, "s": 31096, "text": null }, { "code": "<script>// javascript Program to find Triangular Number Series // Function to find triangular numberfunction triangular_series( n){ for (let i = 1; i <= n; i++) document.write(\" \"+ i * (i + 1)/2);} // Driven Function let n = 5; triangular_series(n); // This code is contributed by gauravrajput1</script>", "e": 31733, "s": 31406, "text": null }, { "code": null, "e": 31744, "s": 31733, "text": "Output : " }, { "code": null, "e": 31756, "s": 31744, "text": "1 3 6 10 15" }, { "code": null, "e": 31764, "s": 31758, "text": "jit_t" }, { "code": null, "e": 31772, "s": 31764, "text": "ihritik" }, { "code": null, "e": 31782, "s": 31772, "text": "Rajput-Ji" }, { "code": null, "e": 31796, "s": 31782, "text": "GauravRajput1" }, { "code": null, "e": 31803, "s": 31796, "text": "series" }, { "code": null, "e": 31821, "s": 31803, "text": "triangular-number" }, { "code": null, "e": 31834, "s": 31821, "text": "Mathematical" }, { "code": null, "e": 31847, "s": 31834, "text": "Mathematical" }, { "code": null, "e": 31854, "s": 31847, "text": "series" }, { "code": null, "e": 31952, "s": 31854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31961, "s": 31952, "text": "Comments" }, { "code": null, "e": 31974, "s": 31961, "text": "Old Comments" }, { "code": null, "e": 32017, "s": 31974, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32066, "s": 32017, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32087, "s": 32066, "text": "Operators in C / C++" }, { "code": null, "e": 32121, "s": 32087, "text": "Program for factorial of a number" }, { "code": null, "e": 32163, "s": 32121, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 32195, "s": 32163, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 32268, "s": 32195, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32331, "s": 32268, "text": "Efficient program to print all prime factors of a given number" }, { "code": null, "e": 32374, "s": 32331, "text": "The Knight's tour problem | Backtracking-1" } ]
TimeSpan.FromDays() Method in C#
The TimeSpan.FromDays() method in C# is used to return a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond. The syntax is as follows − public static TimeSpan FromDays (double val); Above, the parameter val is the number of days, accurate to the nearest millisecond. Let us now see an example − Live Demo using System; public class Demo { public static void Main(){ TimeSpan span1 = new TimeSpan(5, 25, 0); TimeSpan span2 = new TimeSpan(1, 10, 0); TimeSpan span3 = TimeSpan.FromDays(43.999999); Console.WriteLine("TimeSpan1 = "+span1); Console.WriteLine("TimeSpan2 = "+span2); Console.WriteLine("TimeSpan3 = "+span3); Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2)); } } This will produce the following output − TimeSpan1 = 05:25:00 TimeSpan2 = 01:10:00 TimeSpan3 = 43.23:59:59.9140000 Result (Comparison of span1 and span2) = 1 Let us now see another example − Live Demo using System; public class Demo { public static void Main(){ TimeSpan span1 = new TimeSpan(-3, 15, 0); TimeSpan span2 = new TimeSpan(-2, 05, 10); TimeSpan span3 = TimeSpan.FromDays(0.000323456); Console.WriteLine("TimeSpan1 = "+span1); Console.WriteLine("TimeSpan2 = "+span2); Console.WriteLine("TimeSpan3 = "+span3); Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2)); Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3)); } } This will produce the following output − TimeSpan1 = -02:45:00 TimeSpan2 = -01:54:50 TimeSpan3 = 00:00:27.9470000 Result (Comparison of span1 and span2) = -1 Result (Comparison of span2 and span3) = -1
[ { "code": null, "e": 1236, "s": 1062, "text": "The TimeSpan.FromDays() method in C# is used to return a TimeSpan that\nrepresents a specified number of days, where the specification is accurate to the nearest millisecond." }, { "code": null, "e": 1263, "s": 1236, "text": "The syntax is as follows −" }, { "code": null, "e": 1309, "s": 1263, "text": "public static TimeSpan FromDays (double val);" }, { "code": null, "e": 1394, "s": 1309, "text": "Above, the parameter val is the number of days, accurate to the nearest\nmillisecond." }, { "code": null, "e": 1422, "s": 1394, "text": "Let us now see an example −" }, { "code": null, "e": 1433, "s": 1422, "text": " Live Demo" }, { "code": null, "e": 1893, "s": 1433, "text": "using System;\npublic class Demo {\n public static void Main(){\n TimeSpan span1 = new TimeSpan(5, 25, 0);\n TimeSpan span2 = new TimeSpan(1, 10, 0);\n TimeSpan span3 = TimeSpan.FromDays(43.999999);\n Console.WriteLine(\"TimeSpan1 = \"+span1);\n Console.WriteLine(\"TimeSpan2 = \"+span2);\n Console.WriteLine(\"TimeSpan3 = \"+span3);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n }\n}" }, { "code": null, "e": 1934, "s": 1893, "text": "This will produce the following output −" }, { "code": null, "e": 2051, "s": 1934, "text": "TimeSpan1 = 05:25:00\nTimeSpan2 = 01:10:00\nTimeSpan3 = 43.23:59:59.9140000\nResult (Comparison of span1 and span2) = 1" }, { "code": null, "e": 2084, "s": 2051, "text": "Let us now see another example −" }, { "code": null, "e": 2095, "s": 2084, "text": " Live Demo" }, { "code": null, "e": 2661, "s": 2095, "text": "using System;\npublic class Demo {\n public static void Main(){\n TimeSpan span1 = new TimeSpan(-3, 15, 0);\n TimeSpan span2 = new TimeSpan(-2, 05, 10);\n TimeSpan span3 = TimeSpan.FromDays(0.000323456);\n Console.WriteLine(\"TimeSpan1 = \"+span1);\n Console.WriteLine(\"TimeSpan2 = \"+span2);\n Console.WriteLine(\"TimeSpan3 = \"+span3);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n Console.WriteLine(\"Result (Comparison of span2 and span3) = \"+TimeSpan.Compare(span2, span3));\n }\n}" }, { "code": null, "e": 2702, "s": 2661, "text": "This will produce the following output −" }, { "code": null, "e": 2863, "s": 2702, "text": "TimeSpan1 = -02:45:00\nTimeSpan2 = -01:54:50\nTimeSpan3 = 00:00:27.9470000\nResult (Comparison of span1 and span2) = -1\nResult (Comparison of span2 and span3) = -1" } ]
ZoneOffset of(String) method in Java with Examples - GeeksforGeeks
11 Dec, 2018 The of(String) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offsetId passed as the parameter. This method takes the offsetId as parameter in the form of String and converts it into the ZoneOffset. The ID of the returned offset will be normalized to one of the formats described by getId().The list of String offsetId accepted by this method are as follows: Z – for UTC +h +hh +hh:mm -hh:mm +hhmm -hhmm +hh:mm:ss -hh:mm:ss +hhmmss -hhmmssNote: ± means either the plus or minus symbol. And the maximum supported range is from +18:00 to -18:00 inclusive.Syntax:public static ZoneOffset of(String offsetId) Parameters: This method accepts a parameter offsetId which is String to be parsed into an ZoneOffset instance.Return Value: This method returns a ZoneOffset instance parsed from the specified offsetId.Exception: This method throws DateTimeException if the offset ID is invalid.Below examples illustrate the ZoneOffset.of() method:Example 1:// Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the offset ID String offsetId = "Z"; // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); System.out.println(zoneOffset); }}Output:Z Example 2: To demonstrate DateTimeException// Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the invalid offset ID String offsetId = "10:10"; try { // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); } catch (Exception e) { System.out.println(e); } }}Output:java.time.DateTimeException: Invalid ID for ZoneOffset, non numeric characters found: 10:10 Reference: Oracle DocMy Personal Notes arrow_drop_upSave Note: ± means either the plus or minus symbol. And the maximum supported range is from +18:00 to -18:00 inclusive. Syntax: public static ZoneOffset of(String offsetId) Parameters: This method accepts a parameter offsetId which is String to be parsed into an ZoneOffset instance. Return Value: This method returns a ZoneOffset instance parsed from the specified offsetId. Exception: This method throws DateTimeException if the offset ID is invalid. Below examples illustrate the ZoneOffset.of() method: Example 1: // Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the offset ID String offsetId = "Z"; // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); System.out.println(zoneOffset); }} Z Example 2: To demonstrate DateTimeException // Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the invalid offset ID String offsetId = "10:10"; try { // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); } catch (Exception e) { System.out.println(e); } }} java.time.DateTimeException: Invalid ID for ZoneOffset, non numeric characters found: 10:10 Reference: Oracle Doc Java-Functions Java-time package Java-ZoneOffset Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java
[ { "code": null, "e": 24850, "s": 24822, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25264, "s": 24850, "text": "The of(String) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offsetId passed as the parameter. This method takes the offsetId as parameter in the form of String and converts it into the ZoneOffset. The ID of the returned offset will be normalized to one of the formats described by getId().The list of String offsetId accepted by this method are as follows:" }, { "code": null, "e": 25276, "s": 25264, "text": "Z – for UTC" }, { "code": null, "e": 25279, "s": 25276, "text": "+h" }, { "code": null, "e": 25283, "s": 25279, "text": "+hh" }, { "code": null, "e": 25290, "s": 25283, "text": "+hh:mm" }, { "code": null, "e": 25297, "s": 25290, "text": "-hh:mm" }, { "code": null, "e": 25303, "s": 25297, "text": "+hhmm" }, { "code": null, "e": 25309, "s": 25303, "text": "-hhmm" }, { "code": null, "e": 25319, "s": 25309, "text": "+hh:mm:ss" }, { "code": null, "e": 25329, "s": 25319, "text": "-hh:mm:ss" }, { "code": null, "e": 25337, "s": 25329, "text": "+hhmmss" }, { "code": null, "e": 26819, "s": 25337, "text": "-hhmmssNote: ± means either the plus or minus symbol. And the maximum supported range is from +18:00 to -18:00 inclusive.Syntax:public static ZoneOffset of(String offsetId)\nParameters: This method accepts a parameter offsetId which is String to be parsed into an ZoneOffset instance.Return Value: This method returns a ZoneOffset instance parsed from the specified offsetId.Exception: This method throws DateTimeException if the offset ID is invalid.Below examples illustrate the ZoneOffset.of() method:Example 1:// Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the offset ID String offsetId = \"Z\"; // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); System.out.println(zoneOffset); }}Output:Z\nExample 2: To demonstrate DateTimeException// Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the invalid offset ID String offsetId = \"10:10\"; try { // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); } catch (Exception e) { System.out.println(e); } }}Output:java.time.DateTimeException: Invalid ID for ZoneOffset, non numeric characters found: 10:10\nReference: Oracle DocMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26934, "s": 26819, "text": "Note: ± means either the plus or minus symbol. And the maximum supported range is from +18:00 to -18:00 inclusive." }, { "code": null, "e": 26942, "s": 26934, "text": "Syntax:" }, { "code": null, "e": 26988, "s": 26942, "text": "public static ZoneOffset of(String offsetId)\n" }, { "code": null, "e": 27099, "s": 26988, "text": "Parameters: This method accepts a parameter offsetId which is String to be parsed into an ZoneOffset instance." }, { "code": null, "e": 27191, "s": 27099, "text": "Return Value: This method returns a ZoneOffset instance parsed from the specified offsetId." }, { "code": null, "e": 27268, "s": 27191, "text": "Exception: This method throws DateTimeException if the offset ID is invalid." }, { "code": null, "e": 27322, "s": 27268, "text": "Below examples illustrate the ZoneOffset.of() method:" }, { "code": null, "e": 27333, "s": 27322, "text": "Example 1:" }, { "code": "// Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the offset ID String offsetId = \"Z\"; // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); System.out.println(zoneOffset); }}", "e": 27675, "s": 27333, "text": null }, { "code": null, "e": 27678, "s": 27675, "text": "Z\n" }, { "code": null, "e": 27722, "s": 27678, "text": "Example 2: To demonstrate DateTimeException" }, { "code": "// Java code to illustrate of() method import java.time.*; public class GFG { public static void main(String[] args) { // Get the invalid offset ID String offsetId = \"10:10\"; try { // ZoneOffset using of() method ZoneOffset zoneOffset = ZoneOffset.of(offsetId); } catch (Exception e) { System.out.println(e); } }}", "e": 28143, "s": 27722, "text": null }, { "code": null, "e": 28236, "s": 28143, "text": "java.time.DateTimeException: Invalid ID for ZoneOffset, non numeric characters found: 10:10\n" }, { "code": null, "e": 28258, "s": 28236, "text": "Reference: Oracle Doc" }, { "code": null, "e": 28273, "s": 28258, "text": "Java-Functions" }, { "code": null, "e": 28291, "s": 28273, "text": "Java-time package" }, { "code": null, "e": 28307, "s": 28291, "text": "Java-ZoneOffset" }, { "code": null, "e": 28312, "s": 28307, "text": "Java" }, { "code": null, "e": 28317, "s": 28312, "text": "Java" }, { "code": null, "e": 28415, "s": 28317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28424, "s": 28415, "text": "Comments" }, { "code": null, "e": 28437, "s": 28424, "text": "Old Comments" }, { "code": null, "e": 28467, "s": 28437, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28486, "s": 28467, "text": "Interfaces in Java" }, { "code": null, "e": 28537, "s": 28486, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28555, "s": 28537, "text": "ArrayList in Java" }, { "code": null, "e": 28586, "s": 28555, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28618, "s": 28586, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28642, "s": 28618, "text": "Singleton Class in Java" }, { "code": null, "e": 28661, "s": 28642, "text": "Overriding in Java" }, { "code": null, "e": 28681, "s": 28661, "text": "Collections in Java" } ]
pulseIn() and pulseInLong() in Arduino
If there is an incoming pulse on a pin, and you need to measure the duration of the pulse then the pulseIn() function comes in handy. The syntax is − pulseIn(pin, value) Where pin is the number of the pin on which you wish to measure the pulse. The value is the level of the pulse. It can be HIGH or LOW. For example, if you set the value to HIGH, it means that as soon as the voltage on the pin goes from LOW to HIGH, the measurement of the time will start. It will stop when the voltage on the pin goes from HIGH to LOW. The pin returns the time of the pulse in microseconds. You can also use an alternate form of the function, which takes in a 3rd argument: timeout pulseIn(pin, value, timeout) The timeout indicates the number of microseconds to wait for the pulse to start. If you don’t specify this argument, the default timeout is 1 second. In other words, if, after the call to the pulseIn function, the pulse doesn’t start within 1 second (or timeout), this function will give up and return 0. If you have a very long pulse that needs to be measured, and have interrupts enabled in your code, you could use pulseInLong() instead of pulseIn. The syntax is similar, and the timeout argument is optional over here as well. This function can be used for measuring pulses from 10 microseconds to 3 minutes in length, and can be used only if interrupts are enabled.It is prone to errors for shorter pulses and gives the highest resolution for larger pulses. An example implementation is given below − int pulsePin = 6; unsigned long pulseDuration; void setup() { Serial.begin(9600); pinMode(pulsePin, INPUT); } void loop() { pulseDuration = pulseIn(pulsePin, HIGH); Serial.println(pulseDuration); } The syntax for pulseInLong remains the same; only the function name changes from pulseIn() to pulseInLong().
[ { "code": null, "e": 1196, "s": 1062, "text": "If there is an incoming pulse on a pin, and you need to measure the duration of the pulse then the pulseIn() function comes in handy." }, { "code": null, "e": 1212, "s": 1196, "text": "The syntax is −" }, { "code": null, "e": 1232, "s": 1212, "text": "pulseIn(pin, value)" }, { "code": null, "e": 1367, "s": 1232, "text": "Where pin is the number of the pin on which you wish to measure the pulse. The value is the level of the pulse. It can be HIGH or LOW." }, { "code": null, "e": 1585, "s": 1367, "text": "For example, if you set the value to HIGH, it means that as soon as the voltage on the pin goes from LOW to HIGH, the measurement of the time will start. It will stop when the voltage on the pin goes from HIGH to LOW." }, { "code": null, "e": 1640, "s": 1585, "text": "The pin returns the time of the pulse in microseconds." }, { "code": null, "e": 1731, "s": 1640, "text": "You can also use an alternate form of the function, which takes in a 3rd argument: timeout" }, { "code": null, "e": 1760, "s": 1731, "text": "pulseIn(pin, value, timeout)" }, { "code": null, "e": 2065, "s": 1760, "text": "The timeout indicates the number of microseconds to wait for the pulse to start. If you don’t specify this argument, the default timeout is 1 second. In other words, if, after the call to the pulseIn function, the pulse doesn’t start within 1 second (or timeout), this function will give up and return 0." }, { "code": null, "e": 2523, "s": 2065, "text": "If you have a very long pulse that needs to be measured, and have interrupts enabled in your code, you could use pulseInLong() instead of pulseIn. The syntax is similar, and the timeout argument is optional over here as well. This function can be used for measuring pulses from 10 microseconds to 3 minutes in length, and can be used only if interrupts are enabled.It is prone to errors for shorter pulses and gives the highest resolution for larger pulses." }, { "code": null, "e": 2566, "s": 2523, "text": "An example implementation is given below −" }, { "code": null, "e": 2777, "s": 2566, "text": "int pulsePin = 6;\nunsigned long pulseDuration;\n\nvoid setup() {\n Serial.begin(9600);\n pinMode(pulsePin, INPUT);\n}\nvoid loop() {\n pulseDuration = pulseIn(pulsePin, HIGH);\n Serial.println(pulseDuration);\n}" }, { "code": null, "e": 2886, "s": 2777, "text": "The syntax for pulseInLong remains the same; only the function name changes from pulseIn() to pulseInLong()." } ]
Python program to multiply all numbers in the list?
First we create 3 list for user input .here we use traversing technique. Initializing the value of product to 1, traverse all the element and multiply every number with the product one by one till the end of list. Input: A=[5,6,3] Output:90 Explanation:5*6*3 Step 1: input all numbers in the list (lst). Step 2: to multiply all values in the list we use traversing technique. Step 3: variable X=1. Step 4: for i in LST /*traverse from first to last in the list X=X*i /* multiply elements one by one Step 5: display X #To multiply all numbers in a list def mulallnum(lst): x=1 for i in lst: x=x*i return x #driver code A=list() B=list() C=list() n1=int(input("Enter the size of the First List ::")) n2=int(input("Enter the size of the Second List ::")) n3=int(input("Enter the size of the Third List ::")) print("Enter the Element of First List ::") for i in range(int(n1)): k=int(input("")) A.append(k) print("Enter the Element of Second List ::") for j in range(int(n2)): k1=int(input("")) B.append(k1) print("Enter the Element of Third List ::") for j in range(int(n3)): k1=int(input("")) C.append(k1) print("MULTIPLY OF ALL NUMBERS IN FIRST LIST ::>",mulallnum(A)) print("MULTIPLY OF ALL NUMBERS IN SECOND LIST ::>",mulallnum(B)) print("MULTIPLY OF ALL NUMBERS IN THIRD LIST ::>",mulallnum(C)) Enter the size of the First List ::3 Enter the size of the Second List ::4 Enter the size of the Third List ::5 Enter the Element of First List :: 1 2 5 Enter the Element of Second List :: 3 2 4 5 Enter the Element of Third List :: 12 2 1 3 2 MULTIPLY OF ALL NUMBERS IN FIRST LIST ::> 10 MULTIPLY OF ALL NUMBERS IN SECOND LIST ::> 120 MULTIPLY OF ALL NUMBERS IN THIRD LIST ::> 144
[ { "code": null, "e": 1276, "s": 1062, "text": "First we create 3 list for user input .here we use traversing technique. Initializing the value of product to 1, traverse all the element and multiply every number with the product one by one till the end of list." }, { "code": null, "e": 1322, "s": 1276, "text": "Input: A=[5,6,3]\nOutput:90\nExplanation:5*6*3\n" }, { "code": null, "e": 1599, "s": 1322, "text": "Step 1: input all numbers in the list (lst).\nStep 2: to multiply all values in the list we use traversing technique.\t\nStep 3: variable X=1.\nStep 4: for i in LST\t\t/*traverse from first to last in the list\n X=X*i\t\t/* multiply elements one by one\nStep 5: display X\n" }, { "code": null, "e": 2418, "s": 1599, "text": "#To multiply all numbers in a list\ndef mulallnum(lst):\n x=1\n for i in lst:\n x=x*i\n return x\n #driver code\nA=list()\nB=list()\nC=list()\nn1=int(input(\"Enter the size of the First List ::\"))\nn2=int(input(\"Enter the size of the Second List ::\"))\nn3=int(input(\"Enter the size of the Third List ::\"))\nprint(\"Enter the Element of First List ::\")\nfor i in range(int(n1)):\n k=int(input(\"\"))\n A.append(k)\nprint(\"Enter the Element of Second List ::\")\nfor j in range(int(n2)):\n k1=int(input(\"\"))\n B.append(k1)\nprint(\"Enter the Element of Third List ::\")\nfor j in range(int(n3)):\n k1=int(input(\"\"))\n C.append(k1)\nprint(\"MULTIPLY OF ALL NUMBERS IN FIRST LIST ::>\",mulallnum(A))\nprint(\"MULTIPLY OF ALL NUMBERS IN SECOND LIST ::>\",mulallnum(B))\nprint(\"MULTIPLY OF ALL NUMBERS IN THIRD LIST ::>\",mulallnum(C))" }, { "code": null, "e": 2800, "s": 2418, "text": "Enter the size of the First List ::3\nEnter the size of the Second List ::4\nEnter the size of the Third List ::5\nEnter the Element of First List ::\n1\n2\n5\nEnter the Element of Second List ::\n3\n2\n4\n5\nEnter the Element of Third List ::\n12\n2\n1\n3\n2\nMULTIPLY OF ALL NUMBERS IN FIRST LIST ::> 10\nMULTIPLY OF ALL NUMBERS IN SECOND LIST ::> 120\nMULTIPLY OF ALL NUMBERS IN THIRD LIST ::> 144\n" } ]
Erlang - put
This method is used to add a key value pair to the map. put(key1,value1,map1) key1 − This is key which needs to be added to the map. key1 − This is key which needs to be added to the map. Value1 − This is the value associated with key1 which needs to be added to the map. Value1 − This is the value associated with key1 which needs to be added to the map. map1 − This is map to which the key value needs to be added. map1 − This is map to which the key value needs to be added. The original map with the added key value. -module(helloworld). -export([start/0]). start() -> Lst1 = [{"a",1},{"b",2},{"c",3}], Map1 = maps:from_list(Lst1), io:fwrite("~p~n",[maps:put("d",4,Map1)]). The output of the above program is as follows − #{"a" => 1,"b" => 2,"c" => 3,"d" => 4} Print Add Notes Bookmark this page
[ { "code": null, "e": 2357, "s": 2301, "text": "This method is used to add a key value pair to the map." }, { "code": null, "e": 2380, "s": 2357, "text": "put(key1,value1,map1)\n" }, { "code": null, "e": 2435, "s": 2380, "text": "key1 − This is key which needs to be added to the map." }, { "code": null, "e": 2490, "s": 2435, "text": "key1 − This is key which needs to be added to the map." }, { "code": null, "e": 2574, "s": 2490, "text": "Value1 − This is the value associated with key1 which needs to be added to the map." }, { "code": null, "e": 2658, "s": 2574, "text": "Value1 − This is the value associated with key1 which needs to be added to the map." }, { "code": null, "e": 2719, "s": 2658, "text": "map1 − This is map to which the key value needs to be added." }, { "code": null, "e": 2780, "s": 2719, "text": "map1 − This is map to which the key value needs to be added." }, { "code": null, "e": 2823, "s": 2780, "text": "The original map with the added key value." }, { "code": null, "e": 2995, "s": 2823, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n Lst1 = [{\"a\",1},{\"b\",2},{\"c\",3}], \n Map1 = maps:from_list(Lst1), \n io:fwrite(\"~p~n\",[maps:put(\"d\",4,Map1)])." }, { "code": null, "e": 3043, "s": 2995, "text": "The output of the above program is as follows −" }, { "code": null, "e": 3083, "s": 3043, "text": "#{\"a\" => 1,\"b\" => 2,\"c\" => 3,\"d\" => 4}\n" }, { "code": null, "e": 3090, "s": 3083, "text": " Print" }, { "code": null, "e": 3101, "s": 3090, "text": " Add Notes" } ]
Java - Multithreading
Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. Following are the stages of the life cycle − New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent. If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) As a second step, you will instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Here is an example that creates a new thread and starts running it − class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } } This will produce the following result − Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method − public void run( ) Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start( ); Here is the preceding program rewritten to extend the Thread − class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo( String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { ThreadDemo T1 = new ThreadDemo( "Thread-1"); T1.start(); ThreadDemo T2 = new ThreadDemo( "Thread-2"); T2.start(); } } This will produce the following result − Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Following is the list of important methods available in the Thread class. public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. public final void setName(String name) Changes the name of the Thread object. There is also a getName() method for retrieving the name. public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion. The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread. public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds. public static boolean holdsLock(Object x) Returns true if the current thread holds the lock on the given Object. public static Thread currentThread() Returns a reference to the currently running thread, which is the thread that invokes this method. public static void dumpStack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application. The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable − // File Name : DisplayMessage.java // Create a thread to implement Runnable public class DisplayMessage implements Runnable { private String message; public DisplayMessage(String message) { this.message = message; } public void run() { while(true) { System.out.println(message); } } } Following is another class which extends the Thread class − // File Name : GuessANumber.java // Create a thread to extentd Thread public class GuessANumber extends Thread { private int number; public GuessANumber(int number) { this.number = number; } public void run() { int counter = 0; int guess = 0; do { guess = (int) (Math.random() * 100 + 1); System.out.println(this.getName() + " guesses " + guess); counter++; } while(guess != number); System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**"); } } Following is the main program, which makes use of the above-defined classes − // File Name : ThreadClassDemo.java public class ThreadClassDemo { public static void main(String [] args) { Runnable hello = new DisplayMessage("Hello"); Thread thread1 = new Thread(hello); thread1.setDaemon(true); thread1.setName("hello"); System.out.println("Starting hello thread..."); thread1.start(); Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(bye); thread2.setPriority(Thread.MIN_PRIORITY); thread2.setDaemon(true); System.out.println("Starting goodbye thread..."); thread2.start(); System.out.println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try { thread3.join(); } catch (InterruptedException e) { System.out.println("Thread interrupted."); } System.out.println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); System.out.println("main() is ending..."); } } This will produce the following result. You can try this example again and again and you will get a different result every time. Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye ....... While doing Multithreading programming in Java, you would need to have the following concepts very handy − What is thread synchronization? What is thread synchronization? Handling interthread communication Handling interthread communication Handling thread deadlock Handling thread deadlock Major thread operations Major thread operations 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2716, "s": 2377, "text": "Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs." }, { "code": null, "e": 3145, "s": 2716, "text": "By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application." }, { "code": null, "e": 3263, "s": 3145, "text": "Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program." }, { "code": null, "e": 3445, "s": 3263, "text": "A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread." }, { "code": null, "e": 3490, "s": 3445, "text": "Following are the stages of the life cycle −" }, { "code": null, "e": 3652, "s": 3490, "text": "New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread." }, { "code": null, "e": 3814, "s": 3652, "text": "New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread." }, { "code": null, "e": 3955, "s": 3814, "text": "Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task." }, { "code": null, "e": 4096, "s": 3955, "text": "Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task." }, { "code": null, "e": 4343, "s": 4096, "text": "Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing." }, { "code": null, "e": 4590, "s": 4343, "text": "Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing." }, { "code": null, "e": 4830, "s": 4590, "text": "Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs." }, { "code": null, "e": 5070, "s": 4830, "text": "Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs." }, { "code": null, "e": 5188, "s": 5070, "text": "Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates." }, { "code": null, "e": 5306, "s": 5188, "text": "Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates." }, { "code": null, "e": 5423, "s": 5306, "text": "Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled." }, { "code": null, "e": 5615, "s": 5423, "text": "Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5)." }, { "code": null, "e": 5863, "s": 5615, "text": "Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent." }, { "code": null, "e": 6024, "s": 5863, "text": "If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −" }, { "code": null, "e": 6280, "s": 6024, "text": "As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −" }, { "code": null, "e": 6300, "s": 6280, "text": "public void run( )\n" }, { "code": null, "e": 6389, "s": 6300, "text": "As a second step, you will instantiate a Thread object using the following constructor −" }, { "code": null, "e": 6437, "s": 6389, "text": "Thread(Runnable threadObj, String threadName);\n" }, { "code": null, "e": 6571, "s": 6437, "text": "Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread." }, { "code": null, "e": 6737, "s": 6571, "text": "Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −" }, { "code": null, "e": 6752, "s": 6737, "text": "void start();\n" }, { "code": null, "e": 6821, "s": 6752, "text": "Here is an example that creates a new thread and starts running it −" }, { "code": null, "e": 7934, "s": 6821, "text": "class RunnableDemo implements Runnable {\n private Thread t;\n private String threadName;\n \n RunnableDemo( String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n \n public void run() {\n System.out.println(\"Running \" + threadName );\n try {\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n \n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n\n public static void main(String args[]) {\n RunnableDemo R1 = new RunnableDemo( \"Thread-1\");\n R1.start();\n \n RunnableDemo R2 = new RunnableDemo( \"Thread-2\");\n R2.start();\n } \n}" }, { "code": null, "e": 7975, "s": 7934, "text": "This will produce the following result −" }, { "code": null, "e": 8292, "s": 7975, "text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting.\n" }, { "code": null, "e": 8533, "s": 8292, "text": "The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class." }, { "code": null, "e": 8764, "s": 8533, "text": "You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −" }, { "code": null, "e": 8784, "s": 8764, "text": "public void run( )\n" }, { "code": null, "e": 8948, "s": 8784, "text": "Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −" }, { "code": null, "e": 8964, "s": 8948, "text": "void start( );\n" }, { "code": null, "e": 9027, "s": 8964, "text": "Here is the preceding program rewritten to extend the Thread −" }, { "code": null, "e": 10123, "s": 9027, "text": "class ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n \n ThreadDemo( String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n \n public void run() {\n System.out.println(\"Running \" + threadName );\n try {\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n \n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n\n public static void main(String args[]) {\n ThreadDemo T1 = new ThreadDemo( \"Thread-1\");\n T1.start();\n \n ThreadDemo T2 = new ThreadDemo( \"Thread-2\");\n T2.start();\n } \n}" }, { "code": null, "e": 10164, "s": 10123, "text": "This will produce the following result −" }, { "code": null, "e": 10481, "s": 10164, "text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting.\n" }, { "code": null, "e": 10555, "s": 10481, "text": "Following is the list of important methods available in the Thread class." }, { "code": null, "e": 10575, "s": 10555, "text": "public void start()" }, { "code": null, "e": 10679, "s": 10575, "text": "Starts the thread in a separate path of execution, then invokes the run() method on this Thread object." }, { "code": null, "e": 10697, "s": 10679, "text": "public void run()" }, { "code": null, "e": 10823, "s": 10697, "text": "If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object." }, { "code": null, "e": 10862, "s": 10823, "text": "public final void setName(String name)" }, { "code": null, "e": 10959, "s": 10862, "text": "Changes the name of the Thread object. There is also a getName() method for retrieving the name." }, { "code": null, "e": 11003, "s": 10959, "text": "public final void setPriority(int priority)" }, { "code": null, "e": 11086, "s": 11003, "text": "Sets the priority of this Thread object. The possible values are between 1 and 10." }, { "code": null, "e": 11126, "s": 11086, "text": "public final void setDaemon(boolean on)" }, { "code": null, "e": 11186, "s": 11126, "text": "A parameter of true denotes this Thread as a daemon thread." }, { "code": null, "e": 11224, "s": 11186, "text": "public final void join(long millisec)" }, { "code": null, "e": 11402, "s": 11224, "text": "The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes." }, { "code": null, "e": 11426, "s": 11402, "text": "public void interrupt()" }, { "code": null, "e": 11517, "s": 11426, "text": "Interrupts this thread, causing it to continue execution if it was blocked for any reason." }, { "code": null, "e": 11548, "s": 11517, "text": "public final boolean isAlive()" }, { "code": null, "e": 11671, "s": 11548, "text": "Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion." }, { "code": null, "e": 11880, "s": 11671, "text": "The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread." }, { "code": null, "e": 11907, "s": 11880, "text": "public static void yield()" }, { "code": null, "e": 12028, "s": 11907, "text": "Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled." }, { "code": null, "e": 12068, "s": 12028, "text": "public static void sleep(long millisec)" }, { "code": null, "e": 12164, "s": 12068, "text": "Causes the currently running thread to block for at least the specified number of milliseconds." }, { "code": null, "e": 12206, "s": 12164, "text": "public static boolean holdsLock(Object x)" }, { "code": null, "e": 12277, "s": 12206, "text": "Returns true if the current thread holds the lock on the given Object." }, { "code": null, "e": 12314, "s": 12277, "text": "public static Thread currentThread()" }, { "code": null, "e": 12413, "s": 12314, "text": "Returns a reference to the currently running thread, which is the thread that invokes this method." }, { "code": null, "e": 12444, "s": 12413, "text": "public static void dumpStack()" }, { "code": null, "e": 12561, "s": 12444, "text": "Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application." }, { "code": null, "e": 12715, "s": 12561, "text": "The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable −" }, { "code": null, "e": 13051, "s": 12715, "text": "// File Name : DisplayMessage.java\n// Create a thread to implement Runnable\n\npublic class DisplayMessage implements Runnable {\n private String message;\n \n public DisplayMessage(String message) {\n this.message = message;\n }\n \n public void run() {\n while(true) {\n System.out.println(message);\n }\n }\n}" }, { "code": null, "e": 13111, "s": 13051, "text": "Following is another class which extends the Thread class −" }, { "code": null, "e": 13666, "s": 13111, "text": "// File Name : GuessANumber.java\n// Create a thread to extentd Thread\n\npublic class GuessANumber extends Thread {\n private int number;\n public GuessANumber(int number) {\n this.number = number;\n }\n \n public void run() {\n int counter = 0;\n int guess = 0;\n do {\n guess = (int) (Math.random() * 100 + 1);\n System.out.println(this.getName() + \" guesses \" + guess);\n counter++;\n } while(guess != number);\n System.out.println(\"** Correct!\" + this.getName() + \"in\" + counter + \"guesses.**\");\n }\n}" }, { "code": null, "e": 13744, "s": 13666, "text": "Following is the main program, which makes use of the above-defined classes −" }, { "code": null, "e": 14784, "s": 13744, "text": "// File Name : ThreadClassDemo.java\npublic class ThreadClassDemo {\n\n public static void main(String [] args) {\n Runnable hello = new DisplayMessage(\"Hello\");\n Thread thread1 = new Thread(hello);\n thread1.setDaemon(true);\n thread1.setName(\"hello\");\n System.out.println(\"Starting hello thread...\");\n thread1.start();\n \n Runnable bye = new DisplayMessage(\"Goodbye\");\n Thread thread2 = new Thread(bye);\n thread2.setPriority(Thread.MIN_PRIORITY);\n thread2.setDaemon(true);\n System.out.println(\"Starting goodbye thread...\");\n thread2.start();\n\n System.out.println(\"Starting thread3...\");\n Thread thread3 = new GuessANumber(27);\n thread3.start();\n try {\n thread3.join();\n } catch (InterruptedException e) {\n System.out.println(\"Thread interrupted.\");\n }\n System.out.println(\"Starting thread4...\");\n Thread thread4 = new GuessANumber(75);\n \n thread4.start();\n System.out.println(\"main() is ending...\");\n }\n}" }, { "code": null, "e": 14913, "s": 14784, "text": "This will produce the following result. You can try this example again and again and you will get a different result every time." }, { "code": null, "e": 15050, "s": 14913, "text": "Starting hello thread...\nStarting goodbye thread...\nHello\nHello\nHello\nHello\nHello\nHello\nGoodbye\nGoodbye\nGoodbye\nGoodbye\nGoodbye\n.......\n" }, { "code": null, "e": 15157, "s": 15050, "text": "While doing Multithreading programming in Java, you would need to have the following concepts very handy −" }, { "code": null, "e": 15189, "s": 15157, "text": "What is thread synchronization?" }, { "code": null, "e": 15221, "s": 15189, "text": "What is thread synchronization?" }, { "code": null, "e": 15256, "s": 15221, "text": "Handling interthread communication" }, { "code": null, "e": 15291, "s": 15256, "text": "Handling interthread communication" }, { "code": null, "e": 15316, "s": 15291, "text": "Handling thread deadlock" }, { "code": null, "e": 15341, "s": 15316, "text": "Handling thread deadlock" }, { "code": null, "e": 15365, "s": 15341, "text": "Major thread operations" }, { "code": null, "e": 15389, "s": 15365, "text": "Major thread operations" }, { "code": null, "e": 15422, "s": 15389, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 15438, "s": 15422, "text": " Malhar Lathkar" }, { "code": null, "e": 15471, "s": 15438, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 15487, "s": 15471, "text": " Malhar Lathkar" }, { "code": null, "e": 15522, "s": 15487, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 15536, "s": 15522, "text": " Anadi Sharma" }, { "code": null, "e": 15570, "s": 15536, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 15584, "s": 15570, "text": " Tushar Kale" }, { "code": null, "e": 15621, "s": 15584, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 15636, "s": 15621, "text": " Monica Mittal" }, { "code": null, "e": 15669, "s": 15636, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 15688, "s": 15669, "text": " Arnab Chakraborty" }, { "code": null, "e": 15695, "s": 15688, "text": " Print" }, { "code": null, "e": 15706, "s": 15695, "text": " Add Notes" } ]
Calculate Hyperbolic cosine of a value in R Programming - cosh() Function - GeeksforGeeks
09 Mar, 2021 cosh() function in R Language is used to calculate the hyperbolic cosine value of the numeric value passed to it as the argument. Syntax: cosh(x)Parameter: x: Numeric value Example 1: Python3 # R code to calculate cosine of a value # Assigning values to variablesx1 <- 90x2 <- 30 # Using cosh() Functioncosh(x1)cosh(x2) Output: [1] 6.102016e+38 [1] 5.343237e+12 Example 2: Python3 # R code to calculate cosine of a value # Assigning values to variablesx1 <- pix2 <- pi / 3 # Using cosh() Functioncosh(x1)cosh(x2) Output: [1] 11.59195 [1] 1.600287 arorakashish0911 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n09 Mar, 2021" }, { "code": null, "e": 24982, "s": 24851, "text": "cosh() function in R Language is used to calculate the hyperbolic cosine value of the numeric value passed to it as the argument. " }, { "code": null, "e": 25025, "s": 24982, "text": "Syntax: cosh(x)Parameter: x: Numeric value" }, { "code": null, "e": 25038, "s": 25025, "text": "Example 1: " }, { "code": null, "e": 25046, "s": 25038, "text": "Python3" }, { "code": "# R code to calculate cosine of a value # Assigning values to variablesx1 <- 90x2 <- 30 # Using cosh() Functioncosh(x1)cosh(x2)", "e": 25174, "s": 25046, "text": null }, { "code": null, "e": 25184, "s": 25174, "text": "Output: " }, { "code": null, "e": 25218, "s": 25184, "text": "[1] 6.102016e+38\n[1] 5.343237e+12" }, { "code": null, "e": 25231, "s": 25218, "text": "Example 2: " }, { "code": null, "e": 25239, "s": 25231, "text": "Python3" }, { "code": "# R code to calculate cosine of a value # Assigning values to variablesx1 <- pix2 <- pi / 3 # Using cosh() Functioncosh(x1)cosh(x2)", "e": 25371, "s": 25239, "text": null }, { "code": null, "e": 25381, "s": 25371, "text": "Output: " }, { "code": null, "e": 25407, "s": 25381, "text": "[1] 11.59195\n[1] 1.600287" }, { "code": null, "e": 25426, "s": 25409, "text": "arorakashish0911" }, { "code": null, "e": 25442, "s": 25426, "text": "R Math-Function" }, { "code": null, "e": 25453, "s": 25442, "text": "R Language" }, { "code": null, "e": 25551, "s": 25453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25560, "s": 25551, "text": "Comments" }, { "code": null, "e": 25573, "s": 25560, "text": "Old Comments" }, { "code": null, "e": 25625, "s": 25573, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25663, "s": 25625, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25698, "s": 25663, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25756, "s": 25698, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25799, "s": 25756, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 25848, "s": 25799, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 25898, "s": 25848, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 25915, "s": 25898, "text": "R - if statement" }, { "code": null, "e": 25952, "s": 25915, "text": "How to import an Excel File into R ?" } ]
Python 3 - Tkinter PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically. Each pane contains one widget and each pair of panes is separated by a moveable (via mouse movements) sash. Moving a sash causes the widgets on either side of the sash to be resized. Here is the simple syntax to create this widget − w = PanedWindow( master, option, ... ) master − This represents the parent window. master − This represents the parent window. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. bg The color of the slider and arrowheads when the mouse is not over them. bd The width of the 3-d borders around the entire perimeter of the trough, and also the width of the 3-d effects on the arrowheads and slider. Default is no border around the trough, and a 2-pixel border around the arrowheads and slider. borderwidth Default is 2. cursor The cursor that appears when the mouse is over the window. handlepad Default is 8. handlesize Default is 8. height No default value. orient Default is HORIZONTAL. relief Default is FLAT. sashcursor No default value. sashrelief Default is RAISED. sashwidth Default is 2. showhandle No default value width No default value. PanedWindow objects have these methods − add(child, options) Adds a child window to the paned window. get(startindex [,endindex]) This method returns a specific character or a range of text. config(options) Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values. Try the following example yourself. Here's how to create a 3-pane widget − # !/usr/bin/python3 from tkinter import * m1 = PanedWindow() m1.pack(fill = BOTH, expand = 1) left = Entry(m1, bd = 5) m1.add(left) m2 = PanedWindow(m1, orient = VERTICAL) m1.add(m2) top = Scale( m2, orient = HORIZONTAL) m2.add(top) bottom = Button(m2, text = "OK") m2.add(bottom) mainloop() When the above code is executed, it produces the following result − 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2451, "s": 2340, "text": "A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically." }, { "code": null, "e": 2634, "s": 2451, "text": "Each pane contains one widget and each pair of panes is separated by a moveable (via mouse movements) sash. Moving a sash causes the widgets on either side of the sash to be resized." }, { "code": null, "e": 2684, "s": 2634, "text": "Here is the simple syntax to create this widget −" }, { "code": null, "e": 2724, "s": 2684, "text": "w = PanedWindow( master, option, ... )\n" }, { "code": null, "e": 2768, "s": 2724, "text": "master − This represents the parent window." }, { "code": null, "e": 2812, "s": 2768, "text": "master − This represents the parent window." }, { "code": null, "e": 2952, "s": 2812, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3092, "s": 2952, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3095, "s": 3092, "text": "bg" }, { "code": null, "e": 3167, "s": 3095, "text": "The color of the slider and arrowheads when the mouse is not over them." }, { "code": null, "e": 3170, "s": 3167, "text": "bd" }, { "code": null, "e": 3405, "s": 3170, "text": "The width of the 3-d borders around the entire perimeter of the trough, and also the width of the 3-d effects on the arrowheads and slider. Default is no border around the trough, and a 2-pixel border around the arrowheads and slider." }, { "code": null, "e": 3417, "s": 3405, "text": "borderwidth" }, { "code": null, "e": 3431, "s": 3417, "text": "Default is 2." }, { "code": null, "e": 3438, "s": 3431, "text": "cursor" }, { "code": null, "e": 3497, "s": 3438, "text": "The cursor that appears when the mouse is over the window." }, { "code": null, "e": 3507, "s": 3497, "text": "handlepad" }, { "code": null, "e": 3521, "s": 3507, "text": "Default is 8." }, { "code": null, "e": 3532, "s": 3521, "text": "handlesize" }, { "code": null, "e": 3546, "s": 3532, "text": "Default is 8." }, { "code": null, "e": 3553, "s": 3546, "text": "height" }, { "code": null, "e": 3571, "s": 3553, "text": "No default value." }, { "code": null, "e": 3578, "s": 3571, "text": "orient" }, { "code": null, "e": 3601, "s": 3578, "text": "Default is HORIZONTAL." }, { "code": null, "e": 3608, "s": 3601, "text": "relief" }, { "code": null, "e": 3625, "s": 3608, "text": "Default is FLAT." }, { "code": null, "e": 3636, "s": 3625, "text": "sashcursor" }, { "code": null, "e": 3654, "s": 3636, "text": "No default value." }, { "code": null, "e": 3665, "s": 3654, "text": "sashrelief" }, { "code": null, "e": 3684, "s": 3665, "text": "Default is RAISED." }, { "code": null, "e": 3694, "s": 3684, "text": "sashwidth" }, { "code": null, "e": 3708, "s": 3694, "text": "Default is 2." }, { "code": null, "e": 3719, "s": 3708, "text": "showhandle" }, { "code": null, "e": 3736, "s": 3719, "text": "No default value" }, { "code": null, "e": 3742, "s": 3736, "text": "width" }, { "code": null, "e": 3760, "s": 3742, "text": "No default value." }, { "code": null, "e": 3801, "s": 3760, "text": "PanedWindow objects have these methods −" }, { "code": null, "e": 3821, "s": 3801, "text": "add(child, options)" }, { "code": null, "e": 3862, "s": 3821, "text": "Adds a child window to the paned window." }, { "code": null, "e": 3890, "s": 3862, "text": "get(startindex [,endindex])" }, { "code": null, "e": 3951, "s": 3890, "text": "This method returns a specific character or a range of text." }, { "code": null, "e": 3967, "s": 3951, "text": "config(options)" }, { "code": null, "e": 4099, "s": 3967, "text": "Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values." }, { "code": null, "e": 4174, "s": 4099, "text": "Try the following example yourself. Here's how to create a 3-pane widget −" }, { "code": null, "e": 4472, "s": 4174, "text": "# !/usr/bin/python3\nfrom tkinter import *\n\nm1 = PanedWindow()\nm1.pack(fill = BOTH, expand = 1)\n\nleft = Entry(m1, bd = 5)\nm1.add(left)\n\nm2 = PanedWindow(m1, orient = VERTICAL)\nm1.add(m2)\n\ntop = Scale( m2, orient = HORIZONTAL)\nm2.add(top)\n\nbottom = Button(m2, text = \"OK\")\nm2.add(bottom)\n\nmainloop()" }, { "code": null, "e": 4540, "s": 4472, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4577, "s": 4540, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4593, "s": 4577, "text": " Malhar Lathkar" }, { "code": null, "e": 4626, "s": 4593, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4645, "s": 4626, "text": " Arnab Chakraborty" }, { "code": null, "e": 4680, "s": 4645, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4702, "s": 4680, "text": " In28Minutes Official" }, { "code": null, "e": 4736, "s": 4702, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4764, "s": 4736, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4799, "s": 4764, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4813, "s": 4799, "text": " Lets Kode It" }, { "code": null, "e": 4846, "s": 4813, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4863, "s": 4846, "text": " Abhilash Nelson" }, { "code": null, "e": 4870, "s": 4863, "text": " Print" }, { "code": null, "e": 4881, "s": 4870, "text": " Add Notes" } ]
Visualizing Intersections and Overlaps with Python | by Thiago Carvalho | Towards Data Science
A prevalent task in any data analysis is comparing multiple sets of something. You may have lists of IPs for each landing page of your website, clients who bought certain items from your store, multiple answers from a survey, and so many others. This article will use Python to explore ways to visualize overlaps and intersections of sets, the possibilities, and their advantages and disadvantages. For the next examples, I’ll use a dataset from the Data Visualization Society 2020 Census. I’m using the survey because it has many different types of questions, where some are multiple-choice questions with multiple answers, like the bellow. Let’s say we plot a count for each answer. We would have a total in our chart bigger than the total number of respondents, which can be hard for our audience to understand, raising questions or even making the viewers skeptical about the data. For example, if we had 100 respondents and three possible answers — A, B, and C. We could have something like this:50 answered — A and B;25 answered — A and C;25 answered — A; It looks confusing; even if we explain to the audience that a respondent could select more than one response, it’s hard to grasp what this chart represents. Besides that, with this visualization, we don’t have any information about how the answers intersect. For example, it’s impossible to tell that nobody selected all three options. Let’s start with a simple and very familiar solution, Venn diagrams. I’ll use Matplotlib-Venn for this task. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib_venn import venn2, venn2_circles Now let’s load the dataset and prepare the data we want to analyze. The question we’ll check is, “Which of these best describes your role as a data visualizer in the past year?”. The answers to this question are distributed in 6 columns, one for each response. If the respondent selected that answer, the field will have a text. If not, it’ll be empty. We’ll convert that data to 6 lists containing the indexes of the users that selected each response. df = pd.read_csv('data/2020/DataVizCensus2020-AnonymizedResponses.csv')nm = 'Which of these best describes your role as a data visualizer in the past year?'d1 = df[~df[nm].isnull()].index.tolist() # independentd2 = df[~df[nm+'_1'].isnull()].index.tolist() # organizationd3 = df[~df[nm+'_2'].isnull()].index.tolist() # hobbyd4 = df[~df[nm+'_3'].isnull()].index.tolist() # studentd5 = df[~df[nm+'_4'].isnull()].index.tolist() # teacherd6 = df[~df[nm+'_5'].isnull()].index.tolist() # passive income Venn diagrams are straightforward to use and understand. We need to pass the sets with the key/ids we’ll analyze. If it’s an intersection of two sets, we use Venn2; if it's three sets, we use Venn3. venn2([set(d1), set(d2)])plt.show() Great! With Venn Diagrams, we can clearly display that 201 respondents selected A and didn’t select B, 974 selected B and didn’t select A, and 157 selected both. We can even customize some aspects of the chart. venn2([set(d1), set(d2)], set_colors=('#3E64AF', '#3EAF5D'), set_labels = ('Freelance\nConsultant\nIndependent contractor', 'Position in an organization\nwith some dataviz job responsibilities'), alpha=0.75)venn2_circles([set(d1), set(d2)], lw=0.7)plt.show() venn3([set(d1), set(d2), set(d5)], set_colors=('#3E64AF', '#3EAF5D', '#D74E3B'), set_labels = ('Freelance\nConsultant\nIndependent contractor', 'Position in an organization\nwith some data viz job responsibilities', 'Academic\nTeacher'), alpha=0.75)venn3_circles([set(d1), set(d2), set(d5)], lw=0.7) plt.show() That’s great, but what if we want to display the overlaps of more than 3 sets? Well, there are a couple of possibilities. We could use multiple diagrams, for example. labels = ['Freelance\nConsultant\nIndependent contractor', 'Position in an organization\nwith some data viz\njob responsibilities', 'Non-compensated\ndata visualization hobbyist', 'Student', 'Academic/Teacher', 'Passive income from\ndata visualization\nrelated products']c = ('#3E64AF', '#3EAF5D')# subplot indexestxt_indexes = [1, 7, 13, 19, 25]title_indexes = [2, 9, 16, 23, 30]plot_indexes = [8, 14, 20, 26, 15, 21, 27, 22, 28, 29]# combinations of setstitle_sets = [[set(d1), set(d2)], [set(d2), set(d3)], [set(d3), set(d4)], [set(d4), set(d5)], [set(d5), set(d6)]]plot_sets = [[set(d1), set(d3)], [set(d1), set(d4)], [set(d1), set(d5)], [set(d1), set(d6)], [set(d2), set(d4)], [set(d2), set(d5)], [set(d2), set(d6)], [set(d3), set(d5)], [set(d3), set(d6)], [set(d4), set(d6)]]fig, ax = plt.subplots(1, figsize=(16,16))# plot textsfor idx, txt_idx in enumerate(txt_indexes): plt.subplot(6, 6, txt_idx) plt.text(0.5,0.5, labels[idx+1], ha='center', va='center', color='#1F764B') plt.axis('off')# plot top plots (the ones with a title)for idx, title_idx in enumerate(title_indexes): plt.subplot(6, 6, title_idx) venn2(title_sets[idx], set_colors=c, set_labels = (' ', ' ')) plt.title(labels[idx], fontsize=10, color='#1F4576')# plot the rest of the diagramsfor idx, plot_idx in enumerate(plot_indexes): plt.subplot(6, 6, plot_idx) venn2(plot_sets[idx], set_colors=c, set_labels = (' ', ' '))plt.savefig('venn_matrix.png') That’s ok, but it didn’t really solve the problem. We can’t tell if there’s someone who selected all answers, nor can we tell the intersection of three sets. What about a Venn with four circles? Here is where things start to get complicated. In the above image, there is no intersection for only blue and green. To solve that, we can use ellipses instead of circles. I’ll use PyVenn for the next example. from venn import vennsets = { labels[0]: set(d1), labels[1]: set(d2), labels[2]: set(d3), labels[3]: set(d4)}fig, ax = plt.subplots(1, figsize=(16,12))venn(sets, ax=ax)plt.legend(labels[:-2], ncol=6) Alright, there it is! But, we lost a critical encoding in our diagram — the size. The blue (807) is smaller than the yellow (62), which doesn’t help much in visualizing the data. We can use the legends and the labels to figure what is what, but using a table would be clearer than this. There are a few implementations of area proportional Venn diagrams that can handle more than three sets, but I couldn’t find any in Python. Layout wise, it’s hard to make a Venn diagram that can display more than three sets properly. But there’s another solution available. Upset plots are a great way of displaying the intersection of multiple sets. They’re not so intuitive to read as Venn diagrams but do get the job done. I’ll use the library UpSetPlot for the next example, but first, let’s prepare the data. upset_df = pd.DataFrame()col_names = ['Independent', 'Work for Org', 'Hobby', 'Student', 'Academic', 'Passive Income']nm = 'Which of these best describes your role as a data visualizer in the past year?'for idx, col in enumerate(df[[nm, nm+'_1', nm+'_2', nm+'_3', nm+'_4', nm+'_5']]): temp = [] for i in df[col]: if str(i) != 'nan': temp.append(True) else: temp.append(False) upset_df[col_names[idx]] = temp upset_df['c'] = 1example = upset_df.groupby(col_names).count().sort_values('c')example With the data properly arranged, we only need one method to draw our chart, and we’re done. upsetplot.plot(example['c'], sort_by="cardinality")plt.title('Which of these best describes your role as a data visualizer in the past year?', loc='left')plt.show() Awesome! On the top, we have bars showing how many times a combination appeared. On the bottom, there is a matrix showing which combination each bar represents, and on the bottom left, we have a horizontal bar chart representing the total size of each set. That’s a lot of information, but the well-organized layout makes it simple to extract insights. Even with my poorly written labels, we can easily tell that most people selected ‘working for an organization.’ The second most common answer wasn’t even displayed in the previous Venn diagrams: the number of people who didn’t select any answer. Overall visualizing sets and their intersections can be a thought task, but we have some good options for tackling it. I prefer Venn Diagrams when dealing with a small number of sets and Upset plots when it's more than three. It’s always a good idea to explain what the visualization is displaying and how to read the charts you’re presenting, especially in cases like this where the charts aren’t so friendly. Thanks for reading my article. Here, you can find more tutorials about DataViz with Python.
[ { "code": null, "e": 418, "s": 172, "text": "A prevalent task in any data analysis is comparing multiple sets of something. You may have lists of IPs for each landing page of your website, clients who bought certain items from your store, multiple answers from a survey, and so many others." }, { "code": null, "e": 571, "s": 418, "text": "This article will use Python to explore ways to visualize overlaps and intersections of sets, the possibilities, and their advantages and disadvantages." }, { "code": null, "e": 662, "s": 571, "text": "For the next examples, I’ll use a dataset from the Data Visualization Society 2020 Census." }, { "code": null, "e": 814, "s": 662, "text": "I’m using the survey because it has many different types of questions, where some are multiple-choice questions with multiple answers, like the bellow." }, { "code": null, "e": 1058, "s": 814, "text": "Let’s say we plot a count for each answer. We would have a total in our chart bigger than the total number of respondents, which can be hard for our audience to understand, raising questions or even making the viewers skeptical about the data." }, { "code": null, "e": 1139, "s": 1058, "text": "For example, if we had 100 respondents and three possible answers — A, B, and C." }, { "code": null, "e": 1234, "s": 1139, "text": "We could have something like this:50 answered — A and B;25 answered — A and C;25 answered — A;" }, { "code": null, "e": 1391, "s": 1234, "text": "It looks confusing; even if we explain to the audience that a respondent could select more than one response, it’s hard to grasp what this chart represents." }, { "code": null, "e": 1570, "s": 1391, "text": "Besides that, with this visualization, we don’t have any information about how the answers intersect. For example, it’s impossible to tell that nobody selected all three options." }, { "code": null, "e": 1679, "s": 1570, "text": "Let’s start with a simple and very familiar solution, Venn diagrams. I’ll use Matplotlib-Venn for this task." }, { "code": null, "e": 1844, "s": 1679, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib_venn import venn2, venn2_circles" }, { "code": null, "e": 1912, "s": 1844, "text": "Now let’s load the dataset and prepare the data we want to analyze." }, { "code": null, "e": 2023, "s": 1912, "text": "The question we’ll check is, “Which of these best describes your role as a data visualizer in the past year?”." }, { "code": null, "e": 2105, "s": 2023, "text": "The answers to this question are distributed in 6 columns, one for each response." }, { "code": null, "e": 2197, "s": 2105, "text": "If the respondent selected that answer, the field will have a text. If not, it’ll be empty." }, { "code": null, "e": 2297, "s": 2197, "text": "We’ll convert that data to 6 lists containing the indexes of the users that selected each response." }, { "code": null, "e": 2793, "s": 2297, "text": "df = pd.read_csv('data/2020/DataVizCensus2020-AnonymizedResponses.csv')nm = 'Which of these best describes your role as a data visualizer in the past year?'d1 = df[~df[nm].isnull()].index.tolist() # independentd2 = df[~df[nm+'_1'].isnull()].index.tolist() # organizationd3 = df[~df[nm+'_2'].isnull()].index.tolist() # hobbyd4 = df[~df[nm+'_3'].isnull()].index.tolist() # studentd5 = df[~df[nm+'_4'].isnull()].index.tolist() # teacherd6 = df[~df[nm+'_5'].isnull()].index.tolist() # passive income" }, { "code": null, "e": 2850, "s": 2793, "text": "Venn diagrams are straightforward to use and understand." }, { "code": null, "e": 2992, "s": 2850, "text": "We need to pass the sets with the key/ids we’ll analyze. If it’s an intersection of two sets, we use Venn2; if it's three sets, we use Venn3." }, { "code": null, "e": 3028, "s": 2992, "text": "venn2([set(d1), set(d2)])plt.show()" }, { "code": null, "e": 3190, "s": 3028, "text": "Great! With Venn Diagrams, we can clearly display that 201 respondents selected A and didn’t select B, 974 selected B and didn’t select A, and 157 selected both." }, { "code": null, "e": 3239, "s": 3190, "text": "We can even customize some aspects of the chart." }, { "code": null, "e": 3535, "s": 3239, "text": "venn2([set(d1), set(d2)], set_colors=('#3E64AF', '#3EAF5D'), set_labels = ('Freelance\\nConsultant\\nIndependent contractor', 'Position in an organization\\nwith some dataviz job responsibilities'), alpha=0.75)venn2_circles([set(d1), set(d2)], lw=0.7)plt.show()" }, { "code": null, "e": 3901, "s": 3535, "text": "venn3([set(d1), set(d2), set(d5)], set_colors=('#3E64AF', '#3EAF5D', '#D74E3B'), set_labels = ('Freelance\\nConsultant\\nIndependent contractor', 'Position in an organization\\nwith some data viz job responsibilities', 'Academic\\nTeacher'), alpha=0.75)venn3_circles([set(d1), set(d2), set(d5)], lw=0.7) plt.show()" }, { "code": null, "e": 3980, "s": 3901, "text": "That’s great, but what if we want to display the overlaps of more than 3 sets?" }, { "code": null, "e": 4068, "s": 3980, "text": "Well, there are a couple of possibilities. We could use multiple diagrams, for example." }, { "code": null, "e": 5664, "s": 4068, "text": "labels = ['Freelance\\nConsultant\\nIndependent contractor', 'Position in an organization\\nwith some data viz\\njob responsibilities', 'Non-compensated\\ndata visualization hobbyist', 'Student', 'Academic/Teacher', 'Passive income from\\ndata visualization\\nrelated products']c = ('#3E64AF', '#3EAF5D')# subplot indexestxt_indexes = [1, 7, 13, 19, 25]title_indexes = [2, 9, 16, 23, 30]plot_indexes = [8, 14, 20, 26, 15, 21, 27, 22, 28, 29]# combinations of setstitle_sets = [[set(d1), set(d2)], [set(d2), set(d3)], [set(d3), set(d4)], [set(d4), set(d5)], [set(d5), set(d6)]]plot_sets = [[set(d1), set(d3)], [set(d1), set(d4)], [set(d1), set(d5)], [set(d1), set(d6)], [set(d2), set(d4)], [set(d2), set(d5)], [set(d2), set(d6)], [set(d3), set(d5)], [set(d3), set(d6)], [set(d4), set(d6)]]fig, ax = plt.subplots(1, figsize=(16,16))# plot textsfor idx, txt_idx in enumerate(txt_indexes): plt.subplot(6, 6, txt_idx) plt.text(0.5,0.5, labels[idx+1], ha='center', va='center', color='#1F764B') plt.axis('off')# plot top plots (the ones with a title)for idx, title_idx in enumerate(title_indexes): plt.subplot(6, 6, title_idx) venn2(title_sets[idx], set_colors=c, set_labels = (' ', ' ')) plt.title(labels[idx], fontsize=10, color='#1F4576')# plot the rest of the diagramsfor idx, plot_idx in enumerate(plot_indexes): plt.subplot(6, 6, plot_idx) venn2(plot_sets[idx], set_colors=c, set_labels = (' ', ' '))plt.savefig('venn_matrix.png')" }, { "code": null, "e": 5822, "s": 5664, "text": "That’s ok, but it didn’t really solve the problem. We can’t tell if there’s someone who selected all answers, nor can we tell the intersection of three sets." }, { "code": null, "e": 5859, "s": 5822, "text": "What about a Venn with four circles?" }, { "code": null, "e": 5906, "s": 5859, "text": "Here is where things start to get complicated." }, { "code": null, "e": 6031, "s": 5906, "text": "In the above image, there is no intersection for only blue and green. To solve that, we can use ellipses instead of circles." }, { "code": null, "e": 6069, "s": 6031, "text": "I’ll use PyVenn for the next example." }, { "code": null, "e": 6281, "s": 6069, "text": "from venn import vennsets = { labels[0]: set(d1), labels[1]: set(d2), labels[2]: set(d3), labels[3]: set(d4)}fig, ax = plt.subplots(1, figsize=(16,12))venn(sets, ax=ax)plt.legend(labels[:-2], ncol=6)" }, { "code": null, "e": 6303, "s": 6281, "text": "Alright, there it is!" }, { "code": null, "e": 6363, "s": 6303, "text": "But, we lost a critical encoding in our diagram — the size." }, { "code": null, "e": 6568, "s": 6363, "text": "The blue (807) is smaller than the yellow (62), which doesn’t help much in visualizing the data. We can use the legends and the labels to figure what is what, but using a table would be clearer than this." }, { "code": null, "e": 6708, "s": 6568, "text": "There are a few implementations of area proportional Venn diagrams that can handle more than three sets, but I couldn’t find any in Python." }, { "code": null, "e": 6802, "s": 6708, "text": "Layout wise, it’s hard to make a Venn diagram that can display more than three sets properly." }, { "code": null, "e": 6994, "s": 6802, "text": "But there’s another solution available. Upset plots are a great way of displaying the intersection of multiple sets. They’re not so intuitive to read as Venn diagrams but do get the job done." }, { "code": null, "e": 7082, "s": 6994, "text": "I’ll use the library UpSetPlot for the next example, but first, let’s prepare the data." }, { "code": null, "e": 7625, "s": 7082, "text": "upset_df = pd.DataFrame()col_names = ['Independent', 'Work for Org', 'Hobby', 'Student', 'Academic', 'Passive Income']nm = 'Which of these best describes your role as a data visualizer in the past year?'for idx, col in enumerate(df[[nm, nm+'_1', nm+'_2', nm+'_3', nm+'_4', nm+'_5']]): temp = [] for i in df[col]: if str(i) != 'nan': temp.append(True) else: temp.append(False) upset_df[col_names[idx]] = temp upset_df['c'] = 1example = upset_df.groupby(col_names).count().sort_values('c')example" }, { "code": null, "e": 7717, "s": 7625, "text": "With the data properly arranged, we only need one method to draw our chart, and we’re done." }, { "code": null, "e": 7882, "s": 7717, "text": "upsetplot.plot(example['c'], sort_by=\"cardinality\")plt.title('Which of these best describes your role as a data visualizer in the past year?', loc='left')plt.show()" }, { "code": null, "e": 8139, "s": 7882, "text": "Awesome! On the top, we have bars showing how many times a combination appeared. On the bottom, there is a matrix showing which combination each bar represents, and on the bottom left, we have a horizontal bar chart representing the total size of each set." }, { "code": null, "e": 8235, "s": 8139, "text": "That’s a lot of information, but the well-organized layout makes it simple to extract insights." }, { "code": null, "e": 8347, "s": 8235, "text": "Even with my poorly written labels, we can easily tell that most people selected ‘working for an organization.’" }, { "code": null, "e": 8481, "s": 8347, "text": "The second most common answer wasn’t even displayed in the previous Venn diagrams: the number of people who didn’t select any answer." }, { "code": null, "e": 8600, "s": 8481, "text": "Overall visualizing sets and their intersections can be a thought task, but we have some good options for tackling it." }, { "code": null, "e": 8892, "s": 8600, "text": "I prefer Venn Diagrams when dealing with a small number of sets and Upset plots when it's more than three. It’s always a good idea to explain what the visualization is displaying and how to read the charts you’re presenting, especially in cases like this where the charts aren’t so friendly." } ]
Relational Algebra for Query Optimization
When a query is placed, it is at first scanned, parsed and validated. An internal representation of the query is then created such as a query tree or a query graph. Then alternative execution strategies are devised for retrieving results from the database tables. The process of choosing the most appropriate execution strategy for query processing is called query optimization. In DDBMS, query optimization is a crucial task. The complexity is high since number of alternative strategies may increase exponentially due to the following factors − The presence of a number of fragments. Distribution of the fragments or tables across various sites. The speed of communication links. Disparity in local processing capabilities. Hence, in a distributed system, the target is often to find a good execution strategy for query processing rather than the best one. The time to execute a query is the sum of the following − Time to communicate queries to databases. Time to execute local query fragments. Time to assemble data from different sites. Time to display results to the application. Query processing is a set of all activities starting from query placement to displaying the results of the query. The steps are as shown in the following diagram − Relational algebra defines the basic set of operations of relational database model. A sequence of relational algebra operations forms a relational algebra expression. The result of this expression represents the result of a database query. The basic operations are − Projection Selection Union Intersection Minus Join Projection operation displays a subset of fields of a table. This gives a vertical partition of the table. Syntax in Relational Algebra $$\pi_{<{AttributeList}>}{(<{Table Name}>)}$$ For example, let us consider the following Student database − If we want to display the names and courses of all students, we will use the following relational algebra expression − $$\pi_{Name,Course}{(STUDENT)}$$ Selection operation displays a subset of tuples of a table that satisfies certain conditions. This gives a horizontal partition of the table. Syntax in Relational Algebra $$\sigma_{<{Conditions}>}{(<{Table Name}>)}$$ For example, in the Student table, if we want to display the details of all students who have opted for MCA course, we will use the following relational algebra expression − $$\sigma_{Course} = {\small "BCA"}^{(STUDENT)}$$ For most queries, we need a combination of projection and selection operations. There are two ways to write these expressions − Using sequence of projection and selection operations. Using rename operation to generate intermediate results. For example, to display names of all female students of the BCA course − Relational algebra expression using sequence of projection and selection operations $$\pi_{Name}(\sigma_{Gender = \small "Female" AND \: Course = \small "BCA"}{(STUDENT)})$$ Relational algebra expression using rename operation to generate intermediate results $$FemaleBCAStudent \leftarrow \sigma_{Gender = \small "Female" AND \: Course = \small "BCA"} {(STUDENT)}$$ $$Result \leftarrow \pi_{Name}{(FemaleBCAStudent)}$$ If P is a result of an operation and Q is a result of another operation, the union of P and Q ($p \cup Q$) is the set of all tuples that is either in P or in Q or in both without duplicates. For example, to display all students who are either in Semester 1 or are in BCA course − $$Sem1Student \leftarrow \sigma_{Semester = 1}{(STUDENT)}$$ $$BCAStudent \leftarrow \sigma_{Course = \small "BCA"}{(STUDENT)}$$ $$Result \leftarrow Sem1Student \cup BCAStudent$$ If P is a result of an operation and Q is a result of another operation, the intersection of P and Q ( $p \cap Q$ ) is the set of all tuples that are in P and Q both. For example, given the following two schemas − EMPLOYEE PROJECT To display the names of all cities where a project is located and also an employee resides − $$CityEmp \leftarrow \pi_{City}{(EMPLOYEE)}$$ $$CityProject \leftarrow \pi_{City}{(PROJECT)}$$ $$Result \leftarrow CityEmp \cap CityProject$$ If P is a result of an operation and Q is a result of another operation, P - Q is the set of all tuples that are in P and not in Q. For example, to list all the departments which do not have an ongoing project (projects with status = ongoing) − $$AllDept \leftarrow \pi_{Department}{(EMPLOYEE)}$$ $$ProjectDept \leftarrow \pi_{Department} (\sigma_{Status = \small "ongoing"}{(PROJECT)})$$ $$Result \leftarrow AllDept - ProjectDept$$ Join operation combines related tuples of two different tables (results of queries) into a single table. For example, consider two schemas, Customer and Branch in a Bank database as follows − CUSTOMER BRANCH To list the employee details along with branch details − $$Result \leftarrow CUSTOMER \bowtie_{Customer.BranchID=Branch.BranchID}{BRANCH}$$ SQL queries are translated into equivalent relational algebra expressions before optimization. A query is at first decomposed into smaller query blocks. These blocks are translated to equivalent relational algebra expressions. Optimization includes optimization of each block and then optimization of the query as a whole. Let us consider the following schemas − EMPLOYEE PROJECT WORKS To display the details of all employees who earn a salary LESS than the average salary, we write the SQL query − SELECT * FROM EMPLOYEE WHERE SALARY < ( SELECT AVERAGE(SALARY) FROM EMPLOYEE ) ; This query contains one nested sub-query. So, this can be broken down into two blocks. The inner block is − SELECT AVERAGE(SALARY)FROM EMPLOYEE ; If the result of this query is AvgSal, then outer block is − SELECT * FROM EMPLOYEE WHERE SALARY < AvgSal; Relational algebra expression for inner block − $$AvgSal \leftarrow \Im_{AVERAGE(Salary)}{EMPLOYEE}$$ Relational algebra expression for outer block − $$\sigma_{Salary <{AvgSal}>}{EMPLOYEE}$$ To display the project ID and status of all projects of employee 'Arun Kumar', we write the SQL query − SELECT PID, STATUS FROM PROJECT WHERE PID = ( SELECT FROM WORKS WHERE EMPID = ( SELECT EMPID FROM EMPLOYEE WHERE NAME = 'ARUN KUMAR')); This query contains two nested sub-queries. Thus, can be broken down into three blocks, as follows − SELECT EMPID FROM EMPLOYEE WHERE NAME = 'ARUN KUMAR'; SELECT PID FROM WORKS WHERE EMPID = ArunEmpID; SELECT PID, STATUS FROM PROJECT WHERE PID = ArunPID; (Here ArunEmpID and ArunPID are the results of inner queries) Relational algebra expressions for the three blocks are − $$ArunEmpID \leftarrow \pi_{EmpID}(\sigma_{Name = \small "Arun Kumar"} {(EMPLOYEE)})$$ $$ArunPID \leftarrow \pi_{PID}(\sigma_{EmpID = \small "ArunEmpID"} {(WORKS)})$$ $$Result \leftarrow \pi_{PID, Status}(\sigma_{PID = \small "ArunPID"} {(PROJECT)})$$ The computation of relational algebra operators can be done in many different ways, and each alternative is called an access path. The computation alternative depends upon three main factors − Operator type Available memory Disk structures The time to perform execution of a relational algebra operation is the sum of − Time to process the tuples. Time to fetch the tuples of the table from disk to memory. Since the time to process a tuple is very much smaller than the time to fetch the tuple from the storage, particularly in a distributed system, disk access is very often considered as the metric for calculating cost of relational expression. Computation of selection operation depends upon the complexity of the selection condition and the availability of indexes on the attributes of the table. Following are the computation alternatives depending upon the indexes − No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed. No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed. B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table. B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table. Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory. Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory. When we want to join two tables, say P and Q, each tuple in P has to be compared with each tuple in Q to test if the join condition is satisfied. If the condition is satisfied, the corresponding tuples are concatenated, eliminating duplicate fields and appended to the result relation. Consequently, this is the most expensive operation. The common approaches for computing joins are − This is the conventional join approach. It can be illustrated through the following pseudocode (Tables P and Q, with tuples tuple_p and tuple_q and joining attribute a) − For each tuple_p in P For each tuple_q in Q If tuple_p.a = tuple_q.a Then Concatenate tuple_p and tuple_q and append to Result End If Next tuple_q Next tuple-p In this approach, the two tables are individually sorted based upon the joining attribute and then the sorted tables are merged. External sorting techniques are adopted since the number of records is very high and cannot be accommodated in the memory. Once the individual tables are sorted, one page each of the sorted tables are brought to the memory, merged based upon the joining attribute and the joined tuples are written out. This approach comprises of two phases: partitioning phase and probing phase. In partitioning phase, the tables P and Q are broken into two sets of disjoint partitions. A common hash function is decided upon. This hash function is used to assign tuples to partitions. In the probing phase, tuples in a partition of P are compared with the tuples of corresponding partition of Q. If they match, then they are written out. 49 Lectures 11 hours Hussein Rashad Print Add Notes Bookmark this page
[ { "code": null, "e": 2602, "s": 2223, "text": "When a query is placed, it is at first scanned, parsed and validated. An internal representation of the query is then created such as a query tree or a query graph. Then alternative execution strategies are devised for retrieving results from the database tables. The process of choosing the most appropriate execution strategy for query processing is called query optimization." }, { "code": null, "e": 2770, "s": 2602, "text": "In DDBMS, query optimization is a crucial task. The complexity is high since number of alternative strategies may increase exponentially due to the following factors −" }, { "code": null, "e": 2809, "s": 2770, "text": "The presence of a number of fragments." }, { "code": null, "e": 2871, "s": 2809, "text": "Distribution of the fragments or tables across various sites." }, { "code": null, "e": 2905, "s": 2871, "text": "The speed of communication links." }, { "code": null, "e": 2949, "s": 2905, "text": "Disparity in local processing capabilities." }, { "code": null, "e": 3140, "s": 2949, "text": "Hence, in a distributed system, the target is often to find a good execution strategy for query processing rather than the best one. The time to execute a query is the sum of the following −" }, { "code": null, "e": 3182, "s": 3140, "text": "Time to communicate queries to databases." }, { "code": null, "e": 3221, "s": 3182, "text": "Time to execute local query fragments." }, { "code": null, "e": 3265, "s": 3221, "text": "Time to assemble data from different sites." }, { "code": null, "e": 3309, "s": 3265, "text": "Time to display results to the application." }, { "code": null, "e": 3473, "s": 3309, "text": "Query processing is a set of all activities starting from query placement to displaying the results of the query. The steps are as shown in the following diagram −" }, { "code": null, "e": 3714, "s": 3473, "text": "Relational algebra defines the basic set of operations of relational database model. A sequence of relational algebra operations forms a relational algebra expression. The result of this expression represents the result of a database query." }, { "code": null, "e": 3741, "s": 3714, "text": "The basic operations are −" }, { "code": null, "e": 3752, "s": 3741, "text": "Projection" }, { "code": null, "e": 3762, "s": 3752, "text": "Selection" }, { "code": null, "e": 3768, "s": 3762, "text": "Union" }, { "code": null, "e": 3781, "s": 3768, "text": "Intersection" }, { "code": null, "e": 3787, "s": 3781, "text": "Minus" }, { "code": null, "e": 3793, "s": 3787, "text": "Join " }, { "code": null, "e": 3900, "s": 3793, "text": "Projection operation displays a subset of fields of a table. This gives a vertical partition of the table." }, { "code": null, "e": 3929, "s": 3900, "text": "Syntax in Relational Algebra" }, { "code": null, "e": 3975, "s": 3929, "text": "$$\\pi_{<{AttributeList}>}{(<{Table Name}>)}$$" }, { "code": null, "e": 4037, "s": 3975, "text": "For example, let us consider the following Student database −" }, { "code": null, "e": 4156, "s": 4037, "text": "If we want to display the names and courses of all students, we will use the following relational algebra expression −" }, { "code": null, "e": 4189, "s": 4156, "text": "$$\\pi_{Name,Course}{(STUDENT)}$$" }, { "code": null, "e": 4331, "s": 4189, "text": "Selection operation displays a subset of tuples of a table that satisfies certain conditions. This gives a horizontal partition of the table." }, { "code": null, "e": 4360, "s": 4331, "text": "Syntax in Relational Algebra" }, { "code": null, "e": 4406, "s": 4360, "text": "$$\\sigma_{<{Conditions}>}{(<{Table Name}>)}$$" }, { "code": null, "e": 4580, "s": 4406, "text": "For example, in the Student table, if we want to display the details of all students who have opted for MCA course, we will use the following relational algebra expression −" }, { "code": null, "e": 4629, "s": 4580, "text": "$$\\sigma_{Course} = {\\small \"BCA\"}^{(STUDENT)}$$" }, { "code": null, "e": 4757, "s": 4629, "text": "For most queries, we need a combination of projection and selection operations. There are two ways to write these expressions −" }, { "code": null, "e": 4812, "s": 4757, "text": "Using sequence of projection and selection operations." }, { "code": null, "e": 4869, "s": 4812, "text": "Using rename operation to generate intermediate results." }, { "code": null, "e": 4942, "s": 4869, "text": "For example, to display names of all female students of the BCA course −" }, { "code": null, "e": 5026, "s": 4942, "text": "Relational algebra expression using sequence of projection and selection operations" }, { "code": null, "e": 5116, "s": 5026, "text": "$$\\pi_{Name}(\\sigma_{Gender = \\small \"Female\" AND \\: Course = \\small \"BCA\"}{(STUDENT)})$$" }, { "code": null, "e": 5202, "s": 5116, "text": "Relational algebra expression using rename operation to generate intermediate results" }, { "code": null, "e": 5309, "s": 5202, "text": "$$FemaleBCAStudent \\leftarrow \\sigma_{Gender = \\small \"Female\" AND \\: Course = \\small \"BCA\"} {(STUDENT)}$$" }, { "code": null, "e": 5362, "s": 5309, "text": "$$Result \\leftarrow \\pi_{Name}{(FemaleBCAStudent)}$$" }, { "code": null, "e": 5553, "s": 5362, "text": "If P is a result of an operation and Q is a result of another operation, the union of P and Q ($p \\cup Q$) is the set of all tuples that is either in P or in Q or in both without duplicates." }, { "code": null, "e": 5642, "s": 5553, "text": "For example, to display all students who are either in Semester 1 or are in BCA course −" }, { "code": null, "e": 5702, "s": 5642, "text": "$$Sem1Student \\leftarrow \\sigma_{Semester = 1}{(STUDENT)}$$" }, { "code": null, "e": 5770, "s": 5702, "text": "$$BCAStudent \\leftarrow \\sigma_{Course = \\small \"BCA\"}{(STUDENT)}$$" }, { "code": null, "e": 5820, "s": 5770, "text": "$$Result \\leftarrow Sem1Student \\cup BCAStudent$$" }, { "code": null, "e": 5987, "s": 5820, "text": "If P is a result of an operation and Q is a result of another operation, the intersection of P and Q ( $p \\cap Q$ ) is the set of all tuples that are in P and Q both." }, { "code": null, "e": 6034, "s": 5987, "text": "For example, given the following two schemas −" }, { "code": null, "e": 6043, "s": 6034, "text": "EMPLOYEE" }, { "code": null, "e": 6051, "s": 6043, "text": "PROJECT" }, { "code": null, "e": 6144, "s": 6051, "text": "To display the names of all cities where a project is located and also an employee resides −" }, { "code": null, "e": 6190, "s": 6144, "text": "$$CityEmp \\leftarrow \\pi_{City}{(EMPLOYEE)}$$" }, { "code": null, "e": 6239, "s": 6190, "text": "$$CityProject \\leftarrow \\pi_{City}{(PROJECT)}$$" }, { "code": null, "e": 6286, "s": 6239, "text": "$$Result \\leftarrow CityEmp \\cap CityProject$$" }, { "code": null, "e": 6419, "s": 6286, "text": "If P is a result of an operation and Q is a result of another operation, P - Q is the set of all tuples that are in P and not in Q." }, { "code": null, "e": 6532, "s": 6419, "text": "For example, to list all the departments which do not have an ongoing project (projects with status = ongoing) −" }, { "code": null, "e": 6584, "s": 6532, "text": "$$AllDept \\leftarrow \\pi_{Department}{(EMPLOYEE)}$$" }, { "code": null, "e": 6676, "s": 6584, "text": "$$ProjectDept \\leftarrow \\pi_{Department} (\\sigma_{Status = \\small \"ongoing\"}{(PROJECT)})$$" }, { "code": null, "e": 6720, "s": 6676, "text": "$$Result \\leftarrow AllDept - ProjectDept$$" }, { "code": null, "e": 6825, "s": 6720, "text": "Join operation combines related tuples of two different tables (results of queries) into a single table." }, { "code": null, "e": 6912, "s": 6825, "text": "For example, consider two schemas, Customer and Branch in a Bank database as follows −" }, { "code": null, "e": 6921, "s": 6912, "text": "CUSTOMER" }, { "code": null, "e": 6928, "s": 6921, "text": "BRANCH" }, { "code": null, "e": 6985, "s": 6928, "text": "To list the employee details along with branch details −" }, { "code": null, "e": 7068, "s": 6985, "text": "$$Result \\leftarrow CUSTOMER \\bowtie_{Customer.BranchID=Branch.BranchID}{BRANCH}$$" }, { "code": null, "e": 7391, "s": 7068, "text": "SQL queries are translated into equivalent relational algebra expressions before optimization. A query is at first decomposed into smaller query blocks. These blocks are translated to equivalent relational algebra expressions. Optimization includes optimization of each block and then optimization of the query as a whole." }, { "code": null, "e": 7431, "s": 7391, "text": "Let us consider the following schemas −" }, { "code": null, "e": 7440, "s": 7431, "text": "EMPLOYEE" }, { "code": null, "e": 7448, "s": 7440, "text": "PROJECT" }, { "code": null, "e": 7454, "s": 7448, "text": "WORKS" }, { "code": null, "e": 7567, "s": 7454, "text": "To display the details of all employees who earn a salary LESS than the average salary, we write the SQL query −" }, { "code": null, "e": 7649, "s": 7567, "text": "SELECT * FROM EMPLOYEE \nWHERE SALARY < ( SELECT AVERAGE(SALARY) FROM EMPLOYEE ) ;" }, { "code": null, "e": 7736, "s": 7649, "text": "This query contains one nested sub-query. So, this can be broken down into two blocks." }, { "code": null, "e": 7757, "s": 7736, "text": "The inner block is −" }, { "code": null, "e": 7795, "s": 7757, "text": "SELECT AVERAGE(SALARY)FROM EMPLOYEE ;" }, { "code": null, "e": 7856, "s": 7795, "text": "If the result of this query is AvgSal, then outer block is −" }, { "code": null, "e": 7902, "s": 7856, "text": "SELECT * FROM EMPLOYEE WHERE SALARY < AvgSal;" }, { "code": null, "e": 7950, "s": 7902, "text": "Relational algebra expression for inner block −" }, { "code": null, "e": 8004, "s": 7950, "text": "$$AvgSal \\leftarrow \\Im_{AVERAGE(Salary)}{EMPLOYEE}$$" }, { "code": null, "e": 8052, "s": 8004, "text": "Relational algebra expression for outer block −" }, { "code": null, "e": 8093, "s": 8052, "text": "$$\\sigma_{Salary <{AvgSal}>}{EMPLOYEE}$$" }, { "code": null, "e": 8197, "s": 8093, "text": "To display the project ID and status of all projects of employee 'Arun Kumar', we write the SQL query −" }, { "code": null, "e": 8348, "s": 8197, "text": "SELECT PID, STATUS FROM PROJECT \nWHERE PID = ( SELECT FROM WORKS WHERE EMPID = ( SELECT EMPID FROM EMPLOYEE \n WHERE NAME = 'ARUN KUMAR'));" }, { "code": null, "e": 8449, "s": 8348, "text": "This query contains two nested sub-queries. Thus, can be broken down into three blocks, as follows −" }, { "code": null, "e": 8605, "s": 8449, "text": "SELECT EMPID FROM EMPLOYEE WHERE NAME = 'ARUN KUMAR'; \nSELECT PID FROM WORKS WHERE EMPID = ArunEmpID; \nSELECT PID, STATUS FROM PROJECT WHERE PID = ArunPID;" }, { "code": null, "e": 8667, "s": 8605, "text": "(Here ArunEmpID and ArunPID are the results of inner queries)" }, { "code": null, "e": 8725, "s": 8667, "text": "Relational algebra expressions for the three blocks are −" }, { "code": null, "e": 8812, "s": 8725, "text": "$$ArunEmpID \\leftarrow \\pi_{EmpID}(\\sigma_{Name = \\small \"Arun Kumar\"} {(EMPLOYEE)})$$" }, { "code": null, "e": 8892, "s": 8812, "text": "$$ArunPID \\leftarrow \\pi_{PID}(\\sigma_{EmpID = \\small \"ArunEmpID\"} {(WORKS)})$$" }, { "code": null, "e": 8977, "s": 8892, "text": "$$Result \\leftarrow \\pi_{PID, Status}(\\sigma_{PID = \\small \"ArunPID\"} {(PROJECT)})$$" }, { "code": null, "e": 9108, "s": 8977, "text": "The computation of relational algebra operators can be done in many different ways, and each alternative is called an access path." }, { "code": null, "e": 9170, "s": 9108, "text": "The computation alternative depends upon three main factors −" }, { "code": null, "e": 9184, "s": 9170, "text": "Operator type" }, { "code": null, "e": 9201, "s": 9184, "text": "Available memory" }, { "code": null, "e": 9217, "s": 9201, "text": "Disk structures" }, { "code": null, "e": 9297, "s": 9217, "text": "The time to perform execution of a relational algebra operation is the sum of −" }, { "code": null, "e": 9325, "s": 9297, "text": "Time to process the tuples." }, { "code": null, "e": 9384, "s": 9325, "text": "Time to fetch the tuples of the table from disk to memory." }, { "code": null, "e": 9626, "s": 9384, "text": "Since the time to process a tuple is very much smaller than the time to fetch the tuple from the storage, particularly in a distributed system, disk access is very often considered as the metric for calculating cost of relational expression." }, { "code": null, "e": 9780, "s": 9626, "text": "Computation of selection operation depends upon the complexity of the selection condition and the availability of indexes on the attributes of the table." }, { "code": null, "e": 9852, "s": 9780, "text": "Following are the computation alternatives depending upon the indexes −" }, { "code": null, "e": 10276, "s": 9852, "text": "No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed." }, { "code": null, "e": 10700, "s": 10276, "text": "No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed." }, { "code": null, "e": 11078, "s": 10700, "text": "B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table." }, { "code": null, "e": 11456, "s": 11078, "text": "B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table." }, { "code": null, "e": 11982, "s": 11456, "text": "Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory." }, { "code": null, "e": 12508, "s": 11982, "text": "Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory." }, { "code": null, "e": 12846, "s": 12508, "text": "When we want to join two tables, say P and Q, each tuple in P has to be compared with each tuple in Q to test if the join condition is satisfied. If the condition is satisfied, the corresponding tuples are concatenated, eliminating duplicate fields and appended to the result relation. Consequently, this is the most expensive operation." }, { "code": null, "e": 12894, "s": 12846, "text": "The common approaches for computing joins are −" }, { "code": null, "e": 13065, "s": 12894, "text": "This is the conventional join approach. It can be illustrated through the following pseudocode (Tables P and Q, with tuples tuple_p and tuple_q and joining attribute a) −" }, { "code": null, "e": 13234, "s": 13065, "text": "For each tuple_p in P \nFor each tuple_q in Q\nIf tuple_p.a = tuple_q.a Then \n Concatenate tuple_p and tuple_q and append to Result \nEnd If \nNext tuple_q \nNext tuple-p " }, { "code": null, "e": 13666, "s": 13234, "text": "In this approach, the two tables are individually sorted based upon the joining attribute and then the sorted tables are merged. External sorting techniques are adopted since the number of records is very high and cannot be accommodated in the memory. Once the individual tables are sorted, one page each of the sorted tables are brought to the memory, merged based upon the joining attribute and the joined tuples are written out." }, { "code": null, "e": 14086, "s": 13666, "text": "This approach comprises of two phases: partitioning phase and probing phase. In partitioning phase, the tables P and Q are broken into two sets of disjoint partitions. A common hash function is decided upon. This hash function is used to assign tuples to partitions. In the probing phase, tuples in a partition of P are compared with the tuples of corresponding partition of Q. If they match, then they are written out." }, { "code": null, "e": 14120, "s": 14086, "text": "\n 49 Lectures \n 11 hours \n" }, { "code": null, "e": 14136, "s": 14120, "text": " Hussein Rashad" }, { "code": null, "e": 14143, "s": 14136, "text": " Print" }, { "code": null, "e": 14154, "s": 14143, "text": " Add Notes" } ]
How to use Font Awesome in Native Android Application?
This example demonstrates how do I use FontAwesome in the native android applications. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="FontAwesome" android:textSize="48sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Create a new download asset folder. Copy-paste the fontAwesome.ttf In the asset folder. Step 4 − Add the following code to src/MainActivity.java package app.com.sample; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Typeface; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textView); Typeface font = Typeface.createFromAsset(getAssets(), "FontAwesome.ttf"); textView.setTypeface(font); } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1149, "s": 1062, "text": "This example demonstrates how do I use FontAwesome in the native android applications." }, { "code": null, "e": 1278, "s": 1149, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1343, "s": 1278, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1921, "s": 1343, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"FontAwesome\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2018, "s": 1921, "text": "Step 3 − Create a new download asset folder. Copy-paste the fontAwesome.ttf In the asset folder." }, { "code": null, "e": 2075, "s": 2018, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2627, "s": 2075, "text": "package app.com.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Typeface;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = findViewById(R.id.textView);\n Typeface font = Typeface.createFromAsset(getAssets(), \"FontAwesome.ttf\");\n textView.setTypeface(font);\n }\n}" }, { "code": null, "e": 2682, "s": 2627, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3355, "s": 2682, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3709, "s": 3355, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
Implementing Capsule Network in TensorFlow | by Parth Rajesh Dedhia | Towards Data Science
We are well aware that Convolution Neural Network(CNN) has outperformed humans in many computer vision tasks. All the CNN based models have the same base architecture of the Convolution layer followed by Pooling layers with intermediate Batch Normalization layers, for normalizing batch in the forward pass and controlling the gradients in the backward pass. However, there were a couple of drawbacks in CNN primarily the Max Pooling layer as it does not consider the relation between pixel having maximum value and its immediate neighbors. To solve the problem, Hinton comes up with the idea of Capsule Network and an algorithm called “Dynamic Routing Between Capsules”. Many resources have explained the intuition and the architecture of the model. You can have a look at them in the series of blog posts here. In this post, I have explained the implementation details of the model. It assumes a good understanding of Tensors and TensorFlow Custom Layers and Models. This post has been structured as follows: Essential TensorFlow Operations Capsule Layer Class Miscellaneous Details Results and Feature Visualization Building a model in TensorFlow 2.3 with a Functional API or Sequential model is quite easy with very few lines of code. However, in this capsule network implementation, we make use of Functional API as well as some custom operations and decorated them with the @tf.function for optimization. In this section, I am just going to highlight the tf.matmul function for higher dimensions. If you are familiar with this, then you can skip this section and move ahead to the next one. For 2D Matrices, the matmul operation performs matrix multiplication operations provided the shape signatures are respected. However, for tensors with rank (r > 2), the operation becomes a combination of 2 operations i.e., element-wise multiplication and matrix multiplication. For a rank (r = 4) matrices, it first performs broadcasting along the axis = [0, 1] and makes each of them of equal shape. And the last two axes ([2,3]) undergo matrix multiplication if and only if the last dimension of the first tensor and the second to last dimension of the second tensor should have the matching dimensions. The example below will explain it, for brevity I have only printed the shapes, but feel free to print and calculate the number on the console. >>> w = tf.reshape(tf.range(48), (1,8,3,2))>>> x = tf.reshape(tf.range(40), (5,1,2,4))>>> tf.matmul(w, x).shapeTensorShape([5, 8, 3, 4]) w is broadcasted along axis=0 and x is broadcasted along axis=1, and the remaining two dimensions were matrix multiplied. Let’s check out the transpose_a/transpose_b parameter of matmul. On calling tf.transpose on a tensor all the dimensions are reversed. For example, >>> a = tf.reshape(tf.range(48), (1,8,3,2))>>> tf.transpose(a).shapeTensorShape([2, 3, 8, 1]) So let’s just see how it work in tf.matmul >>> w = tf.ones((1,10,16,1))>>> x = tf.ones((1152,1,16,1))>>> tf.matmul(w, x, transpose_a=True).shapeTensorShape([1152, 10, 1, 1]) Wait !!! I was expecting an error but it worked out fine. How ??? What TensorFlow did was first it broadcasted along the first two dimensions and then assumed them as a stack of 2D matrices. You could visualize it as transposed being applied only to the last two dimensions, of the first array. The shape of the first array after the transpose operation was [1152, 10, 1, 16] (Transpose applied to the last two-dimension), and now matrix multiplication is applied. By the way, transpose_a = True means the above-mentioned transpose operation will be applied to the first element provided in matmul. Refer to the docs for more details. Okay!! That’s enough to get through this post. We can now check out the code for Capsule Layer. Let’s see what’s happening in the code. Note: All the hyper-parameters are used the same as that from the paper. We have used tf.keras functional API to create the primary capsule outputs. These will just perform simple convolution operation in the forward pass of input image input_x. Till now we have achieved 256 (32 * 8) features maps, each of 6 x 6 size. Now instead of visualizing the above feature map as convolution output, we re-imagine them as 32- 6 x 6 x 8 vectors piled along the last axis. Hence, we could easily obtain 6 * 6 * 32 = 1125, 8D vectors just by reshaping them. Each of these vectors is multiplied by a weight matrix which encapsulates the relation between these lower level features and the higher-level features. The dimension of the output features in the Primary Capsule Layer is 8D, and that input to the Digit Caps layer is 16D. So basically we have to multiply them with a 16 X 8 matrix. Okay, that was easy !! But wait, there are 1152 vectors in the Primary Capsule, which implies we will have 1152–16 x 8 matrices. So are we cool now ?? Nope, you forgot the number of Digits Capsule We have 10 Digit Capsules in the next layer, and hence we will have 10 such 1152–16 x 8 matrices. So basically we get a weight tensor of shape [1152, 10,16, 8]. Each of the 1152–8D vectors of primary capsule output is contributing to each of the 10 Digit Capsules, so we could simply use the same 8D vector for each capsule in the Digit Capsule Layer. More simply we could just add a 2 new axis in 1152, 8D vectors thus converting them into the shape of [1152, 1, 8, 1]. Okay! I see what you did there, you are going to the broadcasting in tf.matmul you described above. Great !! That’s correct. Note: The shape of variable W has an extra dimension of 1 along the first axis since then the same weight has to be broadcasted for the entire batch. In the u_hat, the last dimension is extraneous and was added for the correctness of matrix multiplication and hence can be now be removed using the squeeze function. The (None) in the above shapes is for the batch_size which is determined at training time. Let’s move to the next step. Dynamic Routing — This is where the magic begins! Before exploring the algorithm let’s just make the squash function and keep it for further use. I have added a small value of epsilon to avoid the gradients from exploding in-case if the denominator sums up to zero. In this step, the input to the Digit Capsule is the 16D vector ( u_hat ) and the no of routing iterations (r = 3) is used as specified by the paper. There is not much tweaking in the dynamic routing algorithm, and the code is pretty much a direct implementation of the algorithm in the paper. Have a look at the snippet below. Some key points should be highlighted. The c represents the probability distribution of u_hat values and for a particular capsule in the primary capsule layer, it sums to 1. Simply speaking, the values of u_hat are distributed among the Digit capsule based on the variable c which is trained in the routing algorithm. The Σcij ûj|i is the weighted summation of all the lower level vector which are input to the digit capsule. Since there are 1152 lower level vectors, the reduce_sum function is applied across that dimension. Setting the keep_dims=True, just makes the further computation easier. The squash non-linearity is applied across the 16D vector of Digit Capsule to normalize the values. The next step has a subtle implementation where the dot product between the input and output of the digit capsule layers is calculated. This dot product governs the “agreement” between lower and higher-level capsules. You can understand the reasoning and intuition behind this step here. The above loop is iterated 3 times and the hence obtained values of v are then used in the reconstruction network. Wow !! Great. You have just completed most of the difficult part. Now, it’s relatively simple. The Reconstruction network is a kind of regularizer that regenerates the images from the features of Digit Capsule Layers. While back-propagation it has an impact on the entire network, thus making features good for both prediction as well as regeneration. During training, the model uses the actual label of the input image to mask the digit caps values to zeros except the one corresponding to the label (shown in the figure below). The v tensor from the above network is of shape (None, 1, 10, 16) and we broadcast and label along the 16D vector of the Digit Caps layer, and apply the masking. Note: One hot encoded label is used for masking. This v_masked is then sent to the reconstruction network and which is used for regeneration of the entire image. The reconstruction network is just 3 Dense layer shown in the gist below We will convert the same above code into a CapsuleNetwork Class which inherits from tf.keras.Model. You could directly use the class with your custom training loop and for prediction. As you would have noticed that I have added two different functions predict_capsule_output() and regenerate_image() which predict the digit Caps vectors and regenerate the image respectively. The first function will help in the prediction of numbers during test time and the second one will be helpful to regenerate the image from a given set of input features. (Will be used in the visualization) So one last thing is remaining, and that’s the loss function. The paper uses margin loss for classification and uses the squared difference for reconstruction with a weight of 0.0005 to re-construction loss. The parameters m+, m-, lambda are described in the gist above and the loss function in the gist below. The v is the unmasked Digit Caps Vector, the y is the one_hot_encoded vector of the label and y_image is the actual image send as input to the model. The safe norm function is just a function is similar to the TensorFlow norm function but contains an epsilon to avoid the value from becoming exact 0. Let’s check the summary of the model. Congratulation !!! We have completed the model architecture. The model has 8215568 Parameters which corroborated to the paper where they said that the model with reconstruction has 8.2M parameters. However, this blog has 8238608 parameters. The reason for the difference is that TensorFlow considers only tf.Variable resources in the trainable params. If we consider 1152 * 10 b and 1152 * 10 c as trainable then we get the same number. 8215568 + 11520 + 11520 = 8238608 That’s the same number. Yipee!! We will be using the tf.GradientTape for finding the gradients and we will use the Adam optimizer. Since we have subclassed out class with tf.keras.Model, we can simply call the model.trainable_variables and apply gradients. I have made a custom prediction function that will take the input image as well as the model as a parameter. The purpose of sending the model as a parameter is that the checkpointed model could be used later for prediction. Phew !!! We are done. Congratulations! So, you can now try writing your code with this explanation or use it to one on my repository. You can simply run the notebook on your local system or on google colab. To only obtain prediction accuracy, even 10 epochs are sufficed. In the repository, I have added only a single notebook that trains the feature for 50 epochs. However, to tweak and visualize the feature, you may need to train them up to 100 epochs. Note: The training of the model takes a lot of time even on Google Colab’s GPU. So put the model on training and take a break. The model produces a training accuracy of 99% and the testing accuracy is 98%. However, in some checkpoints, the accuracy is 98.4% while in some other its 97.7%. In the gist below, the index_ means a particular sample number in the test set and index means the actual number which the sample y_test[index_] represents. The code below tweaks each of the feature, and tweaking them in the range of [-0.25, 0.25] with an increment of 0.05. At each point, images are generated and stored in an array. Thus we can see how each feature is contributing to the reconstruction of an image. See some samples of reconstruction in the image below. As we can see, some of the features control the brightness, angle of rotation, thickness, skew, etc. In this article, we have tried to reproduce the results as well as visualize the features described in the paper. The training accuracy is 99% and the testing accuracy is almost 98% which is really great. Although, the model takes a lot of time to train, but the features are very intuitive. Github Repository: https://github.com/dedhiaparth98/capsule-network S. Sabour, N. Frost, G. Hinton, Dynamic Routing Between Capsules (2017), arXiv.
[ { "code": null, "e": 530, "s": 171, "text": "We are well aware that Convolution Neural Network(CNN) has outperformed humans in many computer vision tasks. All the CNN based models have the same base architecture of the Convolution layer followed by Pooling layers with intermediate Batch Normalization layers, for normalizing batch in the forward pass and controlling the gradients in the backward pass." }, { "code": null, "e": 984, "s": 530, "text": "However, there were a couple of drawbacks in CNN primarily the Max Pooling layer as it does not consider the relation between pixel having maximum value and its immediate neighbors. To solve the problem, Hinton comes up with the idea of Capsule Network and an algorithm called “Dynamic Routing Between Capsules”. Many resources have explained the intuition and the architecture of the model. You can have a look at them in the series of blog posts here." }, { "code": null, "e": 1140, "s": 984, "text": "In this post, I have explained the implementation details of the model. It assumes a good understanding of Tensors and TensorFlow Custom Layers and Models." }, { "code": null, "e": 1182, "s": 1140, "text": "This post has been structured as follows:" }, { "code": null, "e": 1214, "s": 1182, "text": "Essential TensorFlow Operations" }, { "code": null, "e": 1234, "s": 1214, "text": "Capsule Layer Class" }, { "code": null, "e": 1256, "s": 1234, "text": "Miscellaneous Details" }, { "code": null, "e": 1290, "s": 1256, "text": "Results and Feature Visualization" }, { "code": null, "e": 1768, "s": 1290, "text": "Building a model in TensorFlow 2.3 with a Functional API or Sequential model is quite easy with very few lines of code. However, in this capsule network implementation, we make use of Functional API as well as some custom operations and decorated them with the @tf.function for optimization. In this section, I am just going to highlight the tf.matmul function for higher dimensions. If you are familiar with this, then you can skip this section and move ahead to the next one." }, { "code": null, "e": 2046, "s": 1768, "text": "For 2D Matrices, the matmul operation performs matrix multiplication operations provided the shape signatures are respected. However, for tensors with rank (r > 2), the operation becomes a combination of 2 operations i.e., element-wise multiplication and matrix multiplication." }, { "code": null, "e": 2517, "s": 2046, "text": "For a rank (r = 4) matrices, it first performs broadcasting along the axis = [0, 1] and makes each of them of equal shape. And the last two axes ([2,3]) undergo matrix multiplication if and only if the last dimension of the first tensor and the second to last dimension of the second tensor should have the matching dimensions. The example below will explain it, for brevity I have only printed the shapes, but feel free to print and calculate the number on the console." }, { "code": null, "e": 2654, "s": 2517, "text": ">>> w = tf.reshape(tf.range(48), (1,8,3,2))>>> x = tf.reshape(tf.range(40), (5,1,2,4))>>> tf.matmul(w, x).shapeTensorShape([5, 8, 3, 4])" }, { "code": null, "e": 2923, "s": 2654, "text": "w is broadcasted along axis=0 and x is broadcasted along axis=1, and the remaining two dimensions were matrix multiplied. Let’s check out the transpose_a/transpose_b parameter of matmul. On calling tf.transpose on a tensor all the dimensions are reversed. For example," }, { "code": null, "e": 3017, "s": 2923, "text": ">>> a = tf.reshape(tf.range(48), (1,8,3,2))>>> tf.transpose(a).shapeTensorShape([2, 3, 8, 1])" }, { "code": null, "e": 3060, "s": 3017, "text": "So let’s just see how it work in tf.matmul" }, { "code": null, "e": 3191, "s": 3060, "text": ">>> w = tf.ones((1,10,16,1))>>> x = tf.ones((1152,1,16,1))>>> tf.matmul(w, x, transpose_a=True).shapeTensorShape([1152, 10, 1, 1])" }, { "code": null, "e": 3257, "s": 3191, "text": "Wait !!! I was expecting an error but it worked out fine. How ???" }, { "code": null, "e": 3826, "s": 3257, "text": "What TensorFlow did was first it broadcasted along the first two dimensions and then assumed them as a stack of 2D matrices. You could visualize it as transposed being applied only to the last two dimensions, of the first array. The shape of the first array after the transpose operation was [1152, 10, 1, 16] (Transpose applied to the last two-dimension), and now matrix multiplication is applied. By the way, transpose_a = True means the above-mentioned transpose operation will be applied to the first element provided in matmul. Refer to the docs for more details." }, { "code": null, "e": 3922, "s": 3826, "text": "Okay!! That’s enough to get through this post. We can now check out the code for Capsule Layer." }, { "code": null, "e": 3962, "s": 3922, "text": "Let’s see what’s happening in the code." }, { "code": null, "e": 4035, "s": 3962, "text": "Note: All the hyper-parameters are used the same as that from the paper." }, { "code": null, "e": 4282, "s": 4035, "text": "We have used tf.keras functional API to create the primary capsule outputs. These will just perform simple convolution operation in the forward pass of input image input_x. Till now we have achieved 256 (32 * 8) features maps, each of 6 x 6 size." }, { "code": null, "e": 4971, "s": 4282, "text": "Now instead of visualizing the above feature map as convolution output, we re-imagine them as 32- 6 x 6 x 8 vectors piled along the last axis. Hence, we could easily obtain 6 * 6 * 32 = 1125, 8D vectors just by reshaping them. Each of these vectors is multiplied by a weight matrix which encapsulates the relation between these lower level features and the higher-level features. The dimension of the output features in the Primary Capsule Layer is 8D, and that input to the Digit Caps layer is 16D. So basically we have to multiply them with a 16 X 8 matrix. Okay, that was easy !! But wait, there are 1152 vectors in the Primary Capsule, which implies we will have 1152–16 x 8 matrices." }, { "code": null, "e": 5039, "s": 4971, "text": "So are we cool now ?? Nope, you forgot the number of Digits Capsule" }, { "code": null, "e": 5610, "s": 5039, "text": "We have 10 Digit Capsules in the next layer, and hence we will have 10 such 1152–16 x 8 matrices. So basically we get a weight tensor of shape [1152, 10,16, 8]. Each of the 1152–8D vectors of primary capsule output is contributing to each of the 10 Digit Capsules, so we could simply use the same 8D vector for each capsule in the Digit Capsule Layer. More simply we could just add a 2 new axis in 1152, 8D vectors thus converting them into the shape of [1152, 1, 8, 1]. Okay! I see what you did there, you are going to the broadcasting in tf.matmul you described above." }, { "code": null, "e": 5635, "s": 5610, "text": "Great !! That’s correct." }, { "code": null, "e": 5785, "s": 5635, "text": "Note: The shape of variable W has an extra dimension of 1 along the first axis since then the same weight has to be broadcasted for the entire batch." }, { "code": null, "e": 6042, "s": 5785, "text": "In the u_hat, the last dimension is extraneous and was added for the correctness of matrix multiplication and hence can be now be removed using the squeeze function. The (None) in the above shapes is for the batch_size which is determined at training time." }, { "code": null, "e": 6071, "s": 6042, "text": "Let’s move to the next step." }, { "code": null, "e": 6121, "s": 6071, "text": "Dynamic Routing — This is where the magic begins!" }, { "code": null, "e": 6337, "s": 6121, "text": "Before exploring the algorithm let’s just make the squash function and keep it for further use. I have added a small value of epsilon to avoid the gradients from exploding in-case if the denominator sums up to zero." }, { "code": null, "e": 6486, "s": 6337, "text": "In this step, the input to the Digit Capsule is the 16D vector ( u_hat ) and the no of routing iterations (r = 3) is used as specified by the paper." }, { "code": null, "e": 6664, "s": 6486, "text": "There is not much tweaking in the dynamic routing algorithm, and the code is pretty much a direct implementation of the algorithm in the paper. Have a look at the snippet below." }, { "code": null, "e": 6703, "s": 6664, "text": "Some key points should be highlighted." }, { "code": null, "e": 6982, "s": 6703, "text": "The c represents the probability distribution of u_hat values and for a particular capsule in the primary capsule layer, it sums to 1. Simply speaking, the values of u_hat are distributed among the Digit capsule based on the variable c which is trained in the routing algorithm." }, { "code": null, "e": 7262, "s": 6982, "text": "The Σcij ûj|i is the weighted summation of all the lower level vector which are input to the digit capsule. Since there are 1152 lower level vectors, the reduce_sum function is applied across that dimension. Setting the keep_dims=True, just makes the further computation easier." }, { "code": null, "e": 7362, "s": 7262, "text": "The squash non-linearity is applied across the 16D vector of Digit Capsule to normalize the values." }, { "code": null, "e": 7650, "s": 7362, "text": "The next step has a subtle implementation where the dot product between the input and output of the digit capsule layers is calculated. This dot product governs the “agreement” between lower and higher-level capsules. You can understand the reasoning and intuition behind this step here." }, { "code": null, "e": 7765, "s": 7650, "text": "The above loop is iterated 3 times and the hence obtained values of v are then used in the reconstruction network." }, { "code": null, "e": 7860, "s": 7765, "text": "Wow !! Great. You have just completed most of the difficult part. Now, it’s relatively simple." }, { "code": null, "e": 8295, "s": 7860, "text": "The Reconstruction network is a kind of regularizer that regenerates the images from the features of Digit Capsule Layers. While back-propagation it has an impact on the entire network, thus making features good for both prediction as well as regeneration. During training, the model uses the actual label of the input image to mask the digit caps values to zeros except the one corresponding to the label (shown in the figure below)." }, { "code": null, "e": 8457, "s": 8295, "text": "The v tensor from the above network is of shape (None, 1, 10, 16) and we broadcast and label along the 16D vector of the Digit Caps layer, and apply the masking." }, { "code": null, "e": 8506, "s": 8457, "text": "Note: One hot encoded label is used for masking." }, { "code": null, "e": 8692, "s": 8506, "text": "This v_masked is then sent to the reconstruction network and which is used for regeneration of the entire image. The reconstruction network is just 3 Dense layer shown in the gist below" }, { "code": null, "e": 8876, "s": 8692, "text": "We will convert the same above code into a CapsuleNetwork Class which inherits from tf.keras.Model. You could directly use the class with your custom training loop and for prediction." }, { "code": null, "e": 9274, "s": 8876, "text": "As you would have noticed that I have added two different functions predict_capsule_output() and regenerate_image() which predict the digit Caps vectors and regenerate the image respectively. The first function will help in the prediction of numbers during test time and the second one will be helpful to regenerate the image from a given set of input features. (Will be used in the visualization)" }, { "code": null, "e": 9585, "s": 9274, "text": "So one last thing is remaining, and that’s the loss function. The paper uses margin loss for classification and uses the squared difference for reconstruction with a weight of 0.0005 to re-construction loss. The parameters m+, m-, lambda are described in the gist above and the loss function in the gist below." }, { "code": null, "e": 9886, "s": 9585, "text": "The v is the unmasked Digit Caps Vector, the y is the one_hot_encoded vector of the label and y_image is the actual image send as input to the model. The safe norm function is just a function is similar to the TensorFlow norm function but contains an epsilon to avoid the value from becoming exact 0." }, { "code": null, "e": 9924, "s": 9886, "text": "Let’s check the summary of the model." }, { "code": null, "e": 10361, "s": 9924, "text": "Congratulation !!! We have completed the model architecture. The model has 8215568 Parameters which corroborated to the paper where they said that the model with reconstruction has 8.2M parameters. However, this blog has 8238608 parameters. The reason for the difference is that TensorFlow considers only tf.Variable resources in the trainable params. If we consider 1152 * 10 b and 1152 * 10 c as trainable then we get the same number." }, { "code": null, "e": 10395, "s": 10361, "text": "8215568 + 11520 + 11520 = 8238608" }, { "code": null, "e": 10427, "s": 10395, "text": "That’s the same number. Yipee!!" }, { "code": null, "e": 10526, "s": 10427, "text": "We will be using the tf.GradientTape for finding the gradients and we will use the Adam optimizer." }, { "code": null, "e": 10652, "s": 10526, "text": "Since we have subclassed out class with tf.keras.Model, we can simply call the model.trainable_variables and apply gradients." }, { "code": null, "e": 10876, "s": 10652, "text": "I have made a custom prediction function that will take the input image as well as the model as a parameter. The purpose of sending the model as a parameter is that the checkpointed model could be used later for prediction." }, { "code": null, "e": 10915, "s": 10876, "text": "Phew !!! We are done. Congratulations!" }, { "code": null, "e": 11332, "s": 10915, "text": "So, you can now try writing your code with this explanation or use it to one on my repository. You can simply run the notebook on your local system or on google colab. To only obtain prediction accuracy, even 10 epochs are sufficed. In the repository, I have added only a single notebook that trains the feature for 50 epochs. However, to tweak and visualize the feature, you may need to train them up to 100 epochs." }, { "code": null, "e": 11459, "s": 11332, "text": "Note: The training of the model takes a lot of time even on Google Colab’s GPU. So put the model on training and take a break." }, { "code": null, "e": 11621, "s": 11459, "text": "The model produces a training accuracy of 99% and the testing accuracy is 98%. However, in some checkpoints, the accuracy is 98.4% while in some other its 97.7%." }, { "code": null, "e": 11778, "s": 11621, "text": "In the gist below, the index_ means a particular sample number in the test set and index means the actual number which the sample y_test[index_] represents." }, { "code": null, "e": 12040, "s": 11778, "text": "The code below tweaks each of the feature, and tweaking them in the range of [-0.25, 0.25] with an increment of 0.05. At each point, images are generated and stored in an array. Thus we can see how each feature is contributing to the reconstruction of an image." }, { "code": null, "e": 12196, "s": 12040, "text": "See some samples of reconstruction in the image below. As we can see, some of the features control the brightness, angle of rotation, thickness, skew, etc." }, { "code": null, "e": 12488, "s": 12196, "text": "In this article, we have tried to reproduce the results as well as visualize the features described in the paper. The training accuracy is 99% and the testing accuracy is almost 98% which is really great. Although, the model takes a lot of time to train, but the features are very intuitive." }, { "code": null, "e": 12556, "s": 12488, "text": "Github Repository: https://github.com/dedhiaparth98/capsule-network" } ]
How to get a Popup Dialog in Tkinter/Python?
Tkinter is a standard Python library that is used to create and develop GUI-based applications. We can create an application in Tkinter and add widgets to it that make the application more interactive. Let's suppose we want to show a popup dialog in an application. In this case, we can use the built-in messagebox module in tkinter. It allows us to show the various dialog boxes such as errors, info box, confirmation boxes, etc. In this example, we've created a button, which upon clicking will show a popup message on the screen. # Import the required library from tkinter import * from tkinter import ttk from tkinter import messagebox # Create an instance of tkinter frame win=Tk() # Set the geometry win.geometry("700x250") # Define a button to show the popup message box def on_click(): messagebox.showinfo("Message", "Hey folks!") # Add a Label widget Label(win, text="Click the button to open a popup", font=('Georgia 13')) # Create a button to open the popup dialog ttk.Button(win, text="Open Popup", command=on_click).pack(pady=30) win.mainloop() Running the above code will display a window with a button to open a dialog box. Click the button to show the popup dialog box on the screen.
[ { "code": null, "e": 1264, "s": 1062, "text": "Tkinter is a standard Python library that is used to create and develop GUI-based applications. We can create an application in Tkinter and add widgets to it that make the application more interactive." }, { "code": null, "e": 1493, "s": 1264, "text": "Let's suppose we want to show a popup dialog in an application. In this case, we can use the built-in messagebox module in tkinter. It allows us to show the various dialog boxes such as errors, info box, confirmation boxes, etc." }, { "code": null, "e": 1595, "s": 1493, "text": "In this example, we've created a button, which upon clicking will show a popup message on the screen." }, { "code": null, "e": 2129, "s": 1595, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n# Create an instance of tkinter frame\nwin=Tk()\n\n# Set the geometry\nwin.geometry(\"700x250\")\n\n# Define a button to show the popup message box\ndef on_click():\n messagebox.showinfo(\"Message\", \"Hey folks!\")\n\n# Add a Label widget\nLabel(win, text=\"Click the button to open a popup\", font=('Georgia 13'))\n\n# Create a button to open the popup dialog\nttk.Button(win, text=\"Open Popup\", command=on_click).pack(pady=30)\n\nwin.mainloop()" }, { "code": null, "e": 2210, "s": 2129, "text": "Running the above code will display a window with a button to open a dialog box." }, { "code": null, "e": 2271, "s": 2210, "text": "Click the button to show the popup dialog box on the screen." } ]
How to format a floating number to fixed width in Python?
You can use string formatting to format floating point numbers to a fixed width in Python. For example, if you want the decimal points to be aligned with width of 12 characters and 4 digits on the right of the decimal, you can use the following: >>> x = 12.35874 >>> print "{:12.4f}".format(x) 12.3587 You can also achieve this result using string interpolation and formatting. For example: >>> x = 12.35874 >>> print "% 12.4f" % x 12.3587
[ { "code": null, "e": 1308, "s": 1062, "text": "You can use string formatting to format floating point numbers to a fixed width in Python. For example, if you want the decimal points to be aligned with width of 12 characters and 4 digits on the right of the decimal, you can use the following:" }, { "code": null, "e": 1369, "s": 1308, "text": ">>> x = 12.35874\n>>> print \"{:12.4f}\".format(x)\n 12.3587" }, { "code": null, "e": 1458, "s": 1369, "text": "You can also achieve this result using string interpolation and formatting. For example:" }, { "code": null, "e": 1512, "s": 1458, "text": ">>> x = 12.35874\n>>> print \"% 12.4f\" % x\n 12.3587" } ]
Creating an Interactive Datetime Filter with Pandas and Streamlit | by M Khorasani | Towards Data Science
Perhaps the most proliferated type of data that we grapple with on a daily basis is time-series data. Basically, anything that is indexed using date, time, or both can be considered as a time-series dataset. And more often than not, you may require to filter your time-series data with, well, date and time themselves. Filtering your data frame based on any other form of index is a rather trivial task; the same cannot be stated about datetime however, especially when the date and time are quoted in different columns. Even after you manage to filter them, it is another task to apply it to your data frame and instantaneously visualize it. Luckily we have Pandas and Streamlit to assist us in this regard in order to create and visualize interactive datetime filters. I assume that most of us are more than familiar with Pandas and possibly use it routinely in our data lives, but I suspect that many are unacquainted with Streamlit given that it is the new kid around the block. Regardless I am going to tender a quick introduction to both lest anyone asks. Pandas is arguably the most agile, efficient, flexible, robust, resilient, and user-friendly binding when it comes to wrestling with data in Python. And in case you think I threw in far too many hyperboles into that previous sentence, then you have greatly underestimated Pandas. This mighty toolkit gives you the ability to manipulate, mutate, transform and not least visualize data in frames, all with a couple of lines of code. In this application, we will use Pandas to read/write our data from/into a CSV file and to resize our data frames based on selected start and end dates/times. Streamlit, as characterized by its founders themselves, is a pure Python API that allows you to create machine learning applications. Wrong. It is actually a lot more than that. Streamlit is a web framework, a quasi-port forwarding proxy server, and a frontend UI library all mixed into one bundle of goodness. Simply put you can develop and deploy countless web apps (or local apps) for a whole slew of purposes. For our application, we will be utilizing Streamlit to render an interactive sliding filter for our time-series data that will also be visualized instantaneously. Without further ado, let’s go ahead and insert the stack of packages we’ll be using. And in case you need to install any of the above packages, please proceed by using ‘pip install’ in Anaconda prompt. pip install streamlit We will be using this randomly generated dataset — CC0 (No Rights Reserved, Public Domain) [1], which has a column for the date, time, and value as shown below. The date is formatted as follows: YYYYMMDD While the time is formatted as: HHMM You can format your datetime with any other formatting that suits your needs, but you will have to make sure that you declare it in your script as explained in the proceeding section. In order to implement our filter, we will use the following function that takes as arguments — message and df which correspond to the message displayed by the slider widget and the raw data frame that needs to be filtered. Initially, we will invoke the Streamlit slider widget which is documented as follows. streamlit.slider(label, min_value, max_value, value, step) Parameters label (str or None) — A short label explaining to the user what this slider is for. min_value (a supported type or None) — The minimum permitted value. Defaults to 0 if the value is an int, 0.0 if a float, value — timedelta(days=14) if a date/datetime, time.min if a time max_value (a supported type or None) — The maximum permitted value. Defaults to 100 if the value is an int, 1.0 if a float, value + timedelta(days=14) if a date/datetime, time.max if a time value (a supported type or a tuple/list of supported types or None) — The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to min_value. step (int/float/timedelta or None) — The stepping interval. Defaults to 1 if the value is an int, 0.01 if a float, timedelta(days=1) if a date/datetime, timedelta(minutes=15) if a time (or if max_value — min_value < 1 day) Please note that our slider will return two values, i.e. the start datetime and end datetime values. Therefore we must declare the initial value of the slider using an array as: [0,len(df)-1] And we must equate the widget to two variables as shown below, i.e. the start and end datetime indices that will be used to filter the data frame: slider_1, slider_2 = st.slider('%s' % (message),0,len(df)-1,[0,len(df)-1],1) Subsequently, we need to remove any trailing decimal places from our start/end time column and add leading zeroes in case the time is less than a whole hour, i.e. 12:00AM quoted as 0, as shown below: while len(str(df.iloc[slider_1][1]).replace('.0','')) < 4: df.iloc[slider_1,1] = '0' + str(df.iloc[slider_1][1]).replace('.0','') Then we need to append our date to time and parse our datetime in a format that is comprehensible by using the datetime.strptime binding in Python as shown below: start_date = datetime.datetime.strptime(str(df.iloc[slider_1][0]).replace('.0','') + str(df.iloc[slider_1][1]).replace('.0',''),'%Y%m%d%H%M%S') To display our selected datetimes we can use the strftime function to reformat the start/end as follows: start_date = start_date.strftime('%d %b %Y, %I:%M%p') In order to use other datetime formatting’s please refer to this article. Finally, we will display the selected datetimes and will apply the filtered indices to our dataset as shown below: st.info('Start: **%s** End: **%s**' % (start_date,end_date)) filtered_df = df.iloc[slider_1:slider_2+1][:].reset_index(drop=True) You may find it convenient to download your filtered data frame as a CSV file. If so please use the following function to create a downloadable file in your Streamlit app. This function’s arguments — name and df correspond to the name of the downloadable file and data frame that needs to be converted to a CSV file respectively. Finally, we can bind everything together in the form of a Streamlit application that will render the datetime filter, data frame, and a line chart that will all be updated instantaneously when we move our sliders. You can run your final app, by typing the following commands in Anaconda prompt. First, change your root directory to where your source code is saved: cd C:/Users/... Then type the following to run your app: streamlit run file_name.py And there you have it, an interactive dashboard that allows you to visually filter your time-series data and visualize it at the same time! If you want to learn more about data visualization and Python, then feel free to check out the following (affiliate linked) courses: www.coursera.org www.coursera.org github.com [1] Khorasani, M. K. (2021, December 28). Interactive Datetime Filter (Version 1) [Randomly generated dataset]. https://github.com/mkhorasani/interactive_datetime_filter/blob/main/data.csv
[ { "code": null, "e": 815, "s": 172, "text": "Perhaps the most proliferated type of data that we grapple with on a daily basis is time-series data. Basically, anything that is indexed using date, time, or both can be considered as a time-series dataset. And more often than not, you may require to filter your time-series data with, well, date and time themselves. Filtering your data frame based on any other form of index is a rather trivial task; the same cannot be stated about datetime however, especially when the date and time are quoted in different columns. Even after you manage to filter them, it is another task to apply it to your data frame and instantaneously visualize it." }, { "code": null, "e": 1234, "s": 815, "text": "Luckily we have Pandas and Streamlit to assist us in this regard in order to create and visualize interactive datetime filters. I assume that most of us are more than familiar with Pandas and possibly use it routinely in our data lives, but I suspect that many are unacquainted with Streamlit given that it is the new kid around the block. Regardless I am going to tender a quick introduction to both lest anyone asks." }, { "code": null, "e": 1824, "s": 1234, "text": "Pandas is arguably the most agile, efficient, flexible, robust, resilient, and user-friendly binding when it comes to wrestling with data in Python. And in case you think I threw in far too many hyperboles into that previous sentence, then you have greatly underestimated Pandas. This mighty toolkit gives you the ability to manipulate, mutate, transform and not least visualize data in frames, all with a couple of lines of code. In this application, we will use Pandas to read/write our data from/into a CSV file and to resize our data frames based on selected start and end dates/times." }, { "code": null, "e": 2401, "s": 1824, "text": "Streamlit, as characterized by its founders themselves, is a pure Python API that allows you to create machine learning applications. Wrong. It is actually a lot more than that. Streamlit is a web framework, a quasi-port forwarding proxy server, and a frontend UI library all mixed into one bundle of goodness. Simply put you can develop and deploy countless web apps (or local apps) for a whole slew of purposes. For our application, we will be utilizing Streamlit to render an interactive sliding filter for our time-series data that will also be visualized instantaneously." }, { "code": null, "e": 2486, "s": 2401, "text": "Without further ado, let’s go ahead and insert the stack of packages we’ll be using." }, { "code": null, "e": 2603, "s": 2486, "text": "And in case you need to install any of the above packages, please proceed by using ‘pip install’ in Anaconda prompt." }, { "code": null, "e": 2625, "s": 2603, "text": "pip install streamlit" }, { "code": null, "e": 2786, "s": 2625, "text": "We will be using this randomly generated dataset — CC0 (No Rights Reserved, Public Domain) [1], which has a column for the date, time, and value as shown below." }, { "code": null, "e": 2820, "s": 2786, "text": "The date is formatted as follows:" }, { "code": null, "e": 2829, "s": 2820, "text": "YYYYMMDD" }, { "code": null, "e": 2861, "s": 2829, "text": "While the time is formatted as:" }, { "code": null, "e": 2866, "s": 2861, "text": "HHMM" }, { "code": null, "e": 3050, "s": 2866, "text": "You can format your datetime with any other formatting that suits your needs, but you will have to make sure that you declare it in your script as explained in the proceeding section." }, { "code": null, "e": 3273, "s": 3050, "text": "In order to implement our filter, we will use the following function that takes as arguments — message and df which correspond to the message displayed by the slider widget and the raw data frame that needs to be filtered." }, { "code": null, "e": 3359, "s": 3273, "text": "Initially, we will invoke the Streamlit slider widget which is documented as follows." }, { "code": null, "e": 3418, "s": 3359, "text": "streamlit.slider(label, min_value, max_value, value, step)" }, { "code": null, "e": 3429, "s": 3418, "text": "Parameters" }, { "code": null, "e": 3513, "s": 3429, "text": "label (str or None) — A short label explaining to the user what this slider is for." }, { "code": null, "e": 3701, "s": 3513, "text": "min_value (a supported type or None) — The minimum permitted value. Defaults to 0 if the value is an int, 0.0 if a float, value — timedelta(days=14) if a date/datetime, time.min if a time" }, { "code": null, "e": 3891, "s": 3701, "text": "max_value (a supported type or None) — The maximum permitted value. Defaults to 100 if the value is an int, 1.0 if a float, value + timedelta(days=14) if a date/datetime, time.max if a time" }, { "code": null, "e": 4233, "s": 3891, "text": "value (a supported type or a tuple/list of supported types or None) — The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to min_value." }, { "code": null, "e": 4456, "s": 4233, "text": "step (int/float/timedelta or None) — The stepping interval. Defaults to 1 if the value is an int, 0.01 if a float, timedelta(days=1) if a date/datetime, timedelta(minutes=15) if a time (or if max_value — min_value < 1 day)" }, { "code": null, "e": 4634, "s": 4456, "text": "Please note that our slider will return two values, i.e. the start datetime and end datetime values. Therefore we must declare the initial value of the slider using an array as:" }, { "code": null, "e": 4648, "s": 4634, "text": "[0,len(df)-1]" }, { "code": null, "e": 4795, "s": 4648, "text": "And we must equate the widget to two variables as shown below, i.e. the start and end datetime indices that will be used to filter the data frame:" }, { "code": null, "e": 4872, "s": 4795, "text": "slider_1, slider_2 = st.slider('%s' % (message),0,len(df)-1,[0,len(df)-1],1)" }, { "code": null, "e": 5072, "s": 4872, "text": "Subsequently, we need to remove any trailing decimal places from our start/end time column and add leading zeroes in case the time is less than a whole hour, i.e. 12:00AM quoted as 0, as shown below:" }, { "code": null, "e": 5205, "s": 5072, "text": "while len(str(df.iloc[slider_1][1]).replace('.0','')) < 4: df.iloc[slider_1,1] = '0' + str(df.iloc[slider_1][1]).replace('.0','')" }, { "code": null, "e": 5368, "s": 5205, "text": "Then we need to append our date to time and parse our datetime in a format that is comprehensible by using the datetime.strptime binding in Python as shown below:" }, { "code": null, "e": 5512, "s": 5368, "text": "start_date = datetime.datetime.strptime(str(df.iloc[slider_1][0]).replace('.0','') + str(df.iloc[slider_1][1]).replace('.0',''),'%Y%m%d%H%M%S')" }, { "code": null, "e": 5617, "s": 5512, "text": "To display our selected datetimes we can use the strftime function to reformat the start/end as follows:" }, { "code": null, "e": 5671, "s": 5617, "text": "start_date = start_date.strftime('%d %b %Y, %I:%M%p')" }, { "code": null, "e": 5860, "s": 5671, "text": "In order to use other datetime formatting’s please refer to this article. Finally, we will display the selected datetimes and will apply the filtered indices to our dataset as shown below:" }, { "code": null, "e": 6005, "s": 5860, "text": "st.info('Start: **%s** End: **%s**' % (start_date,end_date)) filtered_df = df.iloc[slider_1:slider_2+1][:].reset_index(drop=True)" }, { "code": null, "e": 6177, "s": 6005, "text": "You may find it convenient to download your filtered data frame as a CSV file. If so please use the following function to create a downloadable file in your Streamlit app." }, { "code": null, "e": 6335, "s": 6177, "text": "This function’s arguments — name and df correspond to the name of the downloadable file and data frame that needs to be converted to a CSV file respectively." }, { "code": null, "e": 6549, "s": 6335, "text": "Finally, we can bind everything together in the form of a Streamlit application that will render the datetime filter, data frame, and a line chart that will all be updated instantaneously when we move our sliders." }, { "code": null, "e": 6700, "s": 6549, "text": "You can run your final app, by typing the following commands in Anaconda prompt. First, change your root directory to where your source code is saved:" }, { "code": null, "e": 6716, "s": 6700, "text": "cd C:/Users/..." }, { "code": null, "e": 6757, "s": 6716, "text": "Then type the following to run your app:" }, { "code": null, "e": 6784, "s": 6757, "text": "streamlit run file_name.py" }, { "code": null, "e": 6924, "s": 6784, "text": "And there you have it, an interactive dashboard that allows you to visually filter your time-series data and visualize it at the same time!" }, { "code": null, "e": 7057, "s": 6924, "text": "If you want to learn more about data visualization and Python, then feel free to check out the following (affiliate linked) courses:" }, { "code": null, "e": 7074, "s": 7057, "text": "www.coursera.org" }, { "code": null, "e": 7091, "s": 7074, "text": "www.coursera.org" }, { "code": null, "e": 7102, "s": 7091, "text": "github.com" } ]
Check if variable is tuple in Python
When it is required to check if a variable is a tuple, the 'type' method can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access. The 'type' method checks to see the type of the iterable/value that is passed to it as an argument. Below is a demonstration of the same − Live Demo my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4) print ("The tuple is : " ) print(my_tuple_1) my_result = type(my_tuple_1) is tuple print("Is the given variable a tuple ? ") print(my_result) The tuple is : (7, 8, 0, 3, 45, 3, 2, 22, 4) Is the given variable a tuple ? True A tuple is defined, and is displayed on the console. The type of the tuple is examined, and the 'is' and 'tuple' operators are used to check if it is a tuple type. This result is assigned to a value. It is displayed as output on the console.
[ { "code": null, "e": 1388, "s": 1062, "text": "When it is required to check if a variable is a tuple, the 'type' method can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access." }, { "code": null, "e": 1488, "s": 1388, "text": "The 'type' method checks to see the type of the iterable/value that is passed to it as an argument." }, { "code": null, "e": 1527, "s": 1488, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1537, "s": 1527, "text": "Live Demo" }, { "code": null, "e": 1725, "s": 1537, "text": "my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)\n\nprint (\"The tuple is : \" )\nprint(my_tuple_1)\n\nmy_result = type(my_tuple_1) is tuple\n\nprint(\"Is the given variable a tuple ? \")\nprint(my_result)" }, { "code": null, "e": 1807, "s": 1725, "text": "The tuple is :\n(7, 8, 0, 3, 45, 3, 2, 22, 4)\nIs the given variable a tuple ?\nTrue" }, { "code": null, "e": 1860, "s": 1807, "text": "A tuple is defined, and is displayed on the console." }, { "code": null, "e": 1971, "s": 1860, "text": "The type of the tuple is examined, and the 'is' and 'tuple' operators are used to check if it is a tuple type." }, { "code": null, "e": 2007, "s": 1971, "text": "This result is assigned to a value." }, { "code": null, "e": 2049, "s": 2007, "text": "It is displayed as output on the console." } ]
PyQt5 – How to change background color of Main window ? - GeeksforGeeks
26 Mar, 2020 The first step in creating desktop applications with PyQt is getting a window to show up on your desktop, in this article, we will see how we can change the color of this window. In order to change the color of the main window we use setStylesheet() method. Syntax : setStyleSheet(“background-color: grey;”) Argument : It takes string as an argument. Example #1: # importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # changing the background color to yellow self.setStyleSheet("background-color: yellow;") # set the title self.setWindowTitle("Color") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel("Yellow", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet("border: 1px solid black;") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Example #2: # importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # changing the background color to cyan self.setStyleSheet("background-color: cyan;") # set the title self.setWindowTitle("Color") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel("Cyan", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet("border: 1px solid black;") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists sum() function in Python How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python How To Convert Python Dictionary To JSON? Graph Plotting in Python | Set 1 Print lists in Python (4 Different Ways) Check if element exists in list in Python
[ { "code": null, "e": 24459, "s": 24431, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24717, "s": 24459, "text": "The first step in creating desktop applications with PyQt is getting a window to show up on your desktop, in this article, we will see how we can change the color of this window. In order to change the color of the main window we use setStylesheet() method." }, { "code": null, "e": 24767, "s": 24717, "text": "Syntax : setStyleSheet(“background-color: grey;”)" }, { "code": null, "e": 24810, "s": 24767, "text": "Argument : It takes string as an argument." }, { "code": null, "e": 24822, "s": 24810, "text": "Example #1:" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # changing the background color to yellow self.setStyleSheet(\"background-color: yellow;\") # set the title self.setWindowTitle(\"Color\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel(\"Yellow\", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet(\"border: 1px solid black;\") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25701, "s": 24822, "text": null }, { "code": null, "e": 25722, "s": 25701, "text": "Output : Example #2:" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # changing the background color to cyan self.setStyleSheet(\"background-color: cyan;\") # set the title self.setWindowTitle(\"Color\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel(\"Cyan\", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet(\"border: 1px solid black;\") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26595, "s": 25722, "text": null }, { "code": null, "e": 26604, "s": 26595, "text": "Output :" }, { "code": null, "e": 26615, "s": 26604, "text": "Python-gui" }, { "code": null, "e": 26627, "s": 26615, "text": "Python-PyQt" }, { "code": null, "e": 26634, "s": 26627, "text": "Python" }, { "code": null, "e": 26732, "s": 26634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26741, "s": 26732, "text": "Comments" }, { "code": null, "e": 26754, "s": 26741, "text": "Old Comments" }, { "code": null, "e": 26786, "s": 26754, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26828, "s": 26786, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26865, "s": 26828, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26890, "s": 26865, "text": "sum() function in Python" }, { "code": null, "e": 26946, "s": 26890, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26975, "s": 26946, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27017, "s": 26975, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27050, "s": 27017, "text": "Graph Plotting in Python | Set 1" }, { "code": null, "e": 27091, "s": 27050, "text": "Print lists in Python (4 Different Ways)" } ]
tcpdump - Unix, Linux Command
Tcpdump prints out the headers of packets on a network interface that match the boolean expression. It can also be run with the -w flag, which causes it to save the packet data to a file for later analysis, and/or with the -r flag, which causes it to read from a saved packet file rather than to read packets from a network interface. In all cases, only packets that match expression will be processed by tcpdump. Tcpdump will, if not run with the -c flag, continue capturing packets until it is interrupted by a SIGINT signal (generated, for example, by typing your interrupt character, typically control-C) or a SIGTERM signal (typically generated with the kill(1) command); if run with the -c flag, it will capture packets until it is interrupted by a SIGINT or SIGTERM signal or the specified number of packets have been processed. When tcpdump finishes capturing packets, it will report counts of: Note that when used with -Z option (enabled by default), privileges are dropped before opening first savefile. The expression consists of one or more primitives. Primitives usually consist of an id (name or number) preceded by one or more qualifiers. There are three different kinds of qualifier: ip host host ether proto \ip and host host ether host ehost and not host host tcp src port port len <= length. len >= length. ip6 protochain 6 ether proto p ether proto p vlan 100 && vlan 200 vlan && vlan 300 && ip mpls 100000 && mpls 1024 mpls && mpls 1024 && host 192.9.200.1 pppoes && ip ip proto p or ip6 proto p iso proto p proto [ expr : size ] For example, ‘ether[0] & 1 != 0’ catches all multicast traffic. The expression ‘ip[0] & 0xf != 5’ catches all IPv4 packets with options. The expression ‘ip[6:2] & 0x1fff = 0’ catches only unfragmented IPv4 datagrams and frag zero of fragmented IPv4 datagrams. This check is implicitly applied to the tcp and udp index operations. For instance, tcp[0] always means the first byte of the TCP header, and never means the first byte of an intervening fragment. Some offsets and field values may be expressed as names rather than as numeric values. The following protocol header field offsets are available: icmptype (ICMP type field), icmpcode (ICMP code field), and tcpflags (TCP flags field). The following ICMP type field values are available: icmp-echoreply, icmp-unreach, icmp-sourcequench, icmp-redirect, icmp-echo, icmp-routeradvert, icmp-routersolicit, icmp-timxceed, icmp-paramprob, icmp-tstamp, icmp-tstampreply, icmp-ireq, icmp-ireqreply, icmp-maskreq, icmp-maskreply. The following TCP flags field values are available: tcp-fin, tcp-syn, tcp-rst, tcp-push, tcp-ack, tcp-urg. If an identifier is given without a keyword, the most recent keyword is assumed. For example, not host vs and ace not host vs and host ace not ( host vs or ace ) Expression arguments can be passed to tcpdump as either a single argument or as multiple arguments, whichever is more convenient. Generally, if the expression contains Shell metacharacters, it is easier to pass it as a single, quoted argument. Multiple arguments are concatenated with spaces before being parsed. To print all packets arriving at or departing from sundown: tcpdump host sundown To print traffic between helios and either hot or ace: tcpdump host helios and \( hot or ace \) To print all IP packets between ace and any host except helios: tcpdump ip host ace and not helios To print all traffic between local hosts and hosts at Berkeley: tcpdump net ucb-ether To print all ftp traffic through internet gateway snup: (note that the expression is quoted to prevent the shell from (mis-)interpreting the parentheses): tcpdump ’gateway snup and (port ftp or ftp-data)’ To print traffic neither sourced from nor destined for local hosts (if you gateway to one other net, this stuff should never make it onto your local net). tcpdump ip and not net localnet To print the start and end packets (the SYN and FIN packets) of each TCP conversation that involves a non-local host. tcpdump ’tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net localnet’ To print all IPv4 HTTP packets to and from port 80, i.e. print only packets that contain data, not, for example, SYN and FIN packets and ACK-only packets. (IPv6 is left as an exercise for the reader.) tcpdump ’tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)’ To print IP packets longer than 576 bytes sent through gateway snup: tcpdump ’gateway snup and ip[2:2] > 576’ To print IP broadcast or multicast packets that were not sent via Ethernet broadcast or multicast: tcpdump ’ether[0] & 1 = 0 and ip[16] >= 224’ To print all ICMP packets that are not echo requests/replies (i.e., not ping packets): tcpdump ’icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply’ The output of tcpdump is protocol dependent. The following gives a brief description and examples of most of the formats. Link Level Headers If the ’-e’ option is given, the link level header is printed out. On Ethernets, the source and destination addresses, protocol, and packet length are printed. On FDDI networks, the ’-e’ option causes tcpdump to print the ‘frame control’ field, the source and destination addresses, and the packet length. (The ‘frame control’ field governs the interpretation of the rest of the packet. Normal packets (such as those containing IP datagrams) are ‘async’ packets, with a priority value between 0 and 7; for example, ‘async4’. Such packets are assumed to contain an 802.2 Logical Link Control (LLC) packet; the LLC header is printed if it is not an ISO datagram or a so-called SNAP packet. On Token Ring networks, the ’-e’ option causes tcpdump to print the ‘access control’ and ‘frame control’ fields, the source and destination addresses, and the packet length. As on FDDI networks, packets are assumed to contain an LLC packet. Regardless of whether the ’-e’ option is specified or not, the source routing information is printed for source-routed packets. On 802.11 networks, the ’-e’ option causes tcpdump to print the ‘frame control’ fields, all of the addresses in the 802.11 header, and the packet length. As on FDDI networks, packets are assumed to contain an LLC packet. (N.B.: The following description assumes familiarity with the SLIP compression algorithm described in RFC-1144.) On SLIP links, a direction indicator (‘‘I’’ for inbound, ‘‘O’’ for outbound), packet type, and compression information are printed out. The packet type is printed first. The three types are ip, utcp, and ctcp. No further link information is printed for ip packets. For TCP packets, the connection identifier is printed following the type. If the packet is compressed, its encoded header is printed out. The special cases are printed out as *S+n and *SA+n, where n is the amount by which the sequence number (or sequence number and ack) has changed. If it is not a special case, zero or more changes are printed. A change is indicated by U (urgent pointer), W (window), A (ack), S (sequence number), and I (packet ID), followed by a delta (+n or -n), or a new value (=n). Finally, the amount of data in the packet and compressed header length are printed. For example, the following line shows an outbound compressed TCP packet, with an implicit connection identifier; the ack has changed by 6, the sequence number by 49, and the packet ID by 6; there are 3 bytes of data and 6 bytes of compressed header: O ctcp * A+6 S+49 I+6 3 (6) ARP/RARP Packets Arp/rarp output shows the type of request and its arguments. The format is intended to be self explanatory. Here is a short sample taken from the start of an ‘rlogin’ from host rtsg to host csam: arp who-has csam tell rtsg arp reply csam is-at CSAM arp who-has csam tell rtsg arp reply csam is-at CSAM This would look less redundant if we had done tcpdump -n: arp who-has 128.3.254.6 tell 128.3.254.68 arp reply 128.3.254.6 is-at 02:07:01:00:01:c4 arp who-has 128.3.254.6 tell 128.3.254.68 arp reply 128.3.254.6 is-at 02:07:01:00:01:c4 If we had done tcpdump -e, the fact that the first packet is broadcast and the second is point-to-point would be visible: RTSG Broadcast 0806 64: arp who-has csam tell rtsg CSAM RTSG 0806 64: arp reply csam is-at CSAM RTSG Broadcast 0806 64: arp who-has csam tell rtsg CSAM RTSG 0806 64: arp reply csam is-at CSAM TCP Packets (N.B.:The following description assumes familiarity with the TCP protocol described in RFC-793. If you are not familiar with the protocol, neither this description nor tcpdump will be of much use to you.) The general format of a tcp protocol line is: src > dst: flags data-seqno ack window urgent options src > dst: flags data-seqno ack window urgent options Src, dst and flags are always present. The other fields depend on the contents of the packet’s tcp protocol header and are output only if appropriate. Here is the opening portion of an rlogin from host rtsg to host csam. rtsg.1023 > csam.login: S 768512:768512(0) win 4096 <mss 1024> csam.login > rtsg.1023: S 947648:947648(0) ack 768513 win 4096 <mss 1024> rtsg.1023 > csam.login: . ack 1 win 4096 rtsg.1023 > csam.login: P 1:2(1) ack 1 win 4096 csam.login > rtsg.1023: . ack 2 win 4096 rtsg.1023 > csam.login: P 2:21(19) ack 1 win 4096 csam.login > rtsg.1023: P 1:2(1) ack 21 win 4077 csam.login > rtsg.1023: P 2:3(1) ack 21 win 4077 urg 1 csam.login > rtsg.1023: P 3:4(1) ack 21 win 4077 urg 1 rtsg.1023 > csam.login: S 768512:768512(0) win 4096 <mss 1024> csam.login > rtsg.1023: S 947648:947648(0) ack 768513 win 4096 <mss 1024> rtsg.1023 > csam.login: . ack 1 win 4096 rtsg.1023 > csam.login: P 1:2(1) ack 1 win 4096 csam.login > rtsg.1023: . ack 2 win 4096 rtsg.1023 > csam.login: P 2:21(19) ack 1 win 4096 csam.login > rtsg.1023: P 1:2(1) ack 21 win 4077 csam.login > rtsg.1023: P 2:3(1) ack 21 win 4077 urg 1 csam.login > rtsg.1023: P 3:4(1) ack 21 win 4077 urg 1 Csam replies with a similar packet except it includes a piggy-backed ack for rtsg’s SYN. Rtsg then acks csam’s SYN. The ‘.’ means no flags were set. The packet contained no data so there is no data sequence number. Note that the ack sequence number is a small integer (1). The first time tcpdump sees a tcp ‘conversation’, it prints the sequence number from the packet. On subsequent packets of the conversation, the difference between the current packet’s sequence number and this initial sequence number is printed. This means that sequence numbers after the first can be interpreted as relative byte positions in the conversation’s data stream (with the first data byte each direction being ‘1’). ‘-S’ will override this feature, causing the original sequence numbers to be output. On the 6th line, rtsg sends csam 19 bytes of data (bytes 2 through 20 in the rtsg -> csam side of the conversation). The PUSH flag is set in the packet. On the 7th line, csam says it’s received data sent by rtsg up to but not including byte 21. Most of this data is apparently sitting in the socket buffer since csam’s receive window has gotten 19 bytes smaller. Csam also sends one byte of data to rtsg in this packet. On the 8th and 9th lines, csam sends two bytes of urgent, pushed data to rtsg. If the snapshot was small enough that tcpdump didn’t capture the full TCP header, it interprets as much of the header as it can and then reports ‘‘[|tcp]’’ to indicate the remainder could not be interpreted. If the header contains a bogus option (one with a length that’s either too small or beyond the end of the header), tcpdump reports it as ‘‘[bad opt]’’ and does not interpret any further options (since it’s impossible to tell where they start). If the header length indicates options are present but the IP datagram length is not long enough for the options to actually be there, tcpdump reports it as ‘‘[bad hdr length]’’. Capturing TCP packets with particular flag combinations (SYN-ACK, URG-ACK, etc.) There are 8 bits in the control bits section of the TCP header: 0 15 31 ----------------------------------------------------------------- | source port | destination port | ----------------------------------------------------------------- | sequence number | ----------------------------------------------------------------- | acknowledgment number | ----------------------------------------------------------------- | HL | rsvd |C|E|U|A|P|R|S|F| window size | ----------------------------------------------------------------- | TCP checksum | urgent pointer | ----------------------------------------------------------------- 0 7| 15| 23| 31 ----------------|---------------|---------------|---------------- | HL | rsvd |C|E|U|A|P|R|S|F| window size | ----------------|---------------|---------------|---------------- | | 13th octet | | | | | |---------------| |C|E|U|A|P|R|S|F| |---------------| |7 5 3 0| |C|E|U|A|P|R|S|F| |---------------| |0 0 0 0 0 0 1 0| |---------------| |7 6 5 4 3 2 1 0| 7 6 5 4 3 2 1 0 0*2 + 0*2 + 0*2 + 0*2 + 0*2 + 0*2 + 1*2 + 0*2 = 2 |C|E|U|A|P|R|S|F| |---------------| |0 0 0 1 0 0 1 0| |---------------| |7 6 5 4 3 2 1 0| 7 6 5 4 3 2 1 0 0*2 + 0*2 + 0*2 + 1*2 + 0*2 + 0*2 + 1*2 + 0*2 = 18 00010010 SYN-ACK 00000010 SYN AND 00000010 (we want SYN) AND 00000010 (we want SYN) -------- -------- = 00000010 = 00000010 00010010 SYN-ACK 00000010 SYN AND 00000010 (we want SYN) AND 00000010 (we want SYN) -------- -------- = 00000010 = 00000010 UDP Packets actinide.who > broadcast.who: udp 84 actinide.who > broadcast.who: udp 84 UDP Name Server Requests src > dst: id op? flags qtype qclass name (len) h2opolo.1538 > helios.domain: 3+ A? ucbvax.berkeley.edu. (37) src > dst: id op? flags qtype qclass name (len) h2opolo.1538 > helios.domain: 3+ A? ucbvax.berkeley.edu. (37) UDP Name Server Responses src > dst: id op rcode flags a/n/au type class data (len) helios.domain > h2opolo.1538: 3 3/3/7 A 128.32.137.3 (273) helios.domain > h2opolo.1537: 2 NXDomain* 0/1/0 (97) src > dst: id op rcode flags a/n/au type class data (len) helios.domain > h2opolo.1538: 3 3/3/7 A 128.32.137.3 (273) helios.domain > h2opolo.1537: 2 NXDomain* 0/1/0 (97) SMB/CIFS decoding By default a fairly minimal decode is done, with a much more detailed decode done if -v is used. Be warned that with -v a single SMB packet may take up a page or more, so only use -v if you really want all the gory details. For information on SMB packet formats and what all te fields mean see www.cifs.org or the pub/samba/specs/ directory on your favorite samba.org mirror site. The SMB patches were written by Andrew Tridgell ([email protected]). NFS Requests and Replies src.xid > dst.nfs: len op args src.nfs > dst.xid: reply stat len op results sushi.6709 > wrl.nfs: 112 readlink fh 21,24/10.73165 wrl.nfs > sushi.6709: reply ok 40 readlink "../var" sushi.201b > wrl.nfs: 144 lookup fh 9,74/4096.6878 "xcolors" wrl.nfs > sushi.201b: reply ok 128 lookup fh 9,74/4134.3150 src.xid > dst.nfs: len op args src.nfs > dst.xid: reply stat len op results sushi.6709 > wrl.nfs: 112 readlink fh 21,24/10.73165 wrl.nfs > sushi.6709: reply ok 40 readlink "../var" sushi.201b > wrl.nfs: 144 lookup fh 9,74/4096.6878 "xcolors" wrl.nfs > sushi.201b: reply ok 128 lookup fh 9,74/4134.3150 sushi.1372a > wrl.nfs: 148 read fh 21,11/12.195 8192 bytes @ 24576 wrl.nfs > sushi.1372a: reply ok 1472 read REG 100664 ids 417/0 sz 29388 sushi.1372a > wrl.nfs: 148 read fh 21,11/12.195 8192 bytes @ 24576 wrl.nfs > sushi.1372a: reply ok 1472 read REG 100664 ids 417/0 sz 29388 AFS Requests and Replies src.sport > dst.dport: rx packet-type src.sport > dst.dport: rx packet-type service call call-name args src.sport > dst.dport: rx packet-type service reply call-name args elvis.7001 > pike.afsfs: rx data fs call rename old fid 536876964/1/1 ".newsrc.new" new fid 536876964/1/1 ".newsrc" pike.afsfs > elvis.7001: rx data fs reply rename src.sport > dst.dport: rx packet-type src.sport > dst.dport: rx packet-type service call call-name args src.sport > dst.dport: rx packet-type service reply call-name args elvis.7001 > pike.afsfs: rx data fs call rename old fid 536876964/1/1 ".newsrc.new" new fid 536876964/1/1 ".newsrc" pike.afsfs > elvis.7001: rx data fs reply rename KIP AppleTalk (DDP in UDP) number name 1.254 ether 16.1 icsd-net 1.254.110 ace number name 1.254 ether 16.1 icsd-net 1.254.110 ace net.host.port 144.1.209.2 > icsd-net.112.220 office.2 > icsd-net.112.220 jssmag.149.235 > icsd-net.2 net.host.port 144.1.209.2 > icsd-net.112.220 office.2 > icsd-net.112.220 jssmag.149.235 > icsd-net.2 NBP packets are formatted like the following examples: icsd-net.112.220 > jssmag.2: nbp-lkup 190: "=:LaserWriter@*" jssmag.209.2 > icsd-net.112.220: nbp-reply 190: "RM1140:LaserWriter@*" 250 techpit.2 > icsd-net.112.220: nbp-reply 190: "techpit:LaserWriter@*" 186 icsd-net.112.220 > jssmag.2: nbp-lkup 190: "=:LaserWriter@*" jssmag.209.2 > icsd-net.112.220: nbp-reply 190: "RM1140:LaserWriter@*" 250 techpit.2 > icsd-net.112.220: nbp-reply 190: "techpit:LaserWriter@*" 186 ATP packet formatting is demonstrated by the following example: jssmag.209.165 > helios.132: atp-req 12266<0-7> 0xae030001 helios.132 > jssmag.209.165: atp-resp 12266:0 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:1 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:2 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:4 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:6 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp*12266:7 (512) 0xae040000 jssmag.209.165 > helios.132: atp-req 12266<3,5> 0xae030001 helios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000 jssmag.209.165 > helios.132: atp-rel 12266<0-7> 0xae030001 jssmag.209.133 > helios.132: atp-req* 12267<0-7> 0xae030002 jssmag.209.165 > helios.132: atp-req 12266<0-7> 0xae030001 helios.132 > jssmag.209.165: atp-resp 12266:0 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:1 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:2 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:4 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:6 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp*12266:7 (512) 0xae040000 jssmag.209.165 > helios.132: atp-req 12266<3,5> 0xae030001 helios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000 helios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000 jssmag.209.165 > helios.132: atp-rel 12266<0-7> 0xae030001 jssmag.209.133 > helios.132: atp-req* 12267<0-7> 0xae030002 IP Fragmentation (frag id:size@offset+) (frag id:size@offset) (frag id:size@offset+) (frag id:size@offset) arizona.ftp-data > rtsg.1170: . 1024:1332(308) ack 1 win 4096 (frag 595a:328@0+) arizona > rtsg: (frag 595a:204@328) rtsg.1170 > arizona.ftp-data: . ack 1536 win 2560 arizona.ftp-data > rtsg.1170: . 1024:1332(308) ack 1 win 4096 (frag 595a:328@0+) arizona > rtsg: (frag 595a:204@328) rtsg.1170 > arizona.ftp-data: . ack 1536 win 2560 Timestamps hh:mm:ss.frac Van Jacobson, Craig Leres and Steven McCanne, all of the Lawrence Berkeley National Laboratory, University of California, Berkeley, CA. It is currently being maintained by tcpdump.org. The current version is available via http: http://www.tcpdump.org/ The original distribution is available via anonymous ftp: ftp://ftp.ee.lbl.gov/tcpdump.tar.Z IPv6/IPsec support is added by WIDE/KAME project. This program uses Eric Young’s SSLeay library, under specific configuration. [email protected] Please send source code contributions, etc. to: [email protected] NIT doesn’t let you watch your own outbound traffic, BPF will. We recommend that you use the latter. On Linux systems with 2.0[.x] kernels: Some attempt should be made to reassemble IP fragments or, at least to compute the right length for the higher level protocol. Name server inverse queries are not dumped correctly: the (empty) question section is printed rather than real query in the answer section. Some believe that inverse queries are themselves a bug and prefer to fix the program generating them rather than tcpdump. A packet trace that crosses a daylight savings time change will give skewed time stamps (the time change is ignored). Filter expressions on fields other than those in Token Ring headers will not correctly handle source-routed Token Ring packets. Filter expressions on fields other than those in 802.11 headers will not correctly handle 802.11 data packets with both To DS and From DS set. ip6 proto should chase header chain, but at this moment it does not. ip6 protochain is supplied for this behavior. Arithmetic expression against transport layer headers, like tcp[0], does not work against IPv6 packets. It only looks at IPv4 packets. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10995, "s": 10577, "text": "\nTcpdump prints out the headers of packets on a network interface\nthat match the boolean expression. It can also be run with the\n-w flag, which causes it to save the packet data to a file for later\nanalysis, and/or with the\n-r flag, which causes it to read from a saved packet file rather than to\nread packets from a network interface. In all cases, only packets that\nmatch\nexpression will be processed by\ntcpdump. " }, { "code": null, "e": 11419, "s": 10995, "text": "\nTcpdump will, if not run with the\n-c flag, continue capturing packets until it is interrupted by a SIGINT\nsignal (generated, for example, by typing your interrupt character,\ntypically control-C) or a SIGTERM signal (typically generated with the\nkill(1)\ncommand); if run with the\n-c flag, it will capture packets until it is interrupted by a SIGINT or\nSIGTERM signal or the specified number of packets have been processed.\n" }, { "code": null, "e": 11488, "s": 11419, "text": "\nWhen\ntcpdump finishes capturing packets, it will report counts of:\n" }, { "code": null, "e": 11601, "s": 11488, "text": "\nNote that when used with -Z option (enabled by default), privileges\nare dropped before opening first savefile.\n" }, { "code": null, "e": 11791, "s": 11603, "text": "\nThe expression consists of one or more\nprimitives. Primitives usually consist of an\nid (name or number) preceded by one or more qualifiers.\nThere are three\ndifferent kinds of qualifier:\n" }, { "code": null, "e": 11805, "s": 11791, "text": "ip host host\n" }, { "code": null, "e": 11836, "s": 11805, "text": "ether proto \\ip and host host\n" }, { "code": null, "e": 11872, "s": 11836, "text": "ether host ehost and not host host\n" }, { "code": null, "e": 11891, "s": 11872, "text": "tcp src port port\n" }, { "code": null, "e": 11907, "s": 11891, "text": "len <= length.\n" }, { "code": null, "e": 11923, "s": 11907, "text": "len >= length.\n" }, { "code": null, "e": 11941, "s": 11923, "text": "ip6 protochain 6\n" }, { "code": null, "e": 11956, "s": 11941, "text": "ether proto p\n" }, { "code": null, "e": 11971, "s": 11956, "text": "ether proto p\n" }, { "code": null, "e": 11993, "s": 11971, "text": "vlan 100 && vlan 200\n" }, { "code": null, "e": 12017, "s": 11993, "text": "vlan && vlan 300 && ip\n" }, { "code": null, "e": 12043, "s": 12017, "text": "mpls 100000 && mpls 1024\n" }, { "code": null, "e": 12082, "s": 12043, "text": "mpls && mpls 1024 && host 192.9.200.1\n" }, { "code": null, "e": 12096, "s": 12082, "text": "pppoes && ip\n" }, { "code": null, "e": 12123, "s": 12096, "text": "ip proto p or ip6 proto p\n" }, { "code": null, "e": 12136, "s": 12123, "text": "iso proto p\n" }, { "code": null, "e": 12159, "s": 12136, "text": "proto [ expr : size ]\n" }, { "code": null, "e": 12618, "s": 12159, "text": "\nFor example, ‘ether[0] & 1 != 0’ catches all multicast traffic.\nThe expression ‘ip[0] & 0xf != 5’\ncatches all IPv4 packets with options.\nThe expression\n‘ip[6:2] & 0x1fff = 0’\ncatches only unfragmented IPv4 datagrams and frag zero of fragmented\nIPv4 datagrams.\nThis check is implicitly applied to the tcp and udp\nindex operations.\nFor instance, tcp[0] always means the first\nbyte of the TCP header, and never means the first byte of an\nintervening fragment.\n" }, { "code": null, "e": 12854, "s": 12618, "text": "\nSome offsets and field values may be expressed as names rather than\nas numeric values.\nThe following protocol header field offsets are\navailable: icmptype (ICMP type field), icmpcode (ICMP\ncode field), and tcpflags (TCP flags field).\n" }, { "code": null, "e": 13141, "s": 12854, "text": "\nThe following ICMP type field values are available: icmp-echoreply,\nicmp-unreach, icmp-sourcequench, icmp-redirect,\nicmp-echo, icmp-routeradvert, icmp-routersolicit,\nicmp-timxceed, icmp-paramprob, icmp-tstamp,\nicmp-tstampreply, icmp-ireq, icmp-ireqreply,\nicmp-maskreq, icmp-maskreply.\n" }, { "code": null, "e": 13250, "s": 13141, "text": "\nThe following TCP flags field values are available: tcp-fin,\ntcp-syn, tcp-rst, tcp-push,\ntcp-ack, tcp-urg.\n" }, { "code": null, "e": 13347, "s": 13250, "text": "\nIf an identifier is given without a keyword, the most recent keyword\nis assumed.\nFor example,\n\n" }, { "code": null, "e": 13368, "s": 13347, "text": "not host vs and ace\n" }, { "code": null, "e": 13394, "s": 13368, "text": "not host vs and host ace\n" }, { "code": null, "e": 13418, "s": 13394, "text": "not ( host vs or ace )\n" }, { "code": null, "e": 13733, "s": 13418, "text": "\nExpression arguments can be passed to tcpdump as either a single\nargument or as multiple arguments, whichever is more convenient.\nGenerally, if the expression contains Shell metacharacters, it is\neasier to pass it as a single, quoted argument.\nMultiple arguments are concatenated with spaces before being parsed.\n" }, { "code": null, "e": 13795, "s": 13733, "text": "\nTo print all packets arriving at or departing from sundown:\n" }, { "code": null, "e": 13817, "s": 13795, "text": "tcpdump host sundown\n" }, { "code": null, "e": 13874, "s": 13817, "text": "\nTo print traffic between helios and either hot or ace:\n" }, { "code": null, "e": 13916, "s": 13874, "text": "tcpdump host helios and \\( hot or ace \\)\n" }, { "code": null, "e": 13982, "s": 13916, "text": "\nTo print all IP packets between ace and any host except helios:\n" }, { "code": null, "e": 14018, "s": 13982, "text": "tcpdump ip host ace and not helios\n" }, { "code": null, "e": 14084, "s": 14018, "text": "\nTo print all traffic between local hosts and hosts at Berkeley:\n" }, { "code": null, "e": 14109, "s": 14084, "text": " \ntcpdump net ucb-ether\n" }, { "code": null, "e": 14266, "s": 14109, "text": "\nTo print all ftp traffic through internet gateway snup:\n(note that the expression is quoted to prevent the shell from\n(mis-)interpreting the parentheses):\n" }, { "code": null, "e": 14319, "s": 14266, "text": " \ntcpdump ’gateway snup and (port ftp or ftp-data)’\n" }, { "code": null, "e": 14476, "s": 14319, "text": "\nTo print traffic neither sourced from nor destined for local hosts\n(if you gateway to one other net, this stuff should never make it\nonto your local net).\n" }, { "code": null, "e": 14511, "s": 14476, "text": " \ntcpdump ip and not net localnet\n" }, { "code": null, "e": 14631, "s": 14511, "text": "\nTo print the start and end packets (the SYN and FIN packets) of each\nTCP conversation that involves a non-local host.\n" }, { "code": null, "e": 14716, "s": 14631, "text": " \ntcpdump ’tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net localnet’\n" }, { "code": null, "e": 14920, "s": 14716, "text": "\nTo print all IPv4 HTTP packets to and from port 80, i.e. print only\npackets that contain data, not, for example, SYN and FIN packets and\nACK-only packets. (IPv6 is left as an exercise for the reader.)\n" }, { "code": null, "e": 15009, "s": 14920, "text": " \ntcpdump ’tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)’\n" }, { "code": null, "e": 15080, "s": 15009, "text": "\nTo print IP packets longer than 576 bytes sent through gateway snup:\n" }, { "code": null, "e": 15124, "s": 15080, "text": " \ntcpdump ’gateway snup and ip[2:2] > 576’\n" }, { "code": null, "e": 15225, "s": 15124, "text": "\nTo print IP broadcast or multicast packets that were\nnot sent via Ethernet broadcast or multicast:\n" }, { "code": null, "e": 15273, "s": 15225, "text": " \ntcpdump ’ether[0] & 1 = 0 and ip[16] >= 224’\n" }, { "code": null, "e": 15362, "s": 15273, "text": "\nTo print all ICMP packets that are not echo requests/replies (i.e., not\nping packets):\n" }, { "code": null, "e": 15440, "s": 15362, "text": " \ntcpdump ’icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply’\n" }, { "code": null, "e": 15564, "s": 15440, "text": "\nThe output of tcpdump is protocol dependent.\nThe following\ngives a brief description and examples of most of the formats.\n" }, { "code": null, "e": 15586, "s": 15564, "text": "\n Link Level Headers\n" }, { "code": null, "e": 15748, "s": 15586, "text": "\nIf the ’-e’ option is given, the link level header is printed out.\nOn Ethernets, the source and destination addresses, protocol,\nand packet length are printed.\n" }, { "code": null, "e": 16280, "s": 15748, "text": "\nOn FDDI networks, the ’-e’ option causes tcpdump to print\nthe ‘frame control’ field, the source and destination addresses,\nand the packet length.\n(The ‘frame control’ field governs the\ninterpretation of the rest of the packet.\nNormal packets (such\nas those containing IP datagrams) are ‘async’ packets, with a priority\nvalue between 0 and 7; for example, ‘async4’.\nSuch packets\nare assumed to contain an 802.2 Logical Link Control (LLC) packet;\nthe LLC header is printed if it is not an ISO datagram or a\nso-called SNAP packet.\n" }, { "code": null, "e": 16651, "s": 16280, "text": "\nOn Token Ring networks, the ’-e’ option causes tcpdump to print\nthe ‘access control’ and ‘frame control’ fields, the source and\ndestination addresses, and the packet length.\nAs on FDDI networks,\npackets are assumed to contain an LLC packet.\nRegardless of whether\nthe ’-e’ option is specified or not, the source routing information is\nprinted for source-routed packets.\n" }, { "code": null, "e": 16874, "s": 16651, "text": "\nOn 802.11 networks, the ’-e’ option causes tcpdump to print\nthe ‘frame control’ fields, all of the addresses in the 802.11 header,\nand the packet length.\nAs on FDDI networks,\npackets are assumed to contain an LLC packet.\n" }, { "code": null, "e": 16989, "s": 16874, "text": "\n(N.B.: The following description assumes familiarity with\nthe SLIP compression algorithm described in RFC-1144.)\n" }, { "code": null, "e": 17846, "s": 16989, "text": "\nOn SLIP links, a direction indicator (‘‘I’’ for inbound, ‘‘O’’ for outbound),\npacket type, and compression information are printed out.\nThe packet type is printed first.\nThe three types are ip, utcp, and ctcp.\nNo further link information is printed for ip packets.\nFor TCP packets, the connection identifier is printed following the type.\nIf the packet is compressed, its encoded header is printed out.\nThe special cases are printed out as\n*S+n and *SA+n, where n is the amount by which\nthe sequence number (or sequence number and ack) has changed.\nIf it is not a special case,\nzero or more changes are printed.\nA change is indicated by U (urgent pointer), W (window), A (ack),\nS (sequence number), and I (packet ID), followed by a delta (+n or -n),\nor a new value (=n).\nFinally, the amount of data in the packet and compressed header length\nare printed.\n" }, { "code": null, "e": 18098, "s": 17846, "text": "\nFor example, the following line shows an outbound compressed TCP packet,\nwith an implicit connection identifier; the ack has changed by 6,\nthe sequence number by 49, and the packet ID by 6; there are 3 bytes of\ndata and 6 bytes of compressed header:\n" }, { "code": null, "e": 18127, "s": 18098, "text": "O ctcp * A+6 S+49 I+6 3 (6)\n" }, { "code": null, "e": 18147, "s": 18127, "text": "\n ARP/RARP Packets\n" }, { "code": null, "e": 18345, "s": 18147, "text": "\nArp/rarp output shows the type of request and its arguments.\nThe\nformat is intended to be self explanatory.\nHere is a short sample taken from the start of an ‘rlogin’ from\nhost rtsg to host csam:\n" }, { "code": null, "e": 18401, "s": 18345, "text": "\narp who-has csam tell rtsg\narp reply csam is-at CSAM\n\n" }, { "code": null, "e": 18456, "s": 18401, "text": "\narp who-has csam tell rtsg\narp reply csam is-at CSAM\n" }, { "code": null, "e": 18518, "s": 18458, "text": "\nThis would look less redundant if we had done tcpdump -n:\n" }, { "code": null, "e": 18608, "s": 18518, "text": "\narp who-has 128.3.254.6 tell 128.3.254.68\narp reply 128.3.254.6 is-at 02:07:01:00:01:c4\n" }, { "code": null, "e": 18698, "s": 18608, "text": "\narp who-has 128.3.254.6 tell 128.3.254.68\narp reply 128.3.254.6 is-at 02:07:01:00:01:c4\n" }, { "code": null, "e": 18822, "s": 18698, "text": "\nIf we had done tcpdump -e, the fact that the first packet is\nbroadcast and the second is point-to-point would be visible:\n" }, { "code": null, "e": 18923, "s": 18822, "text": "\nRTSG Broadcast 0806 64: arp who-has csam tell rtsg\nCSAM RTSG 0806 64: arp reply csam is-at CSAM\n\n" }, { "code": null, "e": 19023, "s": 18923, "text": "\nRTSG Broadcast 0806 64: arp who-has csam tell rtsg\nCSAM RTSG 0806 64: arp reply csam is-at CSAM\n" }, { "code": null, "e": 19040, "s": 19025, "text": "\n TCP Packets\n" }, { "code": null, "e": 19247, "s": 19040, "text": "\n(N.B.:The following description assumes familiarity with\nthe TCP protocol described in RFC-793.\nIf you are not familiar\nwith the protocol, neither this description nor tcpdump will\nbe of much use to you.)\n" }, { "code": null, "e": 19295, "s": 19247, "text": "\nThe general format of a tcp protocol line is:\n" }, { "code": null, "e": 19352, "s": 19295, "text": "\nsrc > dst: flags data-seqno ack window urgent options\n\n" }, { "code": null, "e": 19408, "s": 19352, "text": "\nsrc > dst: flags data-seqno ack window urgent options\n" }, { "code": null, "e": 19563, "s": 19410, "text": "\nSrc, dst and flags are always present.\nThe other fields\ndepend on the contents of the packet’s tcp protocol header and\nare output only if appropriate.\n" }, { "code": null, "e": 19635, "s": 19563, "text": "\nHere is the opening portion of an rlogin from host rtsg to\nhost csam.\n" }, { "code": null, "e": 20114, "s": 19635, "text": "\nrtsg.1023 > csam.login: S 768512:768512(0) win 4096 <mss 1024>\ncsam.login > rtsg.1023: S 947648:947648(0) ack 768513 win 4096 <mss 1024>\nrtsg.1023 > csam.login: . ack 1 win 4096\nrtsg.1023 > csam.login: P 1:2(1) ack 1 win 4096\ncsam.login > rtsg.1023: . ack 2 win 4096\nrtsg.1023 > csam.login: P 2:21(19) ack 1 win 4096\ncsam.login > rtsg.1023: P 1:2(1) ack 21 win 4077\ncsam.login > rtsg.1023: P 2:3(1) ack 21 win 4077 urg 1\ncsam.login > rtsg.1023: P 3:4(1) ack 21 win 4077 urg 1\n\n" }, { "code": null, "e": 20592, "s": 20114, "text": "\nrtsg.1023 > csam.login: S 768512:768512(0) win 4096 <mss 1024>\ncsam.login > rtsg.1023: S 947648:947648(0) ack 768513 win 4096 <mss 1024>\nrtsg.1023 > csam.login: . ack 1 win 4096\nrtsg.1023 > csam.login: P 1:2(1) ack 1 win 4096\ncsam.login > rtsg.1023: . ack 2 win 4096\nrtsg.1023 > csam.login: P 2:21(19) ack 1 win 4096\ncsam.login > rtsg.1023: P 1:2(1) ack 21 win 4077\ncsam.login > rtsg.1023: P 2:3(1) ack 21 win 4077 urg 1\ncsam.login > rtsg.1023: P 3:4(1) ack 21 win 4077 urg 1\n" }, { "code": null, "e": 21381, "s": 20594, "text": "\nCsam replies with a similar packet except it includes a piggy-backed\nack for rtsg’s SYN.\nRtsg then acks csam’s SYN.\nThe ‘.’ means no\nflags were set.\nThe packet contained no data so there is no data sequence number.\nNote that the ack sequence\nnumber is a small integer (1).\nThe first time tcpdump sees a\ntcp ‘conversation’, it prints the sequence number from the packet.\nOn subsequent packets of the conversation, the difference between\nthe current packet’s sequence number and this initial sequence number\nis printed.\nThis means that sequence numbers after the\nfirst can be interpreted\nas relative byte positions in the conversation’s data stream (with the\nfirst data byte each direction being ‘1’).\n‘-S’ will override this\nfeature, causing the original sequence numbers to be output.\n" }, { "code": null, "e": 21882, "s": 21381, "text": "\nOn the 6th line, rtsg sends csam 19 bytes of data (bytes 2 through 20\nin the rtsg -> csam side of the conversation).\nThe PUSH flag is set in the packet.\nOn the 7th line, csam says it’s received data sent by rtsg up to\nbut not including byte 21.\nMost of this data is apparently sitting in the\nsocket buffer since csam’s receive window has gotten 19 bytes smaller.\nCsam also sends one byte of data to rtsg in this packet.\nOn the 8th and 9th lines,\ncsam sends two bytes of urgent, pushed data to rtsg.\n" }, { "code": null, "e": 22515, "s": 21882, "text": "\nIf the snapshot was small enough that tcpdump didn’t capture\nthe full TCP header, it interprets as much of the header as it can\nand then reports ‘‘[|tcp]’’ to indicate the remainder could not\nbe interpreted.\nIf the header contains a bogus option (one with a length\nthat’s either too small or beyond the end of the header), tcpdump\nreports it as ‘‘[bad opt]’’ and does not interpret any further\noptions (since it’s impossible to tell where they start).\nIf the header\nlength indicates options are present but the IP datagram length is not\nlong enough for the options to actually be there, tcpdump reports\nit as ‘‘[bad hdr length]’’.\n" }, { "code": null, "e": 22599, "s": 22515, "text": "\n Capturing TCP packets with particular flag combinations (SYN-ACK, URG-ACK, etc.) " }, { "code": null, "e": 22665, "s": 22599, "text": "\nThere are 8 bits in the control bits section of the TCP header:\n" }, { "code": null, "e": 23459, "s": 22667, "text": " 0 15 31\n-----------------------------------------------------------------\n| source port | destination port |\n-----------------------------------------------------------------\n| sequence number |\n-----------------------------------------------------------------\n| acknowledgment number |\n-----------------------------------------------------------------\n| HL | rsvd |C|E|U|A|P|R|S|F| window size |\n-----------------------------------------------------------------\n| TCP checksum | urgent pointer |\n-----------------------------------------------------------------\n" }, { "code": null, "e": 23789, "s": 23459, "text": " 0 7| 15| 23| 31\n----------------|---------------|---------------|----------------\n| HL | rsvd |C|E|U|A|P|R|S|F| window size |\n----------------|---------------|---------------|----------------\n| | 13th octet | | |\n" }, { "code": null, "e": 23960, "s": 23789, "text": " | |\n |---------------|\n |C|E|U|A|P|R|S|F|\n |---------------|\n |7 5 3 0|\n" }, { "code": null, "e": 24131, "s": 23960, "text": " |C|E|U|A|P|R|S|F|\n |---------------|\n |0 0 0 0 0 0 1 0|\n |---------------|\n |7 6 5 4 3 2 1 0|\n" }, { "code": null, "e": 24231, "s": 24131, "text": " 7 6 5 4 3 2 1 0\n0*2 + 0*2 + 0*2 + 0*2 + 0*2 + 0*2 + 1*2 + 0*2 = 2\n" }, { "code": null, "e": 24347, "s": 24231, "text": " |C|E|U|A|P|R|S|F|\n |---------------|\n |0 0 0 1 0 0 1 0|\n |---------------|\n |7 6 5 4 3 2 1 0|\n" }, { "code": null, "e": 24448, "s": 24347, "text": " 7 6 5 4 3 2 1 0\n0*2 + 0*2 + 0*2 + 1*2 + 0*2 + 0*2 + 1*2 + 0*2 = 18\n" }, { "code": null, "e": 24664, "s": 24448, "text": "\n 00010010 SYN-ACK 00000010 SYN\n AND 00000010 (we want SYN) AND 00000010 (we want SYN)\n -------- --------\n = 00000010 = 00000010\n" }, { "code": null, "e": 24880, "s": 24664, "text": "\n 00010010 SYN-ACK 00000010 SYN\n AND 00000010 (we want SYN) AND 00000010 (we want SYN)\n -------- --------\n = 00000010 = 00000010\n" }, { "code": null, "e": 24896, "s": 24880, "text": "\n UDP Packets\n" }, { "code": null, "e": 24936, "s": 24896, "text": "\nactinide.who > broadcast.who: udp 84\n\n" }, { "code": null, "e": 24975, "s": 24936, "text": "\nactinide.who > broadcast.who: udp 84\n" }, { "code": null, "e": 25005, "s": 24977, "text": "\n UDP Name Server Requests\n" }, { "code": null, "e": 25119, "s": 25005, "text": "\nsrc > dst: id op? flags qtype qclass name (len)\n\nh2opolo.1538 > helios.domain: 3+ A? ucbvax.berkeley.edu. (37)\n\n" }, { "code": null, "e": 25169, "s": 25119, "text": "\nsrc > dst: id op? flags qtype qclass name (len)\n" }, { "code": null, "e": 25233, "s": 25169, "text": "\nh2opolo.1538 > helios.domain: 3+ A? ucbvax.berkeley.edu. (37)\n" }, { "code": null, "e": 25264, "s": 25235, "text": "\n UDP Name Server Responses\n" }, { "code": null, "e": 25439, "s": 25264, "text": "\nsrc > dst: id op rcode flags a/n/au type class data (len)\n\nhelios.domain > h2opolo.1538: 3 3/3/7 A 128.32.137.3 (273)\nhelios.domain > h2opolo.1537: 2 NXDomain* 0/1/0 (97)\n\n" }, { "code": null, "e": 25500, "s": 25439, "text": "\nsrc > dst: id op rcode flags a/n/au type class data (len)\n" }, { "code": null, "e": 25614, "s": 25500, "text": "\nhelios.domain > h2opolo.1538: 3 3/3/7 A 128.32.137.3 (273)\nhelios.domain > h2opolo.1537: 2 NXDomain* 0/1/0 (97)\n" }, { "code": null, "e": 25639, "s": 25618, "text": "\n SMB/CIFS decoding\n" }, { "code": null, "e": 25865, "s": 25639, "text": "\nBy default a fairly minimal decode is done, with a much more detailed\ndecode done if -v is used.\nBe warned that with -v a single SMB packet\nmay take up a page or more, so only use -v if you really want all the\ngory details.\n" }, { "code": null, "e": 26092, "s": 25865, "text": "\nFor information on SMB packet formats and what all te fields mean see\nwww.cifs.org or the pub/samba/specs/ directory on your favorite\nsamba.org mirror site.\nThe SMB patches were written by Andrew Tridgell\n([email protected]).\n" }, { "code": null, "e": 26122, "s": 26094, "text": "\n NFS Requests and Replies\n" }, { "code": null, "e": 26446, "s": 26122, "text": "\nsrc.xid > dst.nfs: len op args\nsrc.nfs > dst.xid: reply stat len op results\n\n\nsushi.6709 > wrl.nfs: 112 readlink fh 21,24/10.73165\nwrl.nfs > sushi.6709: reply ok 40 readlink \"../var\"\nsushi.201b > wrl.nfs:\n 144 lookup fh 9,74/4096.6878 \"xcolors\"\nwrl.nfs > sushi.201b:\n reply ok 128 lookup fh 9,74/4134.3150\n\n\n" }, { "code": null, "e": 26524, "s": 26446, "text": "\nsrc.xid > dst.nfs: len op args\nsrc.nfs > dst.xid: reply stat len op results\n" }, { "code": null, "e": 26770, "s": 26524, "text": "\n\nsushi.6709 > wrl.nfs: 112 readlink fh 21,24/10.73165\nwrl.nfs > sushi.6709: reply ok 40 readlink \"../var\"\nsushi.201b > wrl.nfs:\n 144 lookup fh 9,74/4096.6878 \"xcolors\"\nwrl.nfs > sushi.201b:\n reply ok 128 lookup fh 9,74/4134.3150\n\n" }, { "code": null, "e": 26932, "s": 26772, "text": "\n\nsushi.1372a > wrl.nfs:\n 148 read fh 21,11/12.195 8192 bytes @ 24576\nwrl.nfs > sushi.1372a:\n reply ok 1472 read REG 100664 ids 417/0 sz 29388\n\n\n" }, { "code": null, "e": 27091, "s": 26932, "text": "\n\nsushi.1372a > wrl.nfs:\n 148 read fh 21,11/12.195 8192 bytes @ 24576\nwrl.nfs > sushi.1372a:\n reply ok 1472 read REG 100664 ids 417/0 sz 29388\n\n" }, { "code": null, "e": 27121, "s": 27093, "text": "\n AFS Requests and Replies\n" }, { "code": null, "e": 27482, "s": 27124, "text": "\nsrc.sport > dst.dport: rx packet-type\nsrc.sport > dst.dport: rx packet-type service call call-name args\nsrc.sport > dst.dport: rx packet-type service reply call-name args\n\n\nelvis.7001 > pike.afsfs:\n rx data fs call rename old fid 536876964/1/1 \".newsrc.new\"\n new fid 536876964/1/1 \".newsrc\"\npike.afsfs > elvis.7001: rx data fs reply rename\n\n\n" }, { "code": null, "e": 27655, "s": 27482, "text": "\nsrc.sport > dst.dport: rx packet-type\nsrc.sport > dst.dport: rx packet-type service call call-name args\nsrc.sport > dst.dport: rx packet-type service reply call-name args\n" }, { "code": null, "e": 27840, "s": 27655, "text": "\n\nelvis.7001 > pike.afsfs:\n rx data fs call rename old fid 536876964/1/1 \".newsrc.new\"\n new fid 536876964/1/1 \".newsrc\"\npike.afsfs > elvis.7001: rx data fs reply rename\n\n" }, { "code": null, "e": 27874, "s": 27844, "text": "\n KIP AppleTalk (DDP in UDP)\n" }, { "code": null, "e": 27958, "s": 27874, "text": "\nnumber name\n\n1.254 ether\n16.1 icsd-net\n1.254.110 ace\n\n" }, { "code": null, "e": 27973, "s": 27958, "text": "\nnumber name\n" }, { "code": null, "e": 28042, "s": 27973, "text": "\n1.254 ether\n16.1 icsd-net\n1.254.110 ace\n" }, { "code": null, "e": 28149, "s": 28044, "text": "\nnet.host.port\n\n144.1.209.2 > icsd-net.112.220\noffice.2 > icsd-net.112.220\njssmag.149.235 > icsd-net.2\n\n" }, { "code": null, "e": 28165, "s": 28149, "text": "\nnet.host.port\n" }, { "code": null, "e": 28254, "s": 28165, "text": "\n144.1.209.2 > icsd-net.112.220\noffice.2 > icsd-net.112.220\njssmag.149.235 > icsd-net.2\n" }, { "code": null, "e": 28313, "s": 28256, "text": "\nNBP packets are formatted like the following examples:\n" }, { "code": null, "e": 28525, "s": 28313, "text": "\nicsd-net.112.220 > jssmag.2: nbp-lkup 190: \"=:LaserWriter@*\"\njssmag.209.2 > icsd-net.112.220: nbp-reply 190: \"RM1140:LaserWriter@*\" 250\ntechpit.2 > icsd-net.112.220: nbp-reply 190: \"techpit:LaserWriter@*\" 186\n\n" }, { "code": null, "e": 28736, "s": 28525, "text": "\nicsd-net.112.220 > jssmag.2: nbp-lkup 190: \"=:LaserWriter@*\"\njssmag.209.2 > icsd-net.112.220: nbp-reply 190: \"RM1140:LaserWriter@*\" 250\ntechpit.2 > icsd-net.112.220: nbp-reply 190: \"techpit:LaserWriter@*\" 186\n" }, { "code": null, "e": 28804, "s": 28738, "text": "\nATP packet formatting is demonstrated by the following example:\n" }, { "code": null, "e": 29677, "s": 28804, "text": "\njssmag.209.165 > helios.132: atp-req 12266<0-7> 0xae030001\nhelios.132 > jssmag.209.165: atp-resp 12266:0 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:1 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:2 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:4 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:6 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp*12266:7 (512) 0xae040000\njssmag.209.165 > helios.132: atp-req 12266<3,5> 0xae030001\nhelios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000\njssmag.209.165 > helios.132: atp-rel 12266<0-7> 0xae030001\njssmag.209.133 > helios.132: atp-req* 12267<0-7> 0xae030002\n\n" }, { "code": null, "e": 30549, "s": 29677, "text": "\njssmag.209.165 > helios.132: atp-req 12266<0-7> 0xae030001\nhelios.132 > jssmag.209.165: atp-resp 12266:0 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:1 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:2 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:4 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:6 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp*12266:7 (512) 0xae040000\njssmag.209.165 > helios.132: atp-req 12266<3,5> 0xae030001\nhelios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000\nhelios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000\njssmag.209.165 > helios.132: atp-rel 12266<0-7> 0xae030001\njssmag.209.133 > helios.132: atp-req* 12267<0-7> 0xae030002\n" }, { "code": null, "e": 30573, "s": 30553, "text": "\n IP Fragmentation\n" }, { "code": null, "e": 30621, "s": 30573, "text": "\n(frag id:size@offset+)\n(frag id:size@offset)\n\n" }, { "code": null, "e": 30668, "s": 30621, "text": "\n(frag id:size@offset+)\n(frag id:size@offset)\n" }, { "code": null, "e": 30840, "s": 30670, "text": "\narizona.ftp-data > rtsg.1170: . 1024:1332(308) ack 1 win 4096 (frag 595a:328@0+)\narizona > rtsg: (frag 595a:204@328)\nrtsg.1170 > arizona.ftp-data: . ack 1536 win 2560\n\n" }, { "code": null, "e": 31009, "s": 30840, "text": "\narizona.ftp-data > rtsg.1170: . 1024:1332(308) ack 1 win 4096 (frag 595a:328@0+)\narizona > rtsg: (frag 595a:204@328)\nrtsg.1170 > arizona.ftp-data: . ack 1536 win 2560\n" }, { "code": null, "e": 31025, "s": 31011, "text": "\n Timestamps\n" }, { "code": null, "e": 31040, "s": 31025, "text": "hh:mm:ss.frac\n" }, { "code": null, "e": 31178, "s": 31040, "text": "\nVan Jacobson,\nCraig Leres and\nSteven McCanne, all of the\nLawrence Berkeley National Laboratory, University of California, Berkeley, CA.\n" }, { "code": null, "e": 31229, "s": 31178, "text": "\nIt is currently being maintained by tcpdump.org.\n" }, { "code": null, "e": 31274, "s": 31229, "text": "\nThe current version is available via http:\n" }, { "code": null, "e": 31300, "s": 31274, "text": "\nhttp://www.tcpdump.org/ " }, { "code": null, "e": 31360, "s": 31300, "text": "\nThe original distribution is available via anonymous ftp:\n" }, { "code": null, "e": 31397, "s": 31360, "text": "\nftp://ftp.ee.lbl.gov/tcpdump.tar.Z " }, { "code": null, "e": 31526, "s": 31397, "text": "\nIPv6/IPsec support is added by WIDE/KAME project.\nThis program uses Eric Young’s SSLeay library, under specific configuration.\n" }, { "code": null, "e": 31556, "s": 31526, "text": "\[email protected]\n" }, { "code": null, "e": 31606, "s": 31556, "text": "\nPlease send source code contributions, etc. to:\n" }, { "code": null, "e": 31628, "s": 31606, "text": "\[email protected]\n" }, { "code": null, "e": 31731, "s": 31628, "text": "\nNIT doesn’t let you watch your own outbound traffic, BPF will.\nWe recommend that you use the latter.\n" }, { "code": null, "e": 31772, "s": 31731, "text": "\nOn Linux systems with 2.0[.x] kernels:\n" }, { "code": null, "e": 31901, "s": 31772, "text": "\nSome attempt should be made to reassemble IP fragments or, at least\nto compute the right length for the higher level protocol.\n" }, { "code": null, "e": 32165, "s": 31901, "text": "\nName server inverse queries are not dumped correctly: the (empty)\nquestion section is printed rather than real query in the answer\nsection.\nSome believe that inverse queries are themselves a bug and\nprefer to fix the program generating them rather than tcpdump.\n" }, { "code": null, "e": 32285, "s": 32165, "text": "\nA packet trace that crosses a daylight savings time change will give\nskewed time stamps (the time change is ignored).\n" }, { "code": null, "e": 32415, "s": 32285, "text": "\nFilter expressions on fields other than those in Token Ring headers will\nnot correctly handle source-routed Token Ring packets.\n" }, { "code": null, "e": 32560, "s": 32415, "text": "\nFilter expressions on fields other than those in 802.11 headers will not\ncorrectly handle 802.11 data packets with both To DS and From DS set.\n" }, { "code": null, "e": 32677, "s": 32560, "text": "\nip6 proto should chase header chain, but at this moment it does not.\nip6 protochain is supplied for this behavior.\n" }, { "code": null, "e": 32823, "s": 32677, "text": "\nArithmetic expression against transport layer headers, like tcp[0],\ndoes not work against IPv6 packets.\nIt only looks at IPv4 packets.\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 32840, "s": 32823, "text": "\nAdvertisements\n" }, { "code": null, "e": 32875, "s": 32840, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 32903, "s": 32875, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 32937, "s": 32903, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 32954, "s": 32937, "text": " Frahaan Hussain" }, { "code": null, "e": 32987, "s": 32954, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 32998, "s": 32987, "text": " Pradeep D" }, { "code": null, "e": 33033, "s": 32998, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 33049, "s": 33033, "text": " Musab Zayadneh" }, { "code": null, "e": 33082, "s": 33049, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 33094, "s": 33082, "text": " GUHARAJANM" }, { "code": null, "e": 33126, "s": 33094, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 33134, "s": 33126, "text": " Uplatz" }, { "code": null, "e": 33141, "s": 33134, "text": " Print" }, { "code": null, "e": 33152, "s": 33141, "text": " Add Notes" } ]
How to check whether a vector contains an NA value or not in R?
An NA value in R represents “Not Available” that means missing value. If a vector has even one NA value then the calculations for that vector becomes a little difficult because we will either have to remove that NA, replace it or neglect it during the calculations. To do any of these things, we will have to make some changes in our codes therefore, it is better to check whether a vector contain an NA or not before doing anything. This can be done with the help of any function in conjunction with is.na. > x1<-c(1,2,3,2) > x1 [1] 1 2 3 2 > any(is.na(x1)) [1] FALSE > x2<-c(1,2,3,2,NA) > x2 [1] 1 2 3 2 NA > any(is.na(x2)) [1] TRUE > x3<-c(4,5,6,"",2,8,7) > x3 [1] "4" "5" "6" "" "2" "8" "7" > any(is.na(x3)) [1] FALSE > x4<-c(4,5,6,"NA",2,8,7) > x4 [1] "4" "5" "6" "NA" "2" "8" "7" > any(is.na(x4)) [1] FALSE > x5<-c(4,5,6,4,2,8,7,NA,4,5,NA,NA) > x5 [1] 4 5 6 4 2 8 7 NA 4 5 NA NA > any(is.na(x5)) [1] TRUE > x6<-rep(c(15,NA,10),times=10) > x6 [1] 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 [26] NA 10 15 NA 10 > any(is.na(x6)) [1] TRUE > x7<-rep(c(15,"NA",10),times=10) > x7 [1] "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" [16] "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" > any(is.na(x7)) [1] FALSE > x8<-1:1000000 > any(is.na(x8)) [1] FALSE > x9<-rep(c(1,2,3,4,5,6,7,8,9,10),times=500000) > any(is.na(x9)) [1] FALSE > x10<-rep(c(1,2,3,4,5,6,7,8,9,10),times=5000000) > any(is.na(x10)) [1] FALSE The vectors having small size will take less time to get the answer on the other hand the vectors having a very large size will take slightly more time to let us know whether we have an NA in our vector or not.
[ { "code": null, "e": 1570, "s": 1062, "text": "An NA value in R represents “Not Available” that means missing value. If a vector has even one NA value then the calculations for that vector becomes a little difficult because we will either have to remove that NA, replace it or neglect it during the calculations. To do any of these things, we will have to make some changes in our codes therefore, it is better to check whether a vector contain an NA or not before doing anything. This can be done with the help of any function in conjunction with is.na." }, { "code": null, "e": 2558, "s": 1570, "text": "> x1<-c(1,2,3,2)\n> x1\n[1] 1 2 3 2\n> any(is.na(x1))\n[1] FALSE\n> x2<-c(1,2,3,2,NA)\n> x2\n[1] 1 2 3 2 NA\n> any(is.na(x2))\n[1] TRUE\n> x3<-c(4,5,6,\"\",2,8,7)\n> x3\n[1] \"4\" \"5\" \"6\" \"\" \"2\" \"8\" \"7\"\n> any(is.na(x3))\n[1] FALSE\n> x4<-c(4,5,6,\"NA\",2,8,7)\n> x4\n[1] \"4\" \"5\" \"6\" \"NA\" \"2\" \"8\" \"7\"\n> any(is.na(x4))\n[1] FALSE\n> x5<-c(4,5,6,4,2,8,7,NA,4,5,NA,NA)\n> x5\n[1] 4 5 6 4 2 8 7 NA 4 5 NA NA\n> any(is.na(x5))\n[1] TRUE\n> x6<-rep(c(15,NA,10),times=10)\n> x6\n [1] 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15\n[26] NA 10 15 NA 10\n> any(is.na(x6))\n[1] TRUE\n> x7<-rep(c(15,\"NA\",10),times=10)\n> x7\n [1] \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\"\n[16] \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\" \"15\" \"NA\" \"10\"\n> any(is.na(x7))\n[1] FALSE\n> x8<-1:1000000\n> any(is.na(x8))\n[1] FALSE\n> x9<-rep(c(1,2,3,4,5,6,7,8,9,10),times=500000)\n> any(is.na(x9))\n[1] FALSE\n> x10<-rep(c(1,2,3,4,5,6,7,8,9,10),times=5000000)\n> any(is.na(x10))\n[1] FALSE" }, { "code": null, "e": 2769, "s": 2558, "text": "The vectors having small size will take less time to get the answer on the other hand the vectors having a very large size will take slightly more time to let us know whether we have an NA in our vector or not." } ]
Sum of lengths of all 12 edges of any rectangular parallelepiped - GeeksforGeeks
28 May, 2021 Given the area of three faces of the rectangular parallelepiped which has a common vertex. Our task is to find the sum of lengths of all 12 edges of this parallelepiped.In geometry, a parallelepiped is a three-dimensional figure formed by six parallelograms. By analogy, it relates to a parallelogram just as a cube relates to a square or as a cuboid to a rectangle. A picture of a rectangular parallelepiped is shown below. Examples: Input: 1 1 1 Output: 12 Input: 20 10 50 Output: 68 Approach: The area given are s1, s2 and s3 . Let a, b and c be the lengths of the sides that have one common vertex. Where , , . It’s easy to find the length in terms of faces areas: , , . The answer will be the summation of all the 4 sides, there are four sides that have lengths equal to a, b and c.In the first example the given area s1 = 1, s2 = 1 and s3 = 1. So with the above approach, the value of a, b, c will come out to be 1. So the sum of the length of all 12 edges will be 4 * 3 = 12.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to illustrate// the above problem#include <bits/stdc++.h>using namespace std; // function to find the sum of// all the edges of parallelepipeddouble findEdges(double s1, double s2, double s3){ // to calculate the length of one edge double a = sqrt(s1 * s2 / s3); double b = sqrt(s3 * s1 / s2); double c = sqrt(s3 * s2 / s1); // sum of all the edges of one side double sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum;} // Driver codeint main(){ // initialize the area of three // faces which has a common vertex double s1, s2, s3; s1 = 65, s2 = 156, s3 = 60; cout << findEdges(s1, s2, s3); return 0;} // Java program to illustrate// the above problem import java.io.*; class GFG { // function to find the sum of// all the edges of parallelepipedstatic double findEdges(double s1, double s2, double s3){ // to calculate the length of one edge double a = Math.sqrt(s1 * s2 / s3); double b = Math.sqrt(s3 * s1 / s2); double c = Math.sqrt(s3 * s2 / s1); // sum of all the edges of one side double sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum;} // Driver code public static void main (String[] args) { // initialize the area of three // faces which has a common vertex double s1, s2, s3; s1 = 65; s2 = 156; s3 = 60; System.out.print(findEdges(s1, s2, s3)); }} // this code is contributed by anuj_67.. import math # Python3 program to illustrate# the above problem # function to find the sum of# all the edges of parallelepipeddef findEdges(s1, s2, s3): # to calculate the length of one edge a = math.sqrt(s1 * s2 / s3) b = math.sqrt(s3 * s1 / s2) c = math.sqrt(s3 * s2 / s1) # sum of all the edges of one side sum = a + b + c # net sum will be equal to the # summation of edges of all the sides return 4 * sum # Driver codeif __name__=='__main__': # initialize the area of three# faces which has a common vertex s1 = 65 s2 = 156 s3 = 60 print(int(findEdges(s1, s2, s3))) # This code is contributed by# Shivi_Aggarwal // C# program to illustrate// the above problemusing System; public class GFG{ // function to find the sum of// all the edges of parallelepipedstatic double findEdges(double s1, double s2, double s3){ // to calculate the length of one edge double a = Math.Sqrt(s1 * s2 / s3); double b = Math.Sqrt(s3 * s1 / s2); double c = Math.Sqrt(s3 * s2 / s1); // sum of all the edges of one side double sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum;} // Driver code static public void Main (){ // initialize the area of three // faces which has a common vertex double s1, s2, s3; s1 = 65; s2 = 156; s3 = 60; Console.WriteLine(findEdges(s1, s2, s3)); }} // This code is contributed by anuj_67.. <?php// PHP program to illustrate// the above problem // function to find the sum of// all the edges of parallelepipedfunction findEdges($s1, $s2, $s3){ // to calculate the length of one edge $a = sqrt($s1 * $s2 / $s3); $b = sqrt($s3 * $s1 / $s2); $c = sqrt($s3 * $s2 / $s1); // sum of all the edges of one side $sum = $a + $b + $c; // net sum will be equal to the // summation of edges of all the sides return 4 * $sum;} // Driver code // initialize the area of three// faces which has a common vertex$s1; $s2; $s3;$s1 = 65; $s2 = 156; $s3 = 60; echo findEdges($s1, $s2, $s3); // This code is contributed by Shashank?> <script> // Javascript program to illustrate the above problem // function to find the sum of // all the edges of parallelepiped function findEdges(s1, s2, s3) { // to calculate the length of one edge let a = Math.sqrt(s1 * s2 / s3); let b = Math.sqrt(s3 * s1 / s2); let c = Math.sqrt(s3 * s2 / s1); // sum of all the edges of one side let sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum; } // initialize the area of three // faces which has a common vertex let s1, s2, s3; s1 = 65; s2 = 156; s3 = 60; document.write(findEdges(s1, s2, s3)); </script> 120 Reference: https://en.wikipedia.org/wiki/Parallelepiped vt_m Shashank12 Shivi_Aggarwal nidhi_biet decode2207 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26585, "s": 26557, "text": "\n28 May, 2021" }, { "code": null, "e": 27011, "s": 26585, "text": "Given the area of three faces of the rectangular parallelepiped which has a common vertex. Our task is to find the sum of lengths of all 12 edges of this parallelepiped.In geometry, a parallelepiped is a three-dimensional figure formed by six parallelograms. By analogy, it relates to a parallelogram just as a cube relates to a square or as a cuboid to a rectangle. A picture of a rectangular parallelepiped is shown below. " }, { "code": null, "e": 27023, "s": 27011, "text": "Examples: " }, { "code": null, "e": 27076, "s": 27023, "text": "Input: 1 1 1 \nOutput: 12\n\nInput: 20 10 50\nOutput: 68" }, { "code": null, "e": 27627, "s": 27078, "text": "Approach: The area given are s1, s2 and s3 . Let a, b and c be the lengths of the sides that have one common vertex. Where , , . It’s easy to find the length in terms of faces areas: , , . The answer will be the summation of all the 4 sides, there are four sides that have lengths equal to a, b and c.In the first example the given area s1 = 1, s2 = 1 and s3 = 1. So with the above approach, the value of a, b, c will come out to be 1. So the sum of the length of all 12 edges will be 4 * 3 = 12.Below is the implementation of the above approach: " }, { "code": null, "e": 27631, "s": 27627, "text": "C++" }, { "code": null, "e": 27636, "s": 27631, "text": "Java" }, { "code": null, "e": 27644, "s": 27636, "text": "Python3" }, { "code": null, "e": 27647, "s": 27644, "text": "C#" }, { "code": null, "e": 27651, "s": 27647, "text": "PHP" }, { "code": null, "e": 27662, "s": 27651, "text": "Javascript" }, { "code": "// C++ program to illustrate// the above problem#include <bits/stdc++.h>using namespace std; // function to find the sum of// all the edges of parallelepipeddouble findEdges(double s1, double s2, double s3){ // to calculate the length of one edge double a = sqrt(s1 * s2 / s3); double b = sqrt(s3 * s1 / s2); double c = sqrt(s3 * s2 / s1); // sum of all the edges of one side double sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum;} // Driver codeint main(){ // initialize the area of three // faces which has a common vertex double s1, s2, s3; s1 = 65, s2 = 156, s3 = 60; cout << findEdges(s1, s2, s3); return 0;}", "e": 28381, "s": 27662, "text": null }, { "code": "// Java program to illustrate// the above problem import java.io.*; class GFG { // function to find the sum of// all the edges of parallelepipedstatic double findEdges(double s1, double s2, double s3){ // to calculate the length of one edge double a = Math.sqrt(s1 * s2 / s3); double b = Math.sqrt(s3 * s1 / s2); double c = Math.sqrt(s3 * s2 / s1); // sum of all the edges of one side double sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum;} // Driver code public static void main (String[] args) { // initialize the area of three // faces which has a common vertex double s1, s2, s3; s1 = 65; s2 = 156; s3 = 60; System.out.print(findEdges(s1, s2, s3)); }} // this code is contributed by anuj_67..", "e": 29204, "s": 28381, "text": null }, { "code": "import math # Python3 program to illustrate# the above problem # function to find the sum of# all the edges of parallelepipeddef findEdges(s1, s2, s3): # to calculate the length of one edge a = math.sqrt(s1 * s2 / s3) b = math.sqrt(s3 * s1 / s2) c = math.sqrt(s3 * s2 / s1) # sum of all the edges of one side sum = a + b + c # net sum will be equal to the # summation of edges of all the sides return 4 * sum # Driver codeif __name__=='__main__': # initialize the area of three# faces which has a common vertex s1 = 65 s2 = 156 s3 = 60 print(int(findEdges(s1, s2, s3))) # This code is contributed by# Shivi_Aggarwal", "e": 29876, "s": 29204, "text": null }, { "code": "// C# program to illustrate// the above problemusing System; public class GFG{ // function to find the sum of// all the edges of parallelepipedstatic double findEdges(double s1, double s2, double s3){ // to calculate the length of one edge double a = Math.Sqrt(s1 * s2 / s3); double b = Math.Sqrt(s3 * s1 / s2); double c = Math.Sqrt(s3 * s2 / s1); // sum of all the edges of one side double sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum;} // Driver code static public void Main (){ // initialize the area of three // faces which has a common vertex double s1, s2, s3; s1 = 65; s2 = 156; s3 = 60; Console.WriteLine(findEdges(s1, s2, s3)); }} // This code is contributed by anuj_67..", "e": 30672, "s": 29876, "text": null }, { "code": "<?php// PHP program to illustrate// the above problem // function to find the sum of// all the edges of parallelepipedfunction findEdges($s1, $s2, $s3){ // to calculate the length of one edge $a = sqrt($s1 * $s2 / $s3); $b = sqrt($s3 * $s1 / $s2); $c = sqrt($s3 * $s2 / $s1); // sum of all the edges of one side $sum = $a + $b + $c; // net sum will be equal to the // summation of edges of all the sides return 4 * $sum;} // Driver code // initialize the area of three// faces which has a common vertex$s1; $s2; $s3;$s1 = 65; $s2 = 156; $s3 = 60; echo findEdges($s1, $s2, $s3); // This code is contributed by Shashank?>", "e": 31321, "s": 30672, "text": null }, { "code": "<script> // Javascript program to illustrate the above problem // function to find the sum of // all the edges of parallelepiped function findEdges(s1, s2, s3) { // to calculate the length of one edge let a = Math.sqrt(s1 * s2 / s3); let b = Math.sqrt(s3 * s1 / s2); let c = Math.sqrt(s3 * s2 / s1); // sum of all the edges of one side let sum = a + b + c; // net sum will be equal to the // summation of edges of all the sides return 4 * sum; } // initialize the area of three // faces which has a common vertex let s1, s2, s3; s1 = 65; s2 = 156; s3 = 60; document.write(findEdges(s1, s2, s3)); </script>", "e": 32038, "s": 31321, "text": null }, { "code": null, "e": 32042, "s": 32038, "text": "120" }, { "code": null, "e": 32101, "s": 32044, "text": "Reference: https://en.wikipedia.org/wiki/Parallelepiped " }, { "code": null, "e": 32106, "s": 32101, "text": "vt_m" }, { "code": null, "e": 32117, "s": 32106, "text": "Shashank12" }, { "code": null, "e": 32132, "s": 32117, "text": "Shivi_Aggarwal" }, { "code": null, "e": 32143, "s": 32132, "text": "nidhi_biet" }, { "code": null, "e": 32154, "s": 32143, "text": "decode2207" }, { "code": null, "e": 32164, "s": 32154, "text": "Geometric" }, { "code": null, "e": 32177, "s": 32164, "text": "Mathematical" }, { "code": null, "e": 32190, "s": 32177, "text": "Mathematical" }, { "code": null, "e": 32200, "s": 32190, "text": "Geometric" }, { "code": null, "e": 32298, "s": 32200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32364, "s": 32298, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 32396, "s": 32364, "text": "Program to find slope of a line" }, { "code": null, "e": 32457, "s": 32396, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 32503, "s": 32457, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 32573, "s": 32503, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 32603, "s": 32573, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32663, "s": 32603, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32678, "s": 32663, "text": "C++ Data Types" }, { "code": null, "e": 32721, "s": 32678, "text": "Set in C++ Standard Template Library (STL)" } ]
Python String - GeeksforGeeks
14 May, 2022 In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Strings in Python can be created using single quotes or double quotes or even triple quotes. Python3 # Python Program for# Creation of String # Creating a String# with single QuotesString1 = 'Welcome to the Geeks World'print("String with the use of Single Quotes: ")print(String1) # Creating a String# with double QuotesString1 = "I'm a Geek"print("\nString with the use of Double Quotes: ")print(String1) # Creating a String# with triple QuotesString1 = '''I'm a Geek and I live in a world of "Geeks"'''print("\nString with the use of Triple Quotes: ")print(String1) # Creating String with triple# Quotes allows multiple linesString1 = '''Geeks For Life'''print("\nCreating a multiline String: ")print(String1) Output: String with the use of Single Quotes: Welcome to the Geeks World String with the use of Double Quotes: I'm a Geek String with the use of Triple Quotes: I'm a Geek and I live in a world of "Geeks" Creating a multiline String: Geeks For Life In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError. Python3 # Python Program to Access# characters of String String1 = "GeeksForGeeks"print("Initial String: ")print(String1) # Printing First characterprint("\nFirst character of String is: ")print(String1[0]) # Printing Last characterprint("\nLast character of String is: ")print(String1[-1]) Output: Initial String: GeeksForGeeks First character of String is: G Last character of String is: s To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by using a Slicing operator (colon). Python3 # Python Program to# demonstrate String slicing # Creating a StringString1 = "GeeksForGeeks"print("Initial String: ") print(String1) # Printing 3rd to 12th characterprint("\nSlicing characters from 3-12: ")print(String1[3:12]) # Printing characters between # 3rd and 2nd last characterprint("\nSlicing characters between " + "3rd and 2nd last character: ")print(String1[3:-2]) Output: Initial String: GeeksForGeeks Slicing characters from 3-12: ksForGeek Slicing characters between 3rd and 2nd last character: ksForGee In Python, Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of the entire String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name. Python3 # Python Program to Update# character of a String String1 = "Hello, I'm a Geek"print("Initial String: ")print(String1) # Updating a character# of the StringString1[2] = 'p'print("\nUpdating character at 2nd Index: ")print(String1) Error: Traceback (most recent call last): File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in String1[2] = ‘p’ TypeError: ‘str’ object does not support item assignment Python3 # Python Program to Update# entire String String1 = "Hello, I'm a Geek"print("Initial String: ")print(String1) # Updating a StringString1 = "Welcome to the Geek World"print("\nUpdated String: ")print(String1) Output: Initial String: Hello, I'm a Geek Updated String: Welcome to the Geek World Python3 # Python Program to Delete# characters from a String String1 = "Hello, I'm a Geek"print("Initial String: ")print(String1) # Deleting a character# of the Stringdel String1[2]print("\nDeleting character at 2nd Index: ")print(String1) Error: Traceback (most recent call last): File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 10, in del String1[2] TypeError: ‘str’ object doesn’t support item deletion Deletion of the entire string is possible with the use of del keyword. Further, if we try to print the string, this will produce an error because String is deleted and is unavailable to be printed. Python3 # Python Program to Delete# entire String String1 = "Hello, I'm a Geek"print("Initial String: ")print(String1) # Deleting a String# with the use of deldel String1print("\nDeleting entire String: ")print(String1) Error: Traceback (most recent call last): File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in print(String1) NameError: name ‘String1’ is not defined While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print such Strings. Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and same is done for Double Quotes. Python3 # Python Program for# Escape Sequencing# of String # Initial StringString1 = '''I'm a "Geek"'''print("Initial String with use of Triple Quotes: ")print(String1) # Escaping Single QuoteString1 = 'I\'m a "Geek"'print("\nEscaping Single Quote: ")print(String1) # Escaping Double QuotesString1 = "I'm a \"Geek\""print("\nEscaping Double Quotes: ")print(String1) # Printing Paths with the# use of Escape SequencesString1 = "C:\\Python\\Geeks\\"print("\nEscaping Backslashes: ")print(String1) Output: Initial String with use of Triple Quotes: I'm a "Geek" Escaping Single Quote: I'm a "Geek" Escaping Double Quotes: I'm a "Geek" Escaping Backslashes: C:\Python\Geeks\ To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw string and escape sequences inside it are to be ignored. Python3 # Printing Geeks in HEXString1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"print("\nPrinting in HEX with the use of Escape Sequences: ")print(String1) # Using raw String to# ignore Escape SequencesString1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"print("\nPrinting Raw String in HEX Format: ")print(String1) Output: Printing in HEX with the use of Escape Sequences: This is Geeks in HEX Printing Raw String in HEX Format: This is \x47\x65\x65\x6b\x73 in \x48\x45\x58 Strings in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order. Python3 # Python Program for# Formatting of Strings # Default orderString1 = "{} {} {}".format('Geeks', 'For', 'Life')print("Print String in default order: ")print(String1) # Positional FormattingString1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')print("\nPrint String in Positional order: ")print(String1) # Keyword FormattingString1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')print("\nPrint String in order of Keywords: ")print(String1) Output: Print String in default order: Geeks For Life Print String in Positional order: For Geeks Life Print String in order of Keywords: Life For Geeks Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in the exponent form with the use of format specifiers. Python3 # Formatting of IntegersString1 = "{0:b}".format(16)print("\nBinary representation of 16 is ")print(String1) # Formatting of FloatsString1 = "{0:e}".format(165.6458)print("\nExponent representation of 165.6458 is ")print(String1) # Rounding off IntegersString1 = "{0:.2f}".format(1/6)print("\none-sixth is : ")print(String1) Output: Binary representation of 16 is 10000 Exponent representation of 165.6458 is 1.656458e+02 one-sixth is : 0.17 A string can be left() or center(^) justified with the use of format specifiers, separated by a colon(:). Python3 # String alignmentString1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks', 'for', 'Geeks')print("\nLeft, center and right alignment with Formatting: ")print(String1) # To demonstrate aligning of spacesString1 = "\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks", 2009)print(String1) Output: Left, center and right alignment with Formatting: |Geeks | for | Geeks| GeeksforGeeks was founded in 2009 ! Old style formatting was done without the use of format method by using % operator Python3 # Python Program for# Old Style Formatting# of Integers Integer1 = 12.3456789print("Formatting in 3.2f format: ")print('The value of Integer1 is %3.2f' % Integer1)print("\nFormatting in 3.4f format: ")print('The value of Integer1 is %3.4f' % Integer1) Output: Formatting in 3.2f format: The value of Integer1 is 12.35 Formatting in 3.4f format: The value of Integer1 is 12.3457 Useful String Operations Logical Operators on String String Formatting using % String Template Class Split a string Python Docstrings String slicing Find all duplicate characters in string Reverse string in Python (5 different ways) Python program to check if a string is palindrome or not https://youtu.be/mvDQuegHVXg More Videos on Python Strings:Python String Methods – Part2 Python String Methods – Part 3 Logical Operations and Splitting in Strings Programs of Python Strings Strings – Set 1, Set 2 String Methods – Set 1 , Set 2 , Set 3 Regular Expressions (Search, Match and Find All) Python String Title method Swap commas and dots in a String Program to convert String to a List Count and display vowels in a string Python program to check the validity of a Password Python program to count number of vowels using sets in given string Check for URL in a String Check if a Substring is Present in a Given String Check if two strings are anagram or not Map function and Dictionary in Python to sum ASCII values Map function and Lambda expression in Python to replace characters SequenceMatcher in Python for Longest Common Substring Print the initials of a name with last name in full The k most frequent words from data set in Python Find all close matches of input string from a list Check if there are K consecutive 1’s in a binary number Lambda and filter in Python Concatenated string with uncommon characters in Python Check if both halves of the string have same set of characters in Python Find the first repeated word in a string in Python Second most repeated word in a sequence in Python K’th Non-repeating Character in Python Reverse words in a given String in Python Print number with commas as 1000 separators in Python Prefix matching in Python using pytrie module Python Regex to extract maximum numeric value from a string Pairs of complete strings in two sets Remove all duplicates words from a given sentence Sort words of sentence in ascending order Reverse each word in a sentence Python code to print common characters of two Strings in alphabetical order Python program to split and join a string Python code to move spaces to front of string in single traversal Run Length Encoding in Python Remove all duplicates from a given string in Python Ways to increment a character in Python Prefix matching in Python using pytrie module Print number with commas as 1000 separators in Python Reverse words in a given String in Python Execute a String of Code in Python String slicing in Python to check if a string can become empty by recursive deletion Ways to print escape characters in Python String slicing in Python to rotate a string Count occurrences of a word in string Find the k most frequent words from data set in Python Python | Print the initials of a name with last name in full Zip function in Python to change to a new character set Python String isnumeric() and its application Sort the words in lexicographical order in Python Find the Number Occurring Odd Number of Times using Lambda expression and reduce function Python String Title method Sort words of sentence in ascending order Convert a list of characters into a string Python groupby method to remove all consecutive duplicates Python groupby method to remove all consecutive duplicates Python program for removing i-th character from a string Replacing strings with numbers in Python for Data Analysis Formatted string literals (f-strings) in Python Python Docstrings Permutation of a given string using inbuilt function Find frequency of each word in a string in Python Program to accept the strings which contains all vowels Count the Number of matching characters in a pair of string Count all prefixes in given string with greatest frequency Program to check if a string contains any special character Generating random strings until a given string is generated Python program to count upper and lower case characters without using inbuilt functions SkFayazuddin nikhilaggarwal3 lina3 surindertarika1234 prajapatirahul28 python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42675, "s": 42647, "text": "\n14 May, 2022" }, { "code": null, "e": 42920, "s": 42675, "text": "In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string." }, { "code": null, "e": 43014, "s": 42920, "text": "Strings in Python can be created using single quotes or double quotes or even triple quotes. " }, { "code": null, "e": 43022, "s": 43014, "text": "Python3" }, { "code": "# Python Program for# Creation of String # Creating a String# with single QuotesString1 = 'Welcome to the Geeks World'print(\"String with the use of Single Quotes: \")print(String1) # Creating a String# with double QuotesString1 = \"I'm a Geek\"print(\"\\nString with the use of Double Quotes: \")print(String1) # Creating a String# with triple QuotesString1 = '''I'm a Geek and I live in a world of \"Geeks\"'''print(\"\\nString with the use of Triple Quotes: \")print(String1) # Creating String with triple# Quotes allows multiple linesString1 = '''Geeks For Life'''print(\"\\nCreating a multiline String: \")print(String1)", "e": 43659, "s": 43022, "text": null }, { "code": null, "e": 43668, "s": 43659, "text": "Output: " }, { "code": null, "e": 43939, "s": 43668, "text": "String with the use of Single Quotes: \nWelcome to the Geeks World\n\nString with the use of Double Quotes: \nI'm a Geek\n\nString with the use of Triple Quotes: \nI'm a Geek and I live in a world of \"Geeks\"\n\nCreating a multiline String: \nGeeks\n For\n Life" }, { "code": null, "e": 44217, "s": 43939, "text": "In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. " }, { "code": null, "e": 44388, "s": 44217, "text": "While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError. " }, { "code": null, "e": 44396, "s": 44388, "text": "Python3" }, { "code": "# Python Program to Access# characters of String String1 = \"GeeksForGeeks\"print(\"Initial String: \")print(String1) # Printing First characterprint(\"\\nFirst character of String is: \")print(String1[0]) # Printing Last characterprint(\"\\nLast character of String is: \")print(String1[-1])", "e": 44682, "s": 44396, "text": null }, { "code": null, "e": 44691, "s": 44682, "text": "Output: " }, { "code": null, "e": 44789, "s": 44691, "text": "Initial String: \nGeeksForGeeks\n\nFirst character of String is: \nG\n\nLast character of String is: \ns" }, { "code": null, "e": 44933, "s": 44789, "text": "To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by using a Slicing operator (colon). " }, { "code": null, "e": 44941, "s": 44933, "text": "Python3" }, { "code": "# Python Program to# demonstrate String slicing # Creating a StringString1 = \"GeeksForGeeks\"print(\"Initial String: \") print(String1) # Printing 3rd to 12th characterprint(\"\\nSlicing characters from 3-12: \")print(String1[3:12]) # Printing characters between # 3rd and 2nd last characterprint(\"\\nSlicing characters between \" + \"3rd and 2nd last character: \")print(String1[3:-2])", "e": 45324, "s": 44941, "text": null }, { "code": null, "e": 45333, "s": 45324, "text": "Output: " }, { "code": null, "e": 45472, "s": 45333, "text": "Initial String: \nGeeksForGeeks\n\nSlicing characters from 3-12: \nksForGeek\n\nSlicing characters between 3rd and 2nd last character: \nksForGee" }, { "code": null, "e": 45902, "s": 45472, "text": "In Python, Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of the entire String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name. " }, { "code": null, "e": 45910, "s": 45902, "text": "Python3" }, { "code": "# Python Program to Update# character of a String String1 = \"Hello, I'm a Geek\"print(\"Initial String: \")print(String1) # Updating a character# of the StringString1[2] = 'p'print(\"\\nUpdating character at 2nd Index: \")print(String1)", "e": 46143, "s": 45910, "text": null }, { "code": null, "e": 46151, "s": 46143, "text": "Error: " }, { "code": null, "e": 46322, "s": 46151, "text": "Traceback (most recent call last): File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in String1[2] = ‘p’ TypeError: ‘str’ object does not support item assignment" }, { "code": null, "e": 46330, "s": 46322, "text": "Python3" }, { "code": "# Python Program to Update# entire String String1 = \"Hello, I'm a Geek\"print(\"Initial String: \")print(String1) # Updating a StringString1 = \"Welcome to the Geek World\"print(\"\\nUpdated String: \")print(String1)", "e": 46541, "s": 46330, "text": null }, { "code": null, "e": 46550, "s": 46541, "text": "Output: " }, { "code": null, "e": 46630, "s": 46550, "text": "Initial String: \nHello, I'm a Geek\n\nUpdated String: \nWelcome to the Geek World " }, { "code": null, "e": 46638, "s": 46630, "text": "Python3" }, { "code": "# Python Program to Delete# characters from a String String1 = \"Hello, I'm a Geek\"print(\"Initial String: \")print(String1) # Deleting a character# of the Stringdel String1[2]print(\"\\nDeleting character at 2nd Index: \")print(String1)", "e": 46872, "s": 46638, "text": null }, { "code": null, "e": 46880, "s": 46872, "text": "Error: " }, { "code": null, "e": 47046, "s": 46880, "text": "Traceback (most recent call last): File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 10, in del String1[2] TypeError: ‘str’ object doesn’t support item deletion" }, { "code": null, "e": 47246, "s": 47046, "text": "Deletion of the entire string is possible with the use of del keyword. Further, if we try to print the string, this will produce an error because String is deleted and is unavailable to be printed. " }, { "code": null, "e": 47254, "s": 47246, "text": "Python3" }, { "code": "# Python Program to Delete# entire String String1 = \"Hello, I'm a Geek\"print(\"Initial String: \")print(String1) # Deleting a String# with the use of deldel String1print(\"\\nDeleting entire String: \")print(String1)", "e": 47468, "s": 47254, "text": null }, { "code": null, "e": 47476, "s": 47468, "text": "Error: " }, { "code": null, "e": 47630, "s": 47476, "text": "Traceback (most recent call last): File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in print(String1) NameError: name ‘String1’ is not defined " }, { "code": null, "e": 47939, "s": 47630, "text": "While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print such Strings. " }, { "code": null, "e": 48166, "s": 47939, "text": "Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and same is done for Double Quotes. " }, { "code": null, "e": 48174, "s": 48166, "text": "Python3" }, { "code": "# Python Program for# Escape Sequencing# of String # Initial StringString1 = '''I'm a \"Geek\"'''print(\"Initial String with use of Triple Quotes: \")print(String1) # Escaping Single QuoteString1 = 'I\\'m a \"Geek\"'print(\"\\nEscaping Single Quote: \")print(String1) # Escaping Double QuotesString1 = \"I'm a \\\"Geek\\\"\"print(\"\\nEscaping Double Quotes: \")print(String1) # Printing Paths with the# use of Escape SequencesString1 = \"C:\\\\Python\\\\Geeks\\\\\"print(\"\\nEscaping Backslashes: \")print(String1)", "e": 48665, "s": 48174, "text": null }, { "code": null, "e": 48674, "s": 48665, "text": "Output: " }, { "code": null, "e": 48848, "s": 48674, "text": "Initial String with use of Triple Quotes: \nI'm a \"Geek\"\n\nEscaping Single Quote: \nI'm a \"Geek\"\n\nEscaping Double Quotes: \nI'm a \"Geek\"\n\nEscaping Backslashes: \nC:\\Python\\Geeks\\" }, { "code": null, "e": 49003, "s": 48848, "text": "To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw string and escape sequences inside it are to be ignored." }, { "code": null, "e": 49011, "s": 49003, "text": "Python3" }, { "code": "# Printing Geeks in HEXString1 = \"This is \\x47\\x65\\x65\\x6b\\x73 in \\x48\\x45\\x58\"print(\"\\nPrinting in HEX with the use of Escape Sequences: \")print(String1) # Using raw String to# ignore Escape SequencesString1 = r\"This is \\x47\\x65\\x65\\x6b\\x73 in \\x48\\x45\\x58\"print(\"\\nPrinting Raw String in HEX Format: \")print(String1)", "e": 49331, "s": 49011, "text": null }, { "code": null, "e": 49341, "s": 49331, "text": "Output: " }, { "code": null, "e": 49495, "s": 49341, "text": "Printing in HEX with the use of Escape Sequences: \nThis is Geeks in HEX\n\nPrinting Raw String in HEX Format: \nThis is \\x47\\x65\\x65\\x6b\\x73 in \\x48\\x45\\x58" }, { "code": null, "e": 49775, "s": 49495, "text": "Strings in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order." }, { "code": null, "e": 49783, "s": 49775, "text": "Python3" }, { "code": "# Python Program for# Formatting of Strings # Default orderString1 = \"{} {} {}\".format('Geeks', 'For', 'Life')print(\"Print String in default order: \")print(String1) # Positional FormattingString1 = \"{1} {0} {2}\".format('Geeks', 'For', 'Life')print(\"\\nPrint String in Positional order: \")print(String1) # Keyword FormattingString1 = \"{l} {f} {g}\".format(g='Geeks', f='For', l='Life')print(\"\\nPrint String in order of Keywords: \")print(String1)", "e": 50229, "s": 49783, "text": null }, { "code": null, "e": 50238, "s": 50229, "text": "Output: " }, { "code": null, "e": 50388, "s": 50238, "text": "Print String in default order: \nGeeks For Life\n\nPrint String in Positional order: \nFor Geeks Life\n\nPrint String in order of Keywords: \nLife For Geeks" }, { "code": null, "e": 50528, "s": 50388, "text": "Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in the exponent form with the use of format specifiers. " }, { "code": null, "e": 50536, "s": 50528, "text": "Python3" }, { "code": "# Formatting of IntegersString1 = \"{0:b}\".format(16)print(\"\\nBinary representation of 16 is \")print(String1) # Formatting of FloatsString1 = \"{0:e}\".format(165.6458)print(\"\\nExponent representation of 165.6458 is \")print(String1) # Rounding off IntegersString1 = \"{0:.2f}\".format(1/6)print(\"\\none-sixth is : \")print(String1)", "e": 50863, "s": 50536, "text": null }, { "code": null, "e": 50872, "s": 50863, "text": "Output: " }, { "code": null, "e": 50986, "s": 50872, "text": "Binary representation of 16 is \n10000\n\nExponent representation of 165.6458 is \n1.656458e+02\n\none-sixth is : \n0.17" }, { "code": null, "e": 51094, "s": 50986, "text": "A string can be left() or center(^) justified with the use of format specifiers, separated by a colon(:). " }, { "code": null, "e": 51102, "s": 51094, "text": "Python3" }, { "code": "# String alignmentString1 = \"|{:<10}|{:^10}|{:>10}|\".format('Geeks', 'for', 'Geeks')print(\"\\nLeft, center and right alignment with Formatting: \")print(String1) # To demonstrate aligning of spacesString1 = \"\\n{0:^16} was founded in {1:<4}!\".format(\"GeeksforGeeks\", 2009)print(String1)", "e": 51387, "s": 51102, "text": null }, { "code": null, "e": 51396, "s": 51387, "text": "Output: " }, { "code": null, "e": 51522, "s": 51396, "text": "Left, center and right alignment with Formatting: \n|Geeks | for | Geeks|\n\n GeeksforGeeks was founded in 2009 !" }, { "code": null, "e": 51606, "s": 51522, "text": "Old style formatting was done without the use of format method by using % operator " }, { "code": null, "e": 51614, "s": 51606, "text": "Python3" }, { "code": "# Python Program for# Old Style Formatting# of Integers Integer1 = 12.3456789print(\"Formatting in 3.2f format: \")print('The value of Integer1 is %3.2f' % Integer1)print(\"\\nFormatting in 3.4f format: \")print('The value of Integer1 is %3.4f' % Integer1)", "e": 51867, "s": 51614, "text": null }, { "code": null, "e": 51876, "s": 51867, "text": "Output: " }, { "code": null, "e": 51997, "s": 51876, "text": "Formatting in 3.2f format: \nThe value of Integer1 is 12.35\n\nFormatting in 3.4f format: \nThe value of Integer1 is 12.3457" }, { "code": null, "e": 52024, "s": 51997, "text": "Useful String Operations " }, { "code": null, "e": 52052, "s": 52024, "text": "Logical Operators on String" }, { "code": null, "e": 52078, "s": 52052, "text": "String Formatting using %" }, { "code": null, "e": 52100, "s": 52078, "text": "String Template Class" }, { "code": null, "e": 52115, "s": 52100, "text": "Split a string" }, { "code": null, "e": 52133, "s": 52115, "text": "Python Docstrings" }, { "code": null, "e": 52148, "s": 52133, "text": "String slicing" }, { "code": null, "e": 52188, "s": 52148, "text": "Find all duplicate characters in string" }, { "code": null, "e": 52232, "s": 52188, "text": "Reverse string in Python (5 different ways)" }, { "code": null, "e": 52289, "s": 52232, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 52318, "s": 52289, "text": "https://youtu.be/mvDQuegHVXg" }, { "code": null, "e": 52454, "s": 52318, "text": "More Videos on Python Strings:Python String Methods – Part2 Python String Methods – Part 3 Logical Operations and Splitting in Strings " }, { "code": null, "e": 52483, "s": 52454, "text": "Programs of Python Strings " }, { "code": null, "e": 52506, "s": 52483, "text": "Strings – Set 1, Set 2" }, { "code": null, "e": 52545, "s": 52506, "text": "String Methods – Set 1 , Set 2 , Set 3" }, { "code": null, "e": 52594, "s": 52545, "text": "Regular Expressions (Search, Match and Find All)" }, { "code": null, "e": 52621, "s": 52594, "text": "Python String Title method" }, { "code": null, "e": 52654, "s": 52621, "text": "Swap commas and dots in a String" }, { "code": null, "e": 52690, "s": 52654, "text": "Program to convert String to a List" }, { "code": null, "e": 52727, "s": 52690, "text": "Count and display vowels in a string" }, { "code": null, "e": 52778, "s": 52727, "text": "Python program to check the validity of a Password" }, { "code": null, "e": 52846, "s": 52778, "text": "Python program to count number of vowels using sets in given string" }, { "code": null, "e": 52872, "s": 52846, "text": "Check for URL in a String" }, { "code": null, "e": 52922, "s": 52872, "text": "Check if a Substring is Present in a Given String" }, { "code": null, "e": 52962, "s": 52922, "text": "Check if two strings are anagram or not" }, { "code": null, "e": 53020, "s": 52962, "text": "Map function and Dictionary in Python to sum ASCII values" }, { "code": null, "e": 53087, "s": 53020, "text": "Map function and Lambda expression in Python to replace characters" }, { "code": null, "e": 53142, "s": 53087, "text": "SequenceMatcher in Python for Longest Common Substring" }, { "code": null, "e": 53194, "s": 53142, "text": "Print the initials of a name with last name in full" }, { "code": null, "e": 53244, "s": 53194, "text": "The k most frequent words from data set in Python" }, { "code": null, "e": 53295, "s": 53244, "text": "Find all close matches of input string from a list" }, { "code": null, "e": 53351, "s": 53295, "text": "Check if there are K consecutive 1’s in a binary number" }, { "code": null, "e": 53379, "s": 53351, "text": "Lambda and filter in Python" }, { "code": null, "e": 53434, "s": 53379, "text": "Concatenated string with uncommon characters in Python" }, { "code": null, "e": 53507, "s": 53434, "text": "Check if both halves of the string have same set of characters in Python" }, { "code": null, "e": 53558, "s": 53507, "text": "Find the first repeated word in a string in Python" }, { "code": null, "e": 53608, "s": 53558, "text": "Second most repeated word in a sequence in Python" }, { "code": null, "e": 53648, "s": 53608, "text": "K’th Non-repeating Character in Python " }, { "code": null, "e": 53690, "s": 53648, "text": "Reverse words in a given String in Python" }, { "code": null, "e": 53744, "s": 53690, "text": "Print number with commas as 1000 separators in Python" }, { "code": null, "e": 53790, "s": 53744, "text": "Prefix matching in Python using pytrie module" }, { "code": null, "e": 53850, "s": 53790, "text": "Python Regex to extract maximum numeric value from a string" }, { "code": null, "e": 53888, "s": 53850, "text": "Pairs of complete strings in two sets" }, { "code": null, "e": 53938, "s": 53888, "text": "Remove all duplicates words from a given sentence" }, { "code": null, "e": 53980, "s": 53938, "text": "Sort words of sentence in ascending order" }, { "code": null, "e": 54012, "s": 53980, "text": "Reverse each word in a sentence" }, { "code": null, "e": 54088, "s": 54012, "text": "Python code to print common characters of two Strings in alphabetical order" }, { "code": null, "e": 54130, "s": 54088, "text": "Python program to split and join a string" }, { "code": null, "e": 54196, "s": 54130, "text": "Python code to move spaces to front of string in single traversal" }, { "code": null, "e": 54226, "s": 54196, "text": "Run Length Encoding in Python" }, { "code": null, "e": 54278, "s": 54226, "text": "Remove all duplicates from a given string in Python" }, { "code": null, "e": 54318, "s": 54278, "text": "Ways to increment a character in Python" }, { "code": null, "e": 54364, "s": 54318, "text": "Prefix matching in Python using pytrie module" }, { "code": null, "e": 54418, "s": 54364, "text": "Print number with commas as 1000 separators in Python" }, { "code": null, "e": 54460, "s": 54418, "text": "Reverse words in a given String in Python" }, { "code": null, "e": 54495, "s": 54460, "text": "Execute a String of Code in Python" }, { "code": null, "e": 54580, "s": 54495, "text": "String slicing in Python to check if a string can become empty by recursive deletion" }, { "code": null, "e": 54622, "s": 54580, "text": "Ways to print escape characters in Python" }, { "code": null, "e": 54666, "s": 54622, "text": "String slicing in Python to rotate a string" }, { "code": null, "e": 54704, "s": 54666, "text": "Count occurrences of a word in string" }, { "code": null, "e": 54759, "s": 54704, "text": "Find the k most frequent words from data set in Python" }, { "code": null, "e": 54820, "s": 54759, "text": "Python | Print the initials of a name with last name in full" }, { "code": null, "e": 54876, "s": 54820, "text": "Zip function in Python to change to a new character set" }, { "code": null, "e": 54922, "s": 54876, "text": "Python String isnumeric() and its application" }, { "code": null, "e": 54972, "s": 54922, "text": "Sort the words in lexicographical order in Python" }, { "code": null, "e": 55062, "s": 54972, "text": "Find the Number Occurring Odd Number of Times using Lambda expression and reduce function" }, { "code": null, "e": 55089, "s": 55062, "text": "Python String Title method" }, { "code": null, "e": 55131, "s": 55089, "text": "Sort words of sentence in ascending order" }, { "code": null, "e": 55174, "s": 55131, "text": "Convert a list of characters into a string" }, { "code": null, "e": 55233, "s": 55174, "text": "Python groupby method to remove all consecutive duplicates" }, { "code": null, "e": 55292, "s": 55233, "text": "Python groupby method to remove all consecutive duplicates" }, { "code": null, "e": 55349, "s": 55292, "text": "Python program for removing i-th character from a string" }, { "code": null, "e": 55408, "s": 55349, "text": "Replacing strings with numbers in Python for Data Analysis" }, { "code": null, "e": 55456, "s": 55408, "text": "Formatted string literals (f-strings) in Python" }, { "code": null, "e": 55474, "s": 55456, "text": "Python Docstrings" }, { "code": null, "e": 55527, "s": 55474, "text": "Permutation of a given string using inbuilt function" }, { "code": null, "e": 55577, "s": 55527, "text": "Find frequency of each word in a string in Python" }, { "code": null, "e": 55633, "s": 55577, "text": "Program to accept the strings which contains all vowels" }, { "code": null, "e": 55693, "s": 55633, "text": "Count the Number of matching characters in a pair of string" }, { "code": null, "e": 55752, "s": 55693, "text": "Count all prefixes in given string with greatest frequency" }, { "code": null, "e": 55812, "s": 55752, "text": "Program to check if a string contains any special character" }, { "code": null, "e": 55872, "s": 55812, "text": "Generating random strings until a given string is generated" }, { "code": null, "e": 55960, "s": 55872, "text": "Python program to count upper and lower case characters without using inbuilt functions" }, { "code": null, "e": 55973, "s": 55960, "text": "SkFayazuddin" }, { "code": null, "e": 55989, "s": 55973, "text": "nikhilaggarwal3" }, { "code": null, "e": 55995, "s": 55989, "text": "lina3" }, { "code": null, "e": 56014, "s": 55995, "text": "surindertarika1234" }, { "code": null, "e": 56031, "s": 56014, "text": "prajapatirahul28" }, { "code": null, "e": 56045, "s": 56031, "text": "python-string" }, { "code": null, "e": 56052, "s": 56045, "text": "Python" }, { "code": null, "e": 56150, "s": 56052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 56178, "s": 56150, "text": "Read JSON file using Python" }, { "code": null, "e": 56228, "s": 56178, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 56250, "s": 56228, "text": "Python map() function" }, { "code": null, "e": 56294, "s": 56250, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 56329, "s": 56294, "text": "Read a file line by line in Python" }, { "code": null, "e": 56361, "s": 56329, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 56383, "s": 56361, "text": "Enumerate() in Python" }, { "code": null, "e": 56425, "s": 56383, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 56455, "s": 56425, "text": "Iterate over a list in Python" } ]
Measure similarity between images using Python-OpenCV - GeeksforGeeks
18 Aug, 2021 Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let’s find out which data image is more similar to the test image using python and OpenCV library in Python.Let’s first load the image and find out the histogram of images.Importing library import cv2 Importing image data image = cv2.imread('test.jpg') Converting to gray image gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) Finding Histogram histogram = cv2.calcHist([gray_image], [0], None, [256], [0, 256]) Example:Images used:data1.jpg data2.jpg test.jpg Python3 import cv2 # test imageimage = cv2.imread('cat.jpg')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)histogram = cv2.calcHist([gray_image], [0], None, [256], [0, 256]) # data1 imageimage = cv2.imread('cat.jpeg')gray_image1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)histogram1 = cv2.calcHist([gray_image1], [0], None, [256], [0, 256]) # data2 imageimage = cv2.imread('food.jpeg')gray_image2 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)histogram2 = cv2.calcHist([gray_image2], [0], None, [256], [0, 256]) c1, c2 = 0, 0 # Euclidean Distance between data1 and testi = 0while i<len(histogram) and i<len(histogram1): c1+=(histogram[i]-histogram1[i])**2 i+= 1c1 = c1**(1 / 2) # Euclidean Distance between data2 and testi = 0while i<len(histogram) and i<len(histogram2): c2+=(histogram[i]-histogram2[i])**2 i+= 1c2 = c2**(1 / 2) if(c1<c2): print("data1.jpg is more similar to test.jpg as compare to data2.jpg")else: print("data2.jpg is more similar to test.jpg as compare to data1.jpg") Output : data1.jpg is more similar to test.jpg as compare to data2.jpg singghakshay Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25755, "s": 25727, "text": "\n18 Aug, 2021" }, { "code": null, "e": 26025, "s": 25755, "text": "Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let’s find out which data image is more similar to the test image using python and OpenCV library in Python.Let’s first load the image and find out the histogram of images.Importing library " }, { "code": null, "e": 26036, "s": 26025, "text": "import cv2" }, { "code": null, "e": 26059, "s": 26036, "text": "Importing image data " }, { "code": null, "e": 26090, "s": 26059, "text": "image = cv2.imread('test.jpg')" }, { "code": null, "e": 26117, "s": 26090, "text": "Converting to gray image " }, { "code": null, "e": 26170, "s": 26117, "text": "gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)" }, { "code": null, "e": 26190, "s": 26170, "text": "Finding Histogram " }, { "code": null, "e": 26288, "s": 26190, "text": "histogram = cv2.calcHist([gray_image], [0], \n None, [256], [0, 256])" }, { "code": null, "e": 26320, "s": 26288, "text": "Example:Images used:data1.jpg " }, { "code": null, "e": 26332, "s": 26320, "text": "data2.jpg " }, { "code": null, "e": 26343, "s": 26332, "text": "test.jpg " }, { "code": null, "e": 26353, "s": 26345, "text": "Python3" }, { "code": "import cv2 # test imageimage = cv2.imread('cat.jpg')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)histogram = cv2.calcHist([gray_image], [0], None, [256], [0, 256]) # data1 imageimage = cv2.imread('cat.jpeg')gray_image1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)histogram1 = cv2.calcHist([gray_image1], [0], None, [256], [0, 256]) # data2 imageimage = cv2.imread('food.jpeg')gray_image2 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)histogram2 = cv2.calcHist([gray_image2], [0], None, [256], [0, 256]) c1, c2 = 0, 0 # Euclidean Distance between data1 and testi = 0while i<len(histogram) and i<len(histogram1): c1+=(histogram[i]-histogram1[i])**2 i+= 1c1 = c1**(1 / 2) # Euclidean Distance between data2 and testi = 0while i<len(histogram) and i<len(histogram2): c2+=(histogram[i]-histogram2[i])**2 i+= 1c2 = c2**(1 / 2) if(c1<c2): print(\"data1.jpg is more similar to test.jpg as compare to data2.jpg\")else: print(\"data2.jpg is more similar to test.jpg as compare to data1.jpg\")", "e": 27438, "s": 26353, "text": null }, { "code": null, "e": 27449, "s": 27438, "text": "Output : " }, { "code": null, "e": 27511, "s": 27449, "text": "data1.jpg is more similar to test.jpg as compare to data2.jpg" }, { "code": null, "e": 27526, "s": 27513, "text": "singghakshay" }, { "code": null, "e": 27540, "s": 27526, "text": "Python-OpenCV" }, { "code": null, "e": 27547, "s": 27540, "text": "Python" }, { "code": null, "e": 27645, "s": 27547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27663, "s": 27645, "text": "Python Dictionary" }, { "code": null, "e": 27695, "s": 27663, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27717, "s": 27695, "text": "Enumerate() in Python" }, { "code": null, "e": 27759, "s": 27717, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27785, "s": 27759, "text": "Python String | replace()" }, { "code": null, "e": 27814, "s": 27785, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27851, "s": 27814, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27893, "s": 27851, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27929, "s": 27893, "text": "Convert integer to string in Python" } ]
How to open an image from the URL in PIL? - GeeksforGeeks
26 Mar, 2021 In this article, we will learn How to open an image from the URL using the PIL module in python. For the opening of the image from a URL in Python, we need two Packages urllib and Pillow(PIL). Install the required libraries and then import them. To install use the following commands: pip install pillow Copy the URL of any image. Write URL with file name in urllib.request.urlretrieve() method. Use Image.open() method to open image. At last show the image using obj.show() method. Sample Code: import urllib.request from PIL import Image urllib.request.urlretrieve(‘Image url’, “file_name”) img = Image.open(“file_name”) img.show() Example: Python3 # importing modulesimport urllib.requestfrom PIL import Image urllib.request.urlretrieve( 'https://media.geeksforgeeks.org/wp-content/uploads/20210318103632/gfg-300x300.png', "gfg.png") img = Image.open("gfg.png")img.show() Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Mar, 2021" }, { "code": null, "e": 25730, "s": 25537, "text": "In this article, we will learn How to open an image from the URL using the PIL module in python. For the opening of the image from a URL in Python, we need two Packages urllib and Pillow(PIL)." }, { "code": null, "e": 25822, "s": 25730, "text": "Install the required libraries and then import them. To install use the following commands:" }, { "code": null, "e": 25841, "s": 25822, "text": "pip install pillow" }, { "code": null, "e": 25868, "s": 25841, "text": "Copy the URL of any image." }, { "code": null, "e": 25933, "s": 25868, "text": "Write URL with file name in urllib.request.urlretrieve() method." }, { "code": null, "e": 25972, "s": 25933, "text": "Use Image.open() method to open image." }, { "code": null, "e": 26020, "s": 25972, "text": "At last show the image using obj.show() method." }, { "code": null, "e": 26034, "s": 26020, "text": "Sample Code: " }, { "code": null, "e": 26056, "s": 26034, "text": "import urllib.request" }, { "code": null, "e": 26078, "s": 26056, "text": "from PIL import Image" }, { "code": null, "e": 26131, "s": 26078, "text": "urllib.request.urlretrieve(‘Image url’, “file_name”)" }, { "code": null, "e": 26161, "s": 26131, "text": "img = Image.open(“file_name”)" }, { "code": null, "e": 26172, "s": 26161, "text": "img.show()" }, { "code": null, "e": 26181, "s": 26172, "text": "Example:" }, { "code": null, "e": 26189, "s": 26181, "text": "Python3" }, { "code": "# importing modulesimport urllib.requestfrom PIL import Image urllib.request.urlretrieve( 'https://media.geeksforgeeks.org/wp-content/uploads/20210318103632/gfg-300x300.png', \"gfg.png\") img = Image.open(\"gfg.png\")img.show()", "e": 26418, "s": 26189, "text": null }, { "code": null, "e": 26425, "s": 26418, "text": "Picked" }, { "code": null, "e": 26436, "s": 26425, "text": "Python-pil" }, { "code": null, "e": 26443, "s": 26436, "text": "Python" }, { "code": null, "e": 26541, "s": 26443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26573, "s": 26541, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26615, "s": 26573, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26657, "s": 26615, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26713, "s": 26657, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26740, "s": 26713, "text": "Python Classes and Objects" }, { "code": null, "e": 26779, "s": 26740, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26810, "s": 26779, "text": "Python | os.path.join() method" }, { "code": null, "e": 26832, "s": 26810, "text": "Defaultdict in Python" }, { "code": null, "e": 26861, "s": 26832, "text": "Create a directory in Python" } ]
Gotchas in Python - GeeksforGeeks
02 Sep, 2021 Python is a go-to language for most of the newcomers into the programming world. This is because it is fairly simple, highly in-demand, and ultimately powerful. But there are some cases which might confuse or rather trick a rookie coder. These are called “Gotchas”! Originating from the informal term “Got You!”, a gotcha is a case or scenario when the program plays the trick and results in an output that is quite different from what was expected. It should be noted that a gotcha is not an error or an exception. It is a perfectly valid code that results in an incorrect output only because we missed a teeny-tiny fact or point while writing our program. Therefore, we can also consider gotchas as “commonly made mistakes while coding”. Let’s take a look at some most common gotchas in Python3 and how to tackle them: The parenthesis gotchas :There are a few gotchas that arise when the parenthesis is used incorrectly or unnecessarily.Example:Python3Python3# results in Falseprint(5>2 == True) Output:FalseThis results in False because the above expression effectively means that 5>2 and 2==True. This implies, True and False. Hence, the final result is False.It can be corrected by the use of parenthesis.Python3Python3# results in Trueprint((5>2) == True)Output:True Here is one more example:Python3Python3# results in Falseprint(5 is (not None)) Output:FalseThis is because "is not" is different from "is" and "not" being used separately. The part (not None) equals True and 5 is True results in False. It can be corrected by not using any parenthesis.Python3Python3# results in Trueprint(5 is not None)Output:True “is”, “==”, “is not”, “!=” : This is a short but very common gotcha. Many new programmers often think that is and == are the same thing. But it’s definitely not!Python3Python3# results in Trueprint(1 == True) # results in Falseprint(1 is True) Output:True False On the other hand, is not and != are same.Python3Python3# results in Trueprint(1 != False) # results in Trueprint(1 is not False)Output:True True Default arguments gotcha :In Python, default arguments are declared only once when the function is run for the first time and from then on, the declared argument is used every time.Python3Python3def appendNew(appendTo =[]): appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())It’s expected that every time we call appendNew(), a new list will be created which will have 1 in it. But what happens is this:[1] [1, 1] The variable appendTo isn’t created again when the function is run for the second time. Instead, it’s created only the first time and used again and again. We can tackle it by:Python3Python3def appendNew(appendTo = None): if appendTo == None: appendTo =[] appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())Output:[1] [1] Scope gotchas :Sometimes, we must keep in mind the scope of the variable we are dealing with, i.e whether it is a global scope(works but inside and outside of a function) or a local scope(works just inside the function).Example:Python3Python3list1 = [1, 2, 3]def baz1(): # the code works fine list1.append(4) return list1def baz2(): # Doesn't work fine list1 += [5] return list1 # Driver's codeprint(baz1())print(baz2())Output:[1, 2, 3, 4] Traceback (most recent call last): File "/home/ba0dfa25407638b061076b45ce165ce5.py", line 15, in print(baz2()) File "/home/ba0dfa25407638b061076b45ce165ce5.py", line 10, in baz2 list1 += [5] UnboundLocalError: local variable 'list1' referenced before assignment This happens becauselist1 += [5]means that we are assigning to the variable list1 but list1 is defined outside the scope of our function. While in baz1(), we are appending to list1 instead of assigning and hence it works fine.Variables are bound late in closures :Python has an infamous late binding behavior. By this, we mean that the value of a variable which is being iterated over is finalized to the value when it reaches its last iteration. Let’s look at an example:Python3Python3def create_multipliers(): # lambda function creates an iterable # list anonymously return [lambda c : i * c for i in range(6)] for multiplier in create_multipliers(): print multiplier(3)The expected result is of course:0 3 6 9 12 15 But what we get is:15 15 15 15 15 15 This is because when the loop iteration is complete, i has a value of 5 and hence 3*5 each time results in 15.It can be solved by:Python3Python3def create_multipliers(): return [lambda x, i = i : i * x for i in range(6)] for multiplier in create_multipliers(): print(multiplier(3))Output:0 3 6 9 12 15 Mutating a list while iterating over it :This is the most common gotcha which new coders face almost all the time. While working with a list or other mutable items, if we mutate it while iterating over it, it’s certain to cause errors. It’s recommended that we create the copy of the list instead and mutate it rather than the original list.Python3Python3# buggy program to print a list # of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] for i in range(len(numbers)): if not even(numbers[i]): del numbers[i]Output:Traceback (most recent call last): File "/home/92eed8bfd8c92fca3cf85f22e8cfd9ea.py", line 9, in if not even(numbers[i]): IndexError: list index out of range But if we use a copy of numbers instead:Python3Python3# working program to print a # list of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if even(n)]print(numbers) Output:[1, 3, 5, 7, 9] The parenthesis gotchas :There are a few gotchas that arise when the parenthesis is used incorrectly or unnecessarily.Example:Python3Python3# results in Falseprint(5>2 == True) Output:FalseThis results in False because the above expression effectively means that 5>2 and 2==True. This implies, True and False. Hence, the final result is False.It can be corrected by the use of parenthesis.Python3Python3# results in Trueprint((5>2) == True)Output:True Here is one more example:Python3Python3# results in Falseprint(5 is (not None)) Output:FalseThis is because "is not" is different from "is" and "not" being used separately. The part (not None) equals True and 5 is True results in False. It can be corrected by not using any parenthesis.Python3Python3# results in Trueprint(5 is not None)Output:True There are a few gotchas that arise when the parenthesis is used incorrectly or unnecessarily. Example: Python3 # results in Falseprint(5>2 == True) Output: False This results in False because the above expression effectively means that 5>2 and 2==True. This implies, True and False. Hence, the final result is False.It can be corrected by the use of parenthesis. Python3 # results in Trueprint((5>2) == True) Output: True Here is one more example: Python3 # results in Falseprint(5 is (not None)) Output: False This is because "is not" is different from "is" and "not" being used separately. The part (not None) equals True and 5 is True results in False. It can be corrected by not using any parenthesis. Python3 # results in Trueprint(5 is not None) Output: True “is”, “==”, “is not”, “!=” : This is a short but very common gotcha. Many new programmers often think that is and == are the same thing. But it’s definitely not!Python3Python3# results in Trueprint(1 == True) # results in Falseprint(1 is True) Output:True False On the other hand, is not and != are same.Python3Python3# results in Trueprint(1 != False) # results in Trueprint(1 is not False)Output:True True Python3 # results in Trueprint(1 == True) # results in Falseprint(1 is True) Output: True False On the other hand, is not and != are same. Python3 # results in Trueprint(1 != False) # results in Trueprint(1 is not False) Output: True True Default arguments gotcha :In Python, default arguments are declared only once when the function is run for the first time and from then on, the declared argument is used every time.Python3Python3def appendNew(appendTo =[]): appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())It’s expected that every time we call appendNew(), a new list will be created which will have 1 in it. But what happens is this:[1] [1, 1] The variable appendTo isn’t created again when the function is run for the second time. Instead, it’s created only the first time and used again and again. We can tackle it by:Python3Python3def appendNew(appendTo = None): if appendTo == None: appendTo =[] appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())Output:[1] [1] In Python, default arguments are declared only once when the function is run for the first time and from then on, the declared argument is used every time. Python3 def appendNew(appendTo =[]): appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew()) It’s expected that every time we call appendNew(), a new list will be created which will have 1 in it. But what happens is this: [1] [1, 1] The variable appendTo isn’t created again when the function is run for the second time. Instead, it’s created only the first time and used again and again. We can tackle it by: Python3 def appendNew(appendTo = None): if appendTo == None: appendTo =[] appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew()) Output: [1] [1] Scope gotchas :Sometimes, we must keep in mind the scope of the variable we are dealing with, i.e whether it is a global scope(works but inside and outside of a function) or a local scope(works just inside the function).Example:Python3Python3list1 = [1, 2, 3]def baz1(): # the code works fine list1.append(4) return list1def baz2(): # Doesn't work fine list1 += [5] return list1 # Driver's codeprint(baz1())print(baz2())Output:[1, 2, 3, 4] Traceback (most recent call last): File "/home/ba0dfa25407638b061076b45ce165ce5.py", line 15, in print(baz2()) File "/home/ba0dfa25407638b061076b45ce165ce5.py", line 10, in baz2 list1 += [5] UnboundLocalError: local variable 'list1' referenced before assignment This happens becauselist1 += [5]means that we are assigning to the variable list1 but list1 is defined outside the scope of our function. While in baz1(), we are appending to list1 instead of assigning and hence it works fine. Sometimes, we must keep in mind the scope of the variable we are dealing with, i.e whether it is a global scope(works but inside and outside of a function) or a local scope(works just inside the function). Example: Python3 list1 = [1, 2, 3]def baz1(): # the code works fine list1.append(4) return list1def baz2(): # Doesn't work fine list1 += [5] return list1 # Driver's codeprint(baz1())print(baz2()) Output: [1, 2, 3, 4] Traceback (most recent call last): File "/home/ba0dfa25407638b061076b45ce165ce5.py", line 15, in print(baz2()) File "/home/ba0dfa25407638b061076b45ce165ce5.py", line 10, in baz2 list1 += [5] UnboundLocalError: local variable 'list1' referenced before assignment This happens because list1 += [5] means that we are assigning to the variable list1 but list1 is defined outside the scope of our function. While in baz1(), we are appending to list1 instead of assigning and hence it works fine. Variables are bound late in closures :Python has an infamous late binding behavior. By this, we mean that the value of a variable which is being iterated over is finalized to the value when it reaches its last iteration. Let’s look at an example:Python3Python3def create_multipliers(): # lambda function creates an iterable # list anonymously return [lambda c : i * c for i in range(6)] for multiplier in create_multipliers(): print multiplier(3)The expected result is of course:0 3 6 9 12 15 But what we get is:15 15 15 15 15 15 This is because when the loop iteration is complete, i has a value of 5 and hence 3*5 each time results in 15.It can be solved by:Python3Python3def create_multipliers(): return [lambda x, i = i : i * x for i in range(6)] for multiplier in create_multipliers(): print(multiplier(3))Output:0 3 6 9 12 15 Python has an infamous late binding behavior. By this, we mean that the value of a variable which is being iterated over is finalized to the value when it reaches its last iteration. Let’s look at an example: Python3 def create_multipliers(): # lambda function creates an iterable # list anonymously return [lambda c : i * c for i in range(6)] for multiplier in create_multipliers(): print multiplier(3) The expected result is of course: 0 3 6 9 12 15 But what we get is: 15 15 15 15 15 15 This is because when the loop iteration is complete, i has a value of 5 and hence 3*5 each time results in 15.It can be solved by: Python3 def create_multipliers(): return [lambda x, i = i : i * x for i in range(6)] for multiplier in create_multipliers(): print(multiplier(3)) Output: 0 3 6 9 12 15 Mutating a list while iterating over it :This is the most common gotcha which new coders face almost all the time. While working with a list or other mutable items, if we mutate it while iterating over it, it’s certain to cause errors. It’s recommended that we create the copy of the list instead and mutate it rather than the original list.Python3Python3# buggy program to print a list # of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] for i in range(len(numbers)): if not even(numbers[i]): del numbers[i]Output:Traceback (most recent call last): File "/home/92eed8bfd8c92fca3cf85f22e8cfd9ea.py", line 9, in if not even(numbers[i]): IndexError: list index out of range But if we use a copy of numbers instead:Python3Python3# working program to print a # list of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if even(n)]print(numbers) Output:[1, 3, 5, 7, 9] This is the most common gotcha which new coders face almost all the time. While working with a list or other mutable items, if we mutate it while iterating over it, it’s certain to cause errors. It’s recommended that we create the copy of the list instead and mutate it rather than the original list. Python3 # buggy program to print a list # of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] for i in range(len(numbers)): if not even(numbers[i]): del numbers[i] Output: Traceback (most recent call last): File "/home/92eed8bfd8c92fca3cf85f22e8cfd9ea.py", line 9, in if not even(numbers[i]): IndexError: list index out of range But if we use a copy of numbers instead: Python3 # working program to print a # list of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if even(n)]print(numbers) Output: [1, 3, 5, 7, 9] abhishek0719kadiyan python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26277, "s": 25537, "text": "Python is a go-to language for most of the newcomers into the programming world. This is because it is fairly simple, highly in-demand, and ultimately powerful. But there are some cases which might confuse or rather trick a rookie coder. These are called “Gotchas”! Originating from the informal term “Got You!”, a gotcha is a case or scenario when the program plays the trick and results in an output that is quite different from what was expected. It should be noted that a gotcha is not an error or an exception. It is a perfectly valid code that results in an incorrect output only because we missed a teeny-tiny fact or point while writing our program. Therefore, we can also consider gotchas as “commonly made mistakes while coding”." }, { "code": null, "e": 26358, "s": 26277, "text": "Let’s take a look at some most common gotchas in Python3 and how to tackle them:" }, { "code": null, "e": 31275, "s": 26358, "text": "The parenthesis gotchas :There are a few gotchas that arise when the parenthesis is used incorrectly or unnecessarily.Example:Python3Python3# results in Falseprint(5>2 == True) Output:FalseThis results in False because the above expression effectively means that 5>2 and 2==True. This implies, True and False. Hence, the final result is False.It can be corrected by the use of parenthesis.Python3Python3# results in Trueprint((5>2) == True)Output:True\nHere is one more example:Python3Python3# results in Falseprint(5 is (not None)) Output:FalseThis is because \"is not\" is different from \"is\" and \"not\" being used separately. The part (not None) equals True and 5 is True results in False. It can be corrected by not using any parenthesis.Python3Python3# results in Trueprint(5 is not None)Output:True\n“is”, “==”, “is not”, “!=” : This is a short but very common gotcha. Many new programmers often think that is and == are the same thing. But it’s definitely not!Python3Python3# results in Trueprint(1 == True) # results in Falseprint(1 is True) Output:True\nFalse\nOn the other hand, is not and != are same.Python3Python3# results in Trueprint(1 != False) # results in Trueprint(1 is not False)Output:True\nTrue\nDefault arguments gotcha :In Python, default arguments are declared only once when the function is run for the first time and from then on, the declared argument is used every time.Python3Python3def appendNew(appendTo =[]): appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())It’s expected that every time we call appendNew(), a new list will be created which will have 1 in it. But what happens is this:[1]\n[1, 1]\nThe variable appendTo isn’t created again when the function is run for the second time. Instead, it’s created only the first time and used again and again. We can tackle it by:Python3Python3def appendNew(appendTo = None): if appendTo == None: appendTo =[] appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())Output:[1]\n[1]\nScope gotchas :Sometimes, we must keep in mind the scope of the variable we are dealing with, i.e whether it is a global scope(works but inside and outside of a function) or a local scope(works just inside the function).Example:Python3Python3list1 = [1, 2, 3]def baz1(): # the code works fine list1.append(4) return list1def baz2(): # Doesn't work fine list1 += [5] return list1 # Driver's codeprint(baz1())print(baz2())Output:[1, 2, 3, 4]\nTraceback (most recent call last):\n File \"/home/ba0dfa25407638b061076b45ce165ce5.py\", line 15, in \n print(baz2())\n File \"/home/ba0dfa25407638b061076b45ce165ce5.py\", line 10, in baz2\n list1 += [5] \nUnboundLocalError: local variable 'list1' referenced before assignment\nThis happens becauselist1 += [5]means that we are assigning to the variable list1 but list1 is defined outside the scope of our function. While in baz1(), we are appending to list1 instead of assigning and hence it works fine.Variables are bound late in closures :Python has an infamous late binding behavior. By this, we mean that the value of a variable which is being iterated over is finalized to the value when it reaches its last iteration. Let’s look at an example:Python3Python3def create_multipliers(): # lambda function creates an iterable # list anonymously return [lambda c : i * c for i in range(6)] for multiplier in create_multipliers(): print multiplier(3)The expected result is of course:0\n3\n6\n9\n12\n15\nBut what we get is:15\n15\n15\n15\n15\n15\nThis is because when the loop iteration is complete, i has a value of 5 and hence 3*5 each time results in 15.It can be solved by:Python3Python3def create_multipliers(): return [lambda x, i = i : i * x for i in range(6)] for multiplier in create_multipliers(): print(multiplier(3))Output:0\n3\n6\n9\n12\n15\nMutating a list while iterating over it :This is the most common gotcha which new coders face almost all the time. While working with a list or other mutable items, if we mutate it while iterating over it, it’s certain to cause errors. It’s recommended that we create the copy of the list instead and mutate it rather than the original list.Python3Python3# buggy program to print a list # of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] for i in range(len(numbers)): if not even(numbers[i]): del numbers[i]Output:Traceback (most recent call last):\n File \"/home/92eed8bfd8c92fca3cf85f22e8cfd9ea.py\", line 9, in \n if not even(numbers[i]):\nIndexError: list index out of range\nBut if we use a copy of numbers instead:Python3Python3# working program to print a # list of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if even(n)]print(numbers) Output:[1, 3, 5, 7, 9]\n" }, { "code": null, "e": 32077, "s": 31275, "text": "The parenthesis gotchas :There are a few gotchas that arise when the parenthesis is used incorrectly or unnecessarily.Example:Python3Python3# results in Falseprint(5>2 == True) Output:FalseThis results in False because the above expression effectively means that 5>2 and 2==True. This implies, True and False. Hence, the final result is False.It can be corrected by the use of parenthesis.Python3Python3# results in Trueprint((5>2) == True)Output:True\nHere is one more example:Python3Python3# results in Falseprint(5 is (not None)) Output:FalseThis is because \"is not\" is different from \"is\" and \"not\" being used separately. The part (not None) equals True and 5 is True results in False. It can be corrected by not using any parenthesis.Python3Python3# results in Trueprint(5 is not None)Output:True\n" }, { "code": null, "e": 32171, "s": 32077, "text": "There are a few gotchas that arise when the parenthesis is used incorrectly or unnecessarily." }, { "code": null, "e": 32180, "s": 32171, "text": "Example:" }, { "code": null, "e": 32188, "s": 32180, "text": "Python3" }, { "code": "# results in Falseprint(5>2 == True) ", "e": 32226, "s": 32188, "text": null }, { "code": null, "e": 32234, "s": 32226, "text": "Output:" }, { "code": null, "e": 32240, "s": 32234, "text": "False" }, { "code": null, "e": 32441, "s": 32240, "text": "This results in False because the above expression effectively means that 5>2 and 2==True. This implies, True and False. Hence, the final result is False.It can be corrected by the use of parenthesis." }, { "code": null, "e": 32449, "s": 32441, "text": "Python3" }, { "code": "# results in Trueprint((5>2) == True)", "e": 32487, "s": 32449, "text": null }, { "code": null, "e": 32495, "s": 32487, "text": "Output:" }, { "code": null, "e": 32501, "s": 32495, "text": "True\n" }, { "code": null, "e": 32527, "s": 32501, "text": "Here is one more example:" }, { "code": null, "e": 32535, "s": 32527, "text": "Python3" }, { "code": "# results in Falseprint(5 is (not None)) ", "e": 32577, "s": 32535, "text": null }, { "code": null, "e": 32585, "s": 32577, "text": "Output:" }, { "code": null, "e": 32591, "s": 32585, "text": "False" }, { "code": null, "e": 32786, "s": 32591, "text": "This is because \"is not\" is different from \"is\" and \"not\" being used separately. The part (not None) equals True and 5 is True results in False. It can be corrected by not using any parenthesis." }, { "code": null, "e": 32794, "s": 32786, "text": "Python3" }, { "code": "# results in Trueprint(5 is not None)", "e": 32832, "s": 32794, "text": null }, { "code": null, "e": 32840, "s": 32832, "text": "Output:" }, { "code": null, "e": 32846, "s": 32840, "text": "True\n" }, { "code": null, "e": 33258, "s": 32846, "text": "“is”, “==”, “is not”, “!=” : This is a short but very common gotcha. Many new programmers often think that is and == are the same thing. But it’s definitely not!Python3Python3# results in Trueprint(1 == True) # results in Falseprint(1 is True) Output:True\nFalse\nOn the other hand, is not and != are same.Python3Python3# results in Trueprint(1 != False) # results in Trueprint(1 is not False)Output:True\nTrue\n" }, { "code": null, "e": 33266, "s": 33258, "text": "Python3" }, { "code": "# results in Trueprint(1 == True) # results in Falseprint(1 is True) ", "e": 33337, "s": 33266, "text": null }, { "code": null, "e": 33345, "s": 33337, "text": "Output:" }, { "code": null, "e": 33357, "s": 33345, "text": "True\nFalse\n" }, { "code": null, "e": 33400, "s": 33357, "text": "On the other hand, is not and != are same." }, { "code": null, "e": 33408, "s": 33400, "text": "Python3" }, { "code": "# results in Trueprint(1 != False) # results in Trueprint(1 is not False)", "e": 33484, "s": 33408, "text": null }, { "code": null, "e": 33492, "s": 33484, "text": "Output:" }, { "code": null, "e": 33503, "s": 33492, "text": "True\nTrue\n" }, { "code": null, "e": 34360, "s": 33503, "text": "Default arguments gotcha :In Python, default arguments are declared only once when the function is run for the first time and from then on, the declared argument is used every time.Python3Python3def appendNew(appendTo =[]): appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())It’s expected that every time we call appendNew(), a new list will be created which will have 1 in it. But what happens is this:[1]\n[1, 1]\nThe variable appendTo isn’t created again when the function is run for the second time. Instead, it’s created only the first time and used again and again. We can tackle it by:Python3Python3def appendNew(appendTo = None): if appendTo == None: appendTo =[] appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())Output:[1]\n[1]\n" }, { "code": null, "e": 34516, "s": 34360, "text": "In Python, default arguments are declared only once when the function is run for the first time and from then on, the declared argument is used every time." }, { "code": null, "e": 34524, "s": 34516, "text": "Python3" }, { "code": "def appendNew(appendTo =[]): appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())", "e": 34660, "s": 34524, "text": null }, { "code": null, "e": 34789, "s": 34660, "text": "It’s expected that every time we call appendNew(), a new list will be created which will have 1 in it. But what happens is this:" }, { "code": null, "e": 34801, "s": 34789, "text": "[1]\n[1, 1]\n" }, { "code": null, "e": 34978, "s": 34801, "text": "The variable appendTo isn’t created again when the function is run for the second time. Instead, it’s created only the first time and used again and again. We can tackle it by:" }, { "code": null, "e": 34986, "s": 34978, "text": "Python3" }, { "code": "def appendNew(appendTo = None): if appendTo == None: appendTo =[] appendTo.append(1) return appendTo # Driver's codeprint(appendNew())print(appendNew())", "e": 35169, "s": 34986, "text": null }, { "code": null, "e": 35177, "s": 35169, "text": "Output:" }, { "code": null, "e": 35186, "s": 35177, "text": "[1]\n[1]\n" }, { "code": null, "e": 36168, "s": 35186, "text": "Scope gotchas :Sometimes, we must keep in mind the scope of the variable we are dealing with, i.e whether it is a global scope(works but inside and outside of a function) or a local scope(works just inside the function).Example:Python3Python3list1 = [1, 2, 3]def baz1(): # the code works fine list1.append(4) return list1def baz2(): # Doesn't work fine list1 += [5] return list1 # Driver's codeprint(baz1())print(baz2())Output:[1, 2, 3, 4]\nTraceback (most recent call last):\n File \"/home/ba0dfa25407638b061076b45ce165ce5.py\", line 15, in \n print(baz2())\n File \"/home/ba0dfa25407638b061076b45ce165ce5.py\", line 10, in baz2\n list1 += [5] \nUnboundLocalError: local variable 'list1' referenced before assignment\nThis happens becauselist1 += [5]means that we are assigning to the variable list1 but list1 is defined outside the scope of our function. While in baz1(), we are appending to list1 instead of assigning and hence it works fine." }, { "code": null, "e": 36374, "s": 36168, "text": "Sometimes, we must keep in mind the scope of the variable we are dealing with, i.e whether it is a global scope(works but inside and outside of a function) or a local scope(works just inside the function)." }, { "code": null, "e": 36383, "s": 36374, "text": "Example:" }, { "code": null, "e": 36391, "s": 36383, "text": "Python3" }, { "code": "list1 = [1, 2, 3]def baz1(): # the code works fine list1.append(4) return list1def baz2(): # Doesn't work fine list1 += [5] return list1 # Driver's codeprint(baz1())print(baz2())", "e": 36604, "s": 36391, "text": null }, { "code": null, "e": 36612, "s": 36604, "text": "Output:" }, { "code": null, "e": 36626, "s": 36612, "text": "[1, 2, 3, 4]\n" }, { "code": null, "e": 36908, "s": 36626, "text": "Traceback (most recent call last):\n File \"/home/ba0dfa25407638b061076b45ce165ce5.py\", line 15, in \n print(baz2())\n File \"/home/ba0dfa25407638b061076b45ce165ce5.py\", line 10, in baz2\n list1 += [5] \nUnboundLocalError: local variable 'list1' referenced before assignment\n" }, { "code": null, "e": 36929, "s": 36908, "text": "This happens because" }, { "code": null, "e": 36942, "s": 36929, "text": "list1 += [5]" }, { "code": null, "e": 37137, "s": 36942, "text": "means that we are assigning to the variable list1 but list1 is defined outside the scope of our function. While in baz1(), we are appending to list1 instead of assigning and hence it works fine." }, { "code": null, "e": 38005, "s": 37137, "text": "Variables are bound late in closures :Python has an infamous late binding behavior. By this, we mean that the value of a variable which is being iterated over is finalized to the value when it reaches its last iteration. Let’s look at an example:Python3Python3def create_multipliers(): # lambda function creates an iterable # list anonymously return [lambda c : i * c for i in range(6)] for multiplier in create_multipliers(): print multiplier(3)The expected result is of course:0\n3\n6\n9\n12\n15\nBut what we get is:15\n15\n15\n15\n15\n15\nThis is because when the loop iteration is complete, i has a value of 5 and hence 3*5 each time results in 15.It can be solved by:Python3Python3def create_multipliers(): return [lambda x, i = i : i * x for i in range(6)] for multiplier in create_multipliers(): print(multiplier(3))Output:0\n3\n6\n9\n12\n15\n" }, { "code": null, "e": 38214, "s": 38005, "text": "Python has an infamous late binding behavior. By this, we mean that the value of a variable which is being iterated over is finalized to the value when it reaches its last iteration. Let’s look at an example:" }, { "code": null, "e": 38222, "s": 38214, "text": "Python3" }, { "code": "def create_multipliers(): # lambda function creates an iterable # list anonymously return [lambda c : i * c for i in range(6)] for multiplier in create_multipliers(): print multiplier(3)", "e": 38427, "s": 38222, "text": null }, { "code": null, "e": 38461, "s": 38427, "text": "The expected result is of course:" }, { "code": null, "e": 38476, "s": 38461, "text": "0\n3\n6\n9\n12\n15\n" }, { "code": null, "e": 38496, "s": 38476, "text": "But what we get is:" }, { "code": null, "e": 38515, "s": 38496, "text": "15\n15\n15\n15\n15\n15\n" }, { "code": null, "e": 38646, "s": 38515, "text": "This is because when the loop iteration is complete, i has a value of 5 and hence 3*5 each time results in 15.It can be solved by:" }, { "code": null, "e": 38654, "s": 38646, "text": "Python3" }, { "code": "def create_multipliers(): return [lambda x, i = i : i * x for i in range(6)] for multiplier in create_multipliers(): print(multiplier(3))", "e": 38809, "s": 38654, "text": null }, { "code": null, "e": 38817, "s": 38809, "text": "Output:" }, { "code": null, "e": 38832, "s": 38817, "text": "0\n3\n6\n9\n12\n15\n" }, { "code": null, "e": 39833, "s": 38832, "text": "Mutating a list while iterating over it :This is the most common gotcha which new coders face almost all the time. While working with a list or other mutable items, if we mutate it while iterating over it, it’s certain to cause errors. It’s recommended that we create the copy of the list instead and mutate it rather than the original list.Python3Python3# buggy program to print a list # of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] for i in range(len(numbers)): if not even(numbers[i]): del numbers[i]Output:Traceback (most recent call last):\n File \"/home/92eed8bfd8c92fca3cf85f22e8cfd9ea.py\", line 9, in \n if not even(numbers[i]):\nIndexError: list index out of range\nBut if we use a copy of numbers instead:Python3Python3# working program to print a # list of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if even(n)]print(numbers) Output:[1, 3, 5, 7, 9]\n" }, { "code": null, "e": 40134, "s": 39833, "text": "This is the most common gotcha which new coders face almost all the time. While working with a list or other mutable items, if we mutate it while iterating over it, it’s certain to cause errors. It’s recommended that we create the copy of the list instead and mutate it rather than the original list." }, { "code": null, "e": 40142, "s": 40134, "text": "Python3" }, { "code": "# buggy program to print a list # of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] for i in range(len(numbers)): if not even(numbers[i]): del numbers[i]", "e": 40350, "s": 40142, "text": null }, { "code": null, "e": 40358, "s": 40350, "text": "Output:" }, { "code": null, "e": 40523, "s": 40358, "text": "Traceback (most recent call last):\n File \"/home/92eed8bfd8c92fca3cf85f22e8cfd9ea.py\", line 9, in \n if not even(numbers[i]):\nIndexError: list index out of range\n" }, { "code": null, "e": 40564, "s": 40523, "text": "But if we use a copy of numbers instead:" }, { "code": null, "e": 40572, "s": 40564, "text": "Python3" }, { "code": "# working program to print a # list of odd numbers from 1 to 10 even = lambda x : bool(x % 2)numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if even(n)]print(numbers) ", "e": 40763, "s": 40572, "text": null }, { "code": null, "e": 40771, "s": 40763, "text": "Output:" }, { "code": null, "e": 40788, "s": 40771, "text": "[1, 3, 5, 7, 9]\n" }, { "code": null, "e": 40808, "s": 40788, "text": "abhishek0719kadiyan" }, { "code": null, "e": 40823, "s": 40808, "text": "python-utility" }, { "code": null, "e": 40830, "s": 40823, "text": "Python" }, { "code": null, "e": 40928, "s": 40830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40960, "s": 40928, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 41002, "s": 40960, "text": "Check if element exists in list in Python" }, { "code": null, "e": 41044, "s": 41002, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 41071, "s": 41044, "text": "Python Classes and Objects" }, { "code": null, "e": 41127, "s": 41071, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 41149, "s": 41127, "text": "Defaultdict in Python" }, { "code": null, "e": 41188, "s": 41149, "text": "Python | Get unique values from a list" }, { "code": null, "e": 41219, "s": 41188, "text": "Python | os.path.join() method" }, { "code": null, "e": 41248, "s": 41219, "text": "Create a directory in Python" } ]
Leftmost Column with atleast one 1 in a row-wise sorted binary matrix - GeeksforGeeks
26 May, 2021 Given a binary matrix mat[][] containing 0’s and 1’s. Each row of the matrix is sorted in the non-decreasing order, the task is to find the left-most column of the matrix with at least one 1 in it.Note: If no such column exists return -1.Examples: Input: mat[2][2] = { {0, 0}, {1, 1} } Output: 1 Explanation: The 1st column of the matrix contains atleast a 1. Input: mat[2][2] = {{0, 0}, {0, 0}} Output: -1 Explanation: There is no such column which contains atleast one 1. Approach: The idea is to iterate over all the rows of the matrix and Binary Search over them for the first occurrence of the 1 in that row. The minimum of all the occurrence of the first 1 in the rows of the matrix will be the desired solution for the problem.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// Leftmost Column with atleast a// 1 in a sorted binary matrix #include <bits/stdc++.h> #define N 3using namespace std; // Function to search for the// leftmost column of the matrix// with atleast a 1 in sorted// binary matrixint search(int mat[][3], int n, int m){ int i, a = INT_MAX; // Loop to iterate over all the // rows of the matrix for (i = 0; i < n; i++) { int low = 0; int high = m - 1; int mid; int ans = INT_MAX; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = (low + high) / 2; // Condition if the column // contains the 1 at this // position of matrix if (mat[i][mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i][mid - 1] == 0) { ans = mid; break; } } if (mat[i][mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == INT_MAX) return -1; return a+1;} // Driver Codeint main(){ int mat[3][3] = { 0, 0, 0, 0, 0, 1, 0, 1, 1 }; cout << search(mat, 3, 3); return 0;} // Java implementation to find the// Leftmost Column with atleast a// 1 in a sorted binary matriximport java.util.*; class GFG{ static final int N = 3; // Function to search for the// leftmost column of the matrix// with atleast a 1 in sorted// binary matrixstatic int search(int mat[][], int n, int m){ int i, a = Integer.MAX_VALUE; // Loop to iterate over all the // rows of the matrix for(i = 0; i < n; i++) { int low = 0; int high = m - 1; int mid; int ans = Integer.MAX_VALUE; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = (low + high) / 2; // Condition if the column // contains the 1 at this // position of matrix if (mat[i][mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i][mid - 1] == 0) { ans = mid; break; } } if (mat[i][mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == Integer.MAX_VALUE) return -1; return a + 1;} // Driver Codepublic static void main(String[] args){ int mat[][] = { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 } }; System.out.print(search(mat, 3, 3));}} // This code is contributed by Amit Katiyar # Python3 implementation to find the# Leftmost Column with atleast a# 1 in a sorted binary matriximport sysN = 3 # Function to search for the# leftmost column of the matrix# with atleast a 1 in sorted# binary matrixdef search(mat, n, m): a = sys.maxsize # Loop to iterate over all the # rows of the matrix for i in range (n): low = 0 high = m - 1 ans = sys.maxsize # Binary Search to find the # leftmost occurence of the 1 while (low <= high): mid = (low + high) // 2 # Condition if the column # contains the 1 at this # position of matrix if (mat[i][mid] == 1): if (mid == 0): ans = 0 break elif (mat[i][mid - 1] == 0): ans = mid break if (mat[i][mid] == 1): high = mid - 1 else: low = mid + 1 # If there is a better solution # then update the answer if (ans < a): a = ans # Condition if the solution # doesn't exist in the matrix if (a == sys.maxsize): return -1 return a + 1 # Driver Codeif __name__ == "__main__": mat = [[0, 0, 0], [0, 0, 1], [0, 1, 1]] print(search(mat, 3, 3)) # This code is contributed by Chitranayal // C# implementation to find the leftmost // column with atleast a 1 in a sorted// binary matrixusing System; class GFG{ //static readonly int N = 3; // Function to search for the leftmost // column of the matrix with atleast a// 1 in sorted binary matrixstatic int search(int [,]mat, int n, int m){ int i, a = int.MaxValue; // Loop to iterate over all the // rows of the matrix for(i = 0; i < n; i++) { int low = 0; int high = m - 1; int mid; int ans = int.MaxValue; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = (low + high) / 2; // Condition if the column // contains the 1 at this // position of matrix if (mat[i, mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i, mid - 1] == 0) { ans = mid; break; } } if (mat[i, mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == int.MaxValue) return -1; return a + 1;} // Driver Codepublic static void Main(String[] args){ int [,]mat = { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 } }; Console.Write(search(mat, 3, 3));}} // This code is contributed by Amit Katiyar <script> // JavaScript implementation to find the// Leftmost Column with atleast a// 1 in a sorted binary matrix var N = 3; // Function to search for the// leftmost column of the matrix// with atleast a 1 in sorted// binary matrixfunction search(mat, n, m){ var i, a = 1000000000; // Loop to iterate over all the // rows of the matrix for (i = 0; i < n; i++) { var low = 0; var high = m - 1; var mid; var ans = 1000000000; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = parseInt((low + high) / 2); // Condition if the column // contains the 1 at this // position of matrix if (mat[i][mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i][mid - 1] == 0) { ans = mid; break; } } if (mat[i][mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == 1000000000) return -1; return a+1;} // Driver Codevar mat = [[0, 0, 0], [0, 0, 1], [0, 1, 1]];document.write( search(mat, 3, 3)); </script> 2 Performance Analysis: Time Complexity: O(N*logN) Auxiliary Space: O(1) amit143katiyar ukasp rrrtnx Binary Search Matrix Searching Sorting Searching Sorting Matrix Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Binary Search Linear Search Search an element in a sorted and rotated array Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 26821, "s": 26793, "text": "\n26 May, 2021" }, { "code": null, "e": 27069, "s": 26821, "text": "Given a binary matrix mat[][] containing 0’s and 1’s. Each row of the matrix is sorted in the non-decreasing order, the task is to find the left-most column of the matrix with at least one 1 in it.Note: If no such column exists return -1.Examples:" }, { "code": null, "e": 27327, "s": 27069, "text": "Input: \nmat[2][2] = { {0, 0},\n {1, 1} }\nOutput: 1\nExplanation: \nThe 1st column of the\nmatrix contains atleast a 1.\n\nInput: \nmat[2][2] = {{0, 0},\n {0, 0}}\nOutput: -1\nExplanation:\nThere is no such column which \ncontains atleast one 1." }, { "code": null, "e": 27639, "s": 27327, "text": "Approach: The idea is to iterate over all the rows of the matrix and Binary Search over them for the first occurrence of the 1 in that row. The minimum of all the occurrence of the first 1 in the rows of the matrix will be the desired solution for the problem.Below is the implementation of the above approach: " }, { "code": null, "e": 27643, "s": 27639, "text": "C++" }, { "code": null, "e": 27648, "s": 27643, "text": "Java" }, { "code": null, "e": 27656, "s": 27648, "text": "Python3" }, { "code": null, "e": 27659, "s": 27656, "text": "C#" }, { "code": null, "e": 27670, "s": 27659, "text": "Javascript" }, { "code": "// C++ implementation to find the// Leftmost Column with atleast a// 1 in a sorted binary matrix #include <bits/stdc++.h> #define N 3using namespace std; // Function to search for the// leftmost column of the matrix// with atleast a 1 in sorted// binary matrixint search(int mat[][3], int n, int m){ int i, a = INT_MAX; // Loop to iterate over all the // rows of the matrix for (i = 0; i < n; i++) { int low = 0; int high = m - 1; int mid; int ans = INT_MAX; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = (low + high) / 2; // Condition if the column // contains the 1 at this // position of matrix if (mat[i][mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i][mid - 1] == 0) { ans = mid; break; } } if (mat[i][mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == INT_MAX) return -1; return a+1;} // Driver Codeint main(){ int mat[3][3] = { 0, 0, 0, 0, 0, 1, 0, 1, 1 }; cout << search(mat, 3, 3); return 0;}", "e": 29257, "s": 27670, "text": null }, { "code": "// Java implementation to find the// Leftmost Column with atleast a// 1 in a sorted binary matriximport java.util.*; class GFG{ static final int N = 3; // Function to search for the// leftmost column of the matrix// with atleast a 1 in sorted// binary matrixstatic int search(int mat[][], int n, int m){ int i, a = Integer.MAX_VALUE; // Loop to iterate over all the // rows of the matrix for(i = 0; i < n; i++) { int low = 0; int high = m - 1; int mid; int ans = Integer.MAX_VALUE; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = (low + high) / 2; // Condition if the column // contains the 1 at this // position of matrix if (mat[i][mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i][mid - 1] == 0) { ans = mid; break; } } if (mat[i][mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == Integer.MAX_VALUE) return -1; return a + 1;} // Driver Codepublic static void main(String[] args){ int mat[][] = { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 } }; System.out.print(search(mat, 3, 3));}} // This code is contributed by Amit Katiyar", "e": 30984, "s": 29257, "text": null }, { "code": "# Python3 implementation to find the# Leftmost Column with atleast a# 1 in a sorted binary matriximport sysN = 3 # Function to search for the# leftmost column of the matrix# with atleast a 1 in sorted# binary matrixdef search(mat, n, m): a = sys.maxsize # Loop to iterate over all the # rows of the matrix for i in range (n): low = 0 high = m - 1 ans = sys.maxsize # Binary Search to find the # leftmost occurence of the 1 while (low <= high): mid = (low + high) // 2 # Condition if the column # contains the 1 at this # position of matrix if (mat[i][mid] == 1): if (mid == 0): ans = 0 break elif (mat[i][mid - 1] == 0): ans = mid break if (mat[i][mid] == 1): high = mid - 1 else: low = mid + 1 # If there is a better solution # then update the answer if (ans < a): a = ans # Condition if the solution # doesn't exist in the matrix if (a == sys.maxsize): return -1 return a + 1 # Driver Codeif __name__ == \"__main__\": mat = [[0, 0, 0], [0, 0, 1], [0, 1, 1]] print(search(mat, 3, 3)) # This code is contributed by Chitranayal", "e": 32434, "s": 30984, "text": null }, { "code": "// C# implementation to find the leftmost // column with atleast a 1 in a sorted// binary matrixusing System; class GFG{ //static readonly int N = 3; // Function to search for the leftmost // column of the matrix with atleast a// 1 in sorted binary matrixstatic int search(int [,]mat, int n, int m){ int i, a = int.MaxValue; // Loop to iterate over all the // rows of the matrix for(i = 0; i < n; i++) { int low = 0; int high = m - 1; int mid; int ans = int.MaxValue; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = (low + high) / 2; // Condition if the column // contains the 1 at this // position of matrix if (mat[i, mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i, mid - 1] == 0) { ans = mid; break; } } if (mat[i, mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == int.MaxValue) return -1; return a + 1;} // Driver Codepublic static void Main(String[] args){ int [,]mat = { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 } }; Console.Write(search(mat, 3, 3));}} // This code is contributed by Amit Katiyar", "e": 34137, "s": 32434, "text": null }, { "code": "<script> // JavaScript implementation to find the// Leftmost Column with atleast a// 1 in a sorted binary matrix var N = 3; // Function to search for the// leftmost column of the matrix// with atleast a 1 in sorted// binary matrixfunction search(mat, n, m){ var i, a = 1000000000; // Loop to iterate over all the // rows of the matrix for (i = 0; i < n; i++) { var low = 0; var high = m - 1; var mid; var ans = 1000000000; // Binary Search to find the // leftmost occurence of the 1 while (low <= high) { mid = parseInt((low + high) / 2); // Condition if the column // contains the 1 at this // position of matrix if (mat[i][mid] == 1) { if (mid == 0) { ans = 0; break; } else if (mat[i][mid - 1] == 0) { ans = mid; break; } } if (mat[i][mid] == 1) high = mid - 1; else low = mid + 1; } // If there is a better solution // then update the answer if (ans < a) a = ans; } // Condition if the solution // doesn't exist in the matrix if (a == 1000000000) return -1; return a+1;} // Driver Codevar mat = [[0, 0, 0], [0, 0, 1], [0, 1, 1]];document.write( search(mat, 3, 3)); </script>", "e": 35677, "s": 34137, "text": null }, { "code": null, "e": 35679, "s": 35677, "text": "2" }, { "code": null, "e": 35704, "s": 35681, "text": "Performance Analysis: " }, { "code": null, "e": 35731, "s": 35704, "text": "Time Complexity: O(N*logN)" }, { "code": null, "e": 35753, "s": 35731, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 35768, "s": 35753, "text": "amit143katiyar" }, { "code": null, "e": 35774, "s": 35768, "text": "ukasp" }, { "code": null, "e": 35781, "s": 35774, "text": "rrrtnx" }, { "code": null, "e": 35795, "s": 35781, "text": "Binary Search" }, { "code": null, "e": 35802, "s": 35795, "text": "Matrix" }, { "code": null, "e": 35812, "s": 35802, "text": "Searching" }, { "code": null, "e": 35820, "s": 35812, "text": "Sorting" }, { "code": null, "e": 35830, "s": 35820, "text": "Searching" }, { "code": null, "e": 35838, "s": 35830, "text": "Sorting" }, { "code": null, "e": 35845, "s": 35838, "text": "Matrix" }, { "code": null, "e": 35859, "s": 35845, "text": "Binary Search" }, { "code": null, "e": 35957, "s": 35859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35981, "s": 35957, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 36043, "s": 35981, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 36114, "s": 36043, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 36147, "s": 36114, "text": "Program to multiply two matrices" }, { "code": null, "e": 36198, "s": 36147, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 36212, "s": 36198, "text": "Binary Search" }, { "code": null, "e": 36226, "s": 36212, "text": "Linear Search" }, { "code": null, "e": 36274, "s": 36226, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 36298, "s": 36274, "text": "Find the Missing Number" } ]
C# Program For Removing Duplicates From A Sorted Linked List - GeeksforGeeks
14 Dec, 2021 Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. Algorithm: Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node Implementation: Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates(). C# // C# program to remove duplicates// from a sorted linked listusing System; public class LinkedList{ // Head of list Node head; // Linked list Node class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void removeDuplicates() { // Another reference to head Node current = head; /* Pointer to store the next pointer of a node to be deleted*/ Node next_next; // Do nothing if the list is empty if (head == null) return; // Traverse list till the last node while (current.next != null) { // Compare current node with the // next node if (current.data == current.next.data) { next_next = current.next.next; current.next = null; current.next = next_next; } // Advance if no deletion else current = current.next; } } // Utility functions // Inserts a new Node at front // of the list. public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to new Node head = new_node; } // Function to print linked list void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } // Driver code public static void Main(String []args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); Console.WriteLine( "List before removal of duplicates"); llist.printList(); llist.removeDuplicates(); Console.WriteLine( "List after removal of elements"); llist.printList(); }} // This code is contributed by 29AjayKumar Output: Linked list before duplicate removal 11 11 11 13 13 20 Linked list after duplicate removal 11 13 20 Time Complexity: O(n) where n is the number of nodes in the given linked list. Recursive Approach : C# // C# Program to remove duplicates// from a sorted linked list using System; class GFG{ // Link list node public class Node { public int data; public Node next; }; // The function removes duplicates // from a sorted list static Node removeDuplicates(Node head) { /* Pointer to store the pointer of a node to be deleted*/ Node to_free; // Do nothing if the list is empty if (head == null) return null; // Traverse the list till last node if (head.next != null) { // Compare head node with next node if (head.data == head.next.data) { /* The sequence of steps is important. to_free pointer stores the next of head pointer which is to be deleted.*/ to_free = head.next; head.next = head.next.next; removeDuplicates(head); } // This is tricky: only advance if no deletion else { removeDuplicates(head.next); } } return head; } // UTILITY FUNCTIONS /* Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = (head_ref); // Move the head to point to the // new node (head_ref) = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(" " + node.data); node = node.next; } } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; /* Let us create a sorted linked list to test the functions. Created linked list will be 11.11.11.13.13.20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); Console.Write("Linked list before" + " duplicate removal "); printList(head); // Remove duplicates from linked list head = removeDuplicates(head); Console.Write("Linked list after" + " duplicate removal "); printList(head); }}// This code is contributed by PrinciRaj1992 Output: Linked list before duplicate removal 11 11 11 13 13 20 Linked list after duplicate removal 11 13 20 Another Approach: Create a pointer that will point towards the first occurrence of every element and another pointer temp which will iterate to every element and when the value of the previous pointer is not equal to the temp pointer, we will set the pointer of the previous pointer to the first occurrence of another node. Below is the implementation of the above approach: C# // C# program to remove duplicates// from a sorted linked listusing System; class LinkedList{ // Head of list public Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to remove duplicates // from the given linked list void removeDuplicates() { // Two references to head temp // will iterate to the whole // Linked List prev will point // towards the first occurrence // of every element Node temp = head, prev = head; // Traverse list till the last node while (temp != null) { // Compare values of both pointers if(temp.data != prev.data) { /* if the value of prev is not equal to the value of temp that means there are no more occurrences of the prev data. So we can set the next of prev to the temp node.*/ prev.next = temp; prev = temp; } /*Set the temp to the next node*/ temp = temp.next; } /* This is the edge case if there are more than one occurrences of the last element */ if(prev != temp) { prev.next = null; } } // Utility functions // Inserts a new Node at front // of the list. public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to // new Node head = new_node; } // Function to print linked list void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } // Driver code public static void Main(string []args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); Console.Write("List before "); Console.WriteLine("removal of duplicates"); llist.printList(); llist.removeDuplicates(); Console.WriteLine( "List after removal of elements"); llist.printList(); }} // This code is contributed by rutvik_56 Output: List before removal of duplicates 11 11 11 13 13 20 List after removal of elements 11 13 20 Another Approach: Using Maps The idea is to push all the values in a map and printing its keys. Below is the implementation of the above approach: C# // C# program for the above approachusing System;using System.Collections.Generic; public class Node{ public int data; public Node next; public Node() { data = 0; next = null; }}public class GFG{ /* Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list off // the new node new_node.next = (head_ref); /* Move the head to point to the new node */ head_ref = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Function to remove duplicates static void removeDuplicates(Node head) { Dictionary<int, bool> track = new Dictionary<int, bool>(); Node temp = head; while(temp != null) { if(!track.ContainsKey(temp.data)) { Console.Write(temp.data + " "); track.Add(temp.data , true); } temp = temp.next; } } // Driver Code static public void Main () { Node head = null; /* Created linked list will be 11->11->11->13->13->20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); Console.Write( "Linked list before duplicate removal "); printList(head); Console.Write( "Linked list after duplicate removal "); removeDuplicates(head); }}// This code is contributed by rag2127 Output: Linked list before duplicate removal 11 11 11 13 13 20 Time Complexity: O(Number of Nodes) Space Complexity: O(Number of Nodes) Please refer complete article on Remove duplicates from a sorted linked list for more details! Adobe Linked Lists Myntra Oracle Visa C Programs C# Linked List Oracle Visa Adobe Myntra Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# Dictionary with examples C# | IsNullOrEmpty() Method
[ { "code": null, "e": 26253, "s": 26225, "text": "\n14 Dec, 2021" }, { "code": null, "e": 26535, "s": 26253, "text": "Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. " }, { "code": null, "e": 26811, "s": 26535, "text": "Algorithm: Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node " }, { "code": null, "e": 26930, "s": 26811, "text": "Implementation: Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates(). " }, { "code": null, "e": 26933, "s": 26930, "text": "C#" }, { "code": "// C# program to remove duplicates// from a sorted linked listusing System; public class LinkedList{ // Head of list Node head; // Linked list Node class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void removeDuplicates() { // Another reference to head Node current = head; /* Pointer to store the next pointer of a node to be deleted*/ Node next_next; // Do nothing if the list is empty if (head == null) return; // Traverse list till the last node while (current.next != null) { // Compare current node with the // next node if (current.data == current.next.data) { next_next = current.next.next; current.next = null; current.next = next_next; } // Advance if no deletion else current = current.next; } } // Utility functions // Inserts a new Node at front // of the list. public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to new Node head = new_node; } // Function to print linked list void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } // Driver code public static void Main(String []args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); Console.WriteLine( \"List before removal of duplicates\"); llist.printList(); llist.removeDuplicates(); Console.WriteLine( \"List after removal of elements\"); llist.printList(); }} // This code is contributed by 29AjayKumar ", "e": 29254, "s": 26933, "text": null }, { "code": null, "e": 29262, "s": 29254, "text": "Output:" }, { "code": null, "e": 29364, "s": 29262, "text": "Linked list before duplicate removal 11 11 11 13 13 20\nLinked list after duplicate removal 11 13 20" }, { "code": null, "e": 29443, "s": 29364, "text": "Time Complexity: O(n) where n is the number of nodes in the given linked list." }, { "code": null, "e": 29466, "s": 29443, "text": "Recursive Approach : " }, { "code": null, "e": 29469, "s": 29466, "text": "C#" }, { "code": "// C# Program to remove duplicates// from a sorted linked list using System; class GFG{ // Link list node public class Node { public int data; public Node next; }; // The function removes duplicates // from a sorted list static Node removeDuplicates(Node head) { /* Pointer to store the pointer of a node to be deleted*/ Node to_free; // Do nothing if the list is empty if (head == null) return null; // Traverse the list till last node if (head.next != null) { // Compare head node with next node if (head.data == head.next.data) { /* The sequence of steps is important. to_free pointer stores the next of head pointer which is to be deleted.*/ to_free = head.next; head.next = head.next.next; removeDuplicates(head); } // This is tricky: only advance if no deletion else { removeDuplicates(head.next); } } return head; } // UTILITY FUNCTIONS /* Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = (head_ref); // Move the head to point to the // new node (head_ref) = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(\" \" + node.data); node = node.next; } } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; /* Let us create a sorted linked list to test the functions. Created linked list will be 11.11.11.13.13.20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); Console.Write(\"Linked list before\" + \" duplicate removal \"); printList(head); // Remove duplicates from linked list head = removeDuplicates(head); Console.Write(\"Linked list after\" + \" duplicate removal \"); printList(head); }}// This code is contributed by PrinciRaj1992", "e": 32359, "s": 29469, "text": null }, { "code": null, "e": 32367, "s": 32359, "text": "Output:" }, { "code": null, "e": 32469, "s": 32367, "text": "Linked list before duplicate removal 11 11 11 13 13 20\nLinked list after duplicate removal 11 13 20" }, { "code": null, "e": 32793, "s": 32469, "text": "Another Approach: Create a pointer that will point towards the first occurrence of every element and another pointer temp which will iterate to every element and when the value of the previous pointer is not equal to the temp pointer, we will set the pointer of the previous pointer to the first occurrence of another node." }, { "code": null, "e": 32844, "s": 32793, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 32847, "s": 32844, "text": "C#" }, { "code": "// C# program to remove duplicates// from a sorted linked listusing System; class LinkedList{ // Head of list public Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to remove duplicates // from the given linked list void removeDuplicates() { // Two references to head temp // will iterate to the whole // Linked List prev will point // towards the first occurrence // of every element Node temp = head, prev = head; // Traverse list till the last node while (temp != null) { // Compare values of both pointers if(temp.data != prev.data) { /* if the value of prev is not equal to the value of temp that means there are no more occurrences of the prev data. So we can set the next of prev to the temp node.*/ prev.next = temp; prev = temp; } /*Set the temp to the next node*/ temp = temp.next; } /* This is the edge case if there are more than one occurrences of the last element */ if(prev != temp) { prev.next = null; } } // Utility functions // Inserts a new Node at front // of the list. public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to // new Node head = new_node; } // Function to print linked list void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } // Driver code public static void Main(string []args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); Console.Write(\"List before \"); Console.WriteLine(\"removal of duplicates\"); llist.printList(); llist.removeDuplicates(); Console.WriteLine( \"List after removal of elements\"); llist.printList(); }} // This code is contributed by rutvik_56", "e": 35594, "s": 32847, "text": null }, { "code": null, "e": 35602, "s": 35594, "text": "Output:" }, { "code": null, "e": 35696, "s": 35602, "text": "List before removal of duplicates\n11 11 11 13 13 20 \nList after removal of elements\n11 13 20 " }, { "code": null, "e": 35726, "s": 35696, "text": " Another Approach: Using Maps" }, { "code": null, "e": 35793, "s": 35726, "text": "The idea is to push all the values in a map and printing its keys." }, { "code": null, "e": 35844, "s": 35793, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35847, "s": 35844, "text": "C#" }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class Node{ public int data; public Node next; public Node() { data = 0; next = null; }}public class GFG{ /* Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list off // the new node new_node.next = (head_ref); /* Move the head to point to the new node */ head_ref = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Function to remove duplicates static void removeDuplicates(Node head) { Dictionary<int, bool> track = new Dictionary<int, bool>(); Node temp = head; while(temp != null) { if(!track.ContainsKey(temp.data)) { Console.Write(temp.data + \" \"); track.Add(temp.data , true); } temp = temp.next; } } // Driver Code static public void Main () { Node head = null; /* Created linked list will be 11->11->11->13->13->20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); Console.Write( \"Linked list before duplicate removal \"); printList(head); Console.Write( \"Linked list after duplicate removal \"); removeDuplicates(head); }}// This code is contributed by rag2127", "e": 37899, "s": 35847, "text": null }, { "code": null, "e": 37907, "s": 37899, "text": "Output:" }, { "code": null, "e": 37962, "s": 37907, "text": "Linked list before duplicate removal 11 11 11 13 13 20" }, { "code": null, "e": 37998, "s": 37962, "text": "Time Complexity: O(Number of Nodes)" }, { "code": null, "e": 38035, "s": 37998, "text": "Space Complexity: O(Number of Nodes)" }, { "code": null, "e": 38130, "s": 38035, "text": "Please refer complete article on Remove duplicates from a sorted linked list for more details!" }, { "code": null, "e": 38136, "s": 38130, "text": "Adobe" }, { "code": null, "e": 38149, "s": 38136, "text": "Linked Lists" }, { "code": null, "e": 38156, "s": 38149, "text": "Myntra" }, { "code": null, "e": 38163, "s": 38156, "text": "Oracle" }, { "code": null, "e": 38168, "s": 38163, "text": "Visa" }, { "code": null, "e": 38179, "s": 38168, "text": "C Programs" }, { "code": null, "e": 38182, "s": 38179, "text": "C#" }, { "code": null, "e": 38194, "s": 38182, "text": "Linked List" }, { "code": null, "e": 38201, "s": 38194, "text": "Oracle" }, { "code": null, "e": 38206, "s": 38201, "text": "Visa" }, { "code": null, "e": 38212, "s": 38206, "text": "Adobe" }, { "code": null, "e": 38219, "s": 38212, "text": "Myntra" }, { "code": null, "e": 38231, "s": 38219, "text": "Linked List" }, { "code": null, "e": 38329, "s": 38231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38370, "s": 38329, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 38401, "s": 38370, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 38435, "s": 38401, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 38476, "s": 38435, "text": "C program to find the length of a string" }, { "code": null, "e": 38547, "s": 38476, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 38601, "s": 38547, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 38643, "s": 38601, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 38705, "s": 38643, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 38733, "s": 38705, "text": "C# Dictionary with examples" } ]
PyQt5 QListWidget – Setting Vertical Scroll Bar - GeeksforGeeks
06 Aug, 2020 In this article we will see how we can set the vertical scroll bar of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Setting vertical scroll bar replaces the existing vertical scroll bar with scrollBar, and sets all the former scroll bar’s slider properties on the new scroll bar. The former scroll bar is then deleted. In order to do this we will use setVerticalScrollBar method with the list widget object. Syntax : list_widget.setVerticalScrollBar(scrollbar) Argument : It takes QScrollBar object as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 80) # list widget items item1 = QListWidgetItem("PyQt5 Geeks for Geeks") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") item4 = QListWidgetItem("D") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) list_widget.addItem(item4) # scroll bar scroll_bar = QScrollBar(self) # setting style sheet to the scroll bar scroll_bar.setStyleSheet("background : lightgreen;") # setting vertical scroll bar to it list_widget.setVerticalScrollBar(scroll_bar) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 25646, "s": 25618, "text": "\n06 Aug, 2020" }, { "code": null, "e": 26143, "s": 25646, "text": "In this article we will see how we can set the vertical scroll bar of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Setting vertical scroll bar replaces the existing vertical scroll bar with scrollBar, and sets all the former scroll bar’s slider properties on the new scroll bar. The former scroll bar is then deleted." }, { "code": null, "e": 26232, "s": 26143, "text": "In order to do this we will use setVerticalScrollBar method with the list widget object." }, { "code": null, "e": 26285, "s": 26232, "text": "Syntax : list_widget.setVerticalScrollBar(scrollbar)" }, { "code": null, "e": 26335, "s": 26285, "text": "Argument : It takes QScrollBar object as argument" }, { "code": null, "e": 26360, "s": 26335, "text": "Return : It returns None" }, { "code": null, "e": 26388, "s": 26360, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 80) # list widget items item1 = QListWidgetItem(\"PyQt5 Geeks for Geeks\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") item4 = QListWidgetItem(\"D\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) list_widget.addItem(item4) # scroll bar scroll_bar = QScrollBar(self) # setting style sheet to the scroll bar scroll_bar.setStyleSheet(\"background : lightgreen;\") # setting vertical scroll bar to it list_widget.setVerticalScrollBar(scroll_bar) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 28076, "s": 26388, "text": null }, { "code": null, "e": 28085, "s": 28076, "text": "Output :" }, { "code": null, "e": 28109, "s": 28085, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 28120, "s": 28109, "text": "Python-gui" }, { "code": null, "e": 28132, "s": 28120, "text": "Python-PyQt" }, { "code": null, "e": 28139, "s": 28132, "text": "Python" }, { "code": null, "e": 28237, "s": 28139, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28255, "s": 28237, "text": "Python Dictionary" }, { "code": null, "e": 28287, "s": 28255, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28322, "s": 28287, "text": "Read a file line by line in Python" }, { "code": null, "e": 28344, "s": 28322, "text": "Enumerate() in Python" }, { "code": null, "e": 28386, "s": 28344, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28416, "s": 28386, "text": "Iterate over a list in Python" }, { "code": null, "e": 28442, "s": 28416, "text": "Python String | replace()" }, { "code": null, "e": 28486, "s": 28442, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28515, "s": 28486, "text": "*args and **kwargs in Python" } ]
Lodash _.assignInWith() Method - GeeksforGeeks
18 Sep, 2020 The _.assignInWith() method of Object in lodash is similar to _.assignIn the method and the only difference is that it accepts customizer which is called in order to generate assigned value. Moreover, if the customizer used here returns undefined then the assignment is dealt with by the method instead. Note: The customizer used here can be called with five arguments namely objValue, srcValue, key, object, and source. The object used here is altered by this method. Syntax: _.assignInWith(object, sources, [customizer]) Parameters: This method accepts three parameters as described below: object: It is the destination object. sources: It is the source of objects. customizer: It is the function that customizes assigned values. Return Value: This method returns the object. Below examples illustrate the Lodash _.assignInWith() method in JavaScript: Example 1: Javascript // Requiring lodash libraryconst _ = require('lodash'); // Defining a function customizerfunction customizer(objectVal, sourceVal) { return _.isUndefined(objectVal) ? sourceVal : objectVal;} // Calling assignInWith method with its parameterlet obj = _.assignInWith({ 'gfg': 1 }, { 'geek': 3 }, customizer); // Displays output console.log(obj); Output: { gfg: 1, geek: 3 } Example 2: Javascript // Requiring lodash libraryconst _ = require('lodash'); // Defining a function customizerfunction customizer(objectVal, sourceVal) { return _.isUndefined(objectVal) ? sourceVal : objectVal;} // Defining a function GfGfunction GfG() { this.p = 7;} // Defining a function Portalfunction Portal() { this.r = 9;} // Defining prototype of above functions GfG.prototype.q = 8;Portal.prototype.s = 10; // Calling assignInWith method with its parameterlet obj = _.assignInWith({ 'p': 6 }, new GfG, new Portal,customizer); // Displays output console.log(obj); Output: { p: 6, q: 8, r: 9, s: 10 } Reference: https://lodash.com/docs/4.17.15#assignInWith JavaScript-Lodash 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 calculate the number of days between two dates in javascript? How to append HTML code to a div using JavaScript ? File uploading in React.js Hide or show elements in HTML using display property How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 38679, "s": 38651, "text": "\n18 Sep, 2020" }, { "code": null, "e": 38983, "s": 38679, "text": "The _.assignInWith() method of Object in lodash is similar to _.assignIn the method and the only difference is that it accepts customizer which is called in order to generate assigned value. Moreover, if the customizer used here returns undefined then the assignment is dealt with by the method instead." }, { "code": null, "e": 38990, "s": 38983, "text": "Note: " }, { "code": null, "e": 39101, "s": 38990, "text": "The customizer used here can be called with five arguments namely objValue, srcValue, key, object, and source." }, { "code": null, "e": 39149, "s": 39101, "text": "The object used here is altered by this method." }, { "code": null, "e": 39157, "s": 39149, "text": "Syntax:" }, { "code": null, "e": 39204, "s": 39157, "text": "_.assignInWith(object, sources, [customizer])\n" }, { "code": null, "e": 39273, "s": 39204, "text": "Parameters: This method accepts three parameters as described below:" }, { "code": null, "e": 39311, "s": 39273, "text": "object: It is the destination object." }, { "code": null, "e": 39349, "s": 39311, "text": "sources: It is the source of objects." }, { "code": null, "e": 39413, "s": 39349, "text": "customizer: It is the function that customizes assigned values." }, { "code": null, "e": 39459, "s": 39413, "text": "Return Value: This method returns the object." }, { "code": null, "e": 39535, "s": 39459, "text": "Below examples illustrate the Lodash _.assignInWith() method in JavaScript:" }, { "code": null, "e": 39546, "s": 39535, "text": "Example 1:" }, { "code": null, "e": 39557, "s": 39546, "text": "Javascript" }, { "code": "// Requiring lodash libraryconst _ = require('lodash'); // Defining a function customizerfunction customizer(objectVal, sourceVal) { return _.isUndefined(objectVal) ? sourceVal : objectVal;} // Calling assignInWith method with its parameterlet obj = _.assignInWith({ 'gfg': 1 }, { 'geek': 3 }, customizer); // Displays output console.log(obj);", "e": 39905, "s": 39557, "text": null }, { "code": null, "e": 39913, "s": 39905, "text": "Output:" }, { "code": null, "e": 39935, "s": 39913, "text": "{ gfg: 1, geek: 3 }\n\n" }, { "code": null, "e": 39946, "s": 39935, "text": "Example 2:" }, { "code": null, "e": 39957, "s": 39946, "text": "Javascript" }, { "code": "// Requiring lodash libraryconst _ = require('lodash'); // Defining a function customizerfunction customizer(objectVal, sourceVal) { return _.isUndefined(objectVal) ? sourceVal : objectVal;} // Defining a function GfGfunction GfG() { this.p = 7;} // Defining a function Portalfunction Portal() { this.r = 9;} // Defining prototype of above functions GfG.prototype.q = 8;Portal.prototype.s = 10; // Calling assignInWith method with its parameterlet obj = _.assignInWith({ 'p': 6 }, new GfG, new Portal,customizer); // Displays output console.log(obj);", "e": 40528, "s": 39957, "text": null }, { "code": null, "e": 40536, "s": 40528, "text": "Output:" }, { "code": null, "e": 40565, "s": 40536, "text": "{ p: 6, q: 8, r: 9, s: 10 }\n" }, { "code": null, "e": 40621, "s": 40565, "text": "Reference: https://lodash.com/docs/4.17.15#assignInWith" }, { "code": null, "e": 40639, "s": 40621, "text": "JavaScript-Lodash" }, { "code": null, "e": 40650, "s": 40639, "text": "JavaScript" }, { "code": null, "e": 40748, "s": 40650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40788, "s": 40748, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40833, "s": 40788, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40894, "s": 40833, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40966, "s": 40894, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41035, "s": 40966, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 41087, "s": 41035, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 41114, "s": 41087, "text": "File uploading in React.js" }, { "code": null, "e": 41167, "s": 41114, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 41213, "s": 41167, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Implementing Iterator pattern of a single Linked List - GeeksforGeeks
19 May, 2021 STL is one of the pillars of C++. It makes life a lot easier, especially when your focus is on problem-solving and you don’t want to spend time implementing something that is already available which guarantees a robust solution. One of the key aspects of Software Engineering is to avoid reinventing the wheel. Reusability is always preferred. While relying on library functions directly impacts our efficiency, without having a proper understanding of how it works sometimes loses the meaning of the engineering efficiency we keep on talking about. A wrongly chosen data structure may come back sometime in the future to haunt us. The solution is simple. Use library methods, but know how does it handle operations under the hood. Enough said! Today we will look at how we can implement our own Iterator pattern of a single Linked List. So, here is how an STL implementation of Linked List looks like: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int main(){ // creating a list vector<int> list; // elements to be added at the end. // in the above created list. list.push_back(1); list.push_back(2); list.push_back(3); // elements of list are retrieved through iterator. for (vector<int>::iterator it = list.begin(); it != list.end(); ++it) cout << *it << " "; return 0;} import java.util.*;class GFG{ public static void main(String[] args) { // creating a list ArrayList<Integer> list = new ArrayList<>(); // elements to be added at the end. // in the above created list. list.add(1); list.add(2); list.add(3); // elements of list are retrieved through iterator. Iterator<Integer> it = list.iterator(); while (it.hasNext()) { System.out.print(it.next() + " "); } }} // This code is contributed by pratham76 if __name__=='__main__': # Creating a list list = [] # Elements to be added at the end. # in the above created list. list.append(1) list.append(2) list.append(3) # Elements of list are retrieved # through iterator. for it in list: print(it, end = ' ') # This code is contributed by rutvik_56 using System;using System.Collections.Generic; public class GFG { public static void Main(String[] args) { // creating a list List<int> list = new List<int>(); // elements to be added at the end. // in the above created list. list.Add(1); list.Add(2); list.Add(3); // elements of list are retrieved through iterator. foreach (int it in list) { Console.Write(it + " "); } }} // This code contributed by umadevi9616 <script> // creating a list var list = []; // elements to be added at the end. // in the above created list. list.push(1); list.push(2); list.push(3); // elements of list are retrieved through iterator. for (var i = 0; i<list.length;i++) { document.write(list[i] + " "); } // This code contributed by umadevi9616 </script> Output 1 2 3 One of the beauties of cin and cout is that they don’t demand format specifiers to work with the type of data. This combined with templates makes the code much cleaner and readable. Although I prefer the naming method in C++ to start with caps, this implementation follows STL rules to mimic the exact set of method calls, viz push_back, begin, end. Here is our own implementation of LinkedList and its Iterator pattern: C++ // C++ program to implement Custom Linked List and// iterator pattern.#include <bits/stdc++.h>using namespace std; // Custom class to handle Linked List operations// Operations like push_back, push_front, pop_back,// pop_front, erase, size can be added heretemplate <typename T>class LinkedList{ // Forward declaration class Node; public: LinkedList<T>() noexcept { // caution: static members can't be // initialized by initializer list m_spRoot = nullptr; } // Forward declaration must be done // in the same access scope class Iterator; // Root of LinkedList wrapped in Iterator type Iterator begin() { return Iterator(m_spRoot); } // End of LInkedList wrapped in Iterator type Iterator end() { return Iterator(nullptr); } // Adds data to the end of list void push_back(T data); void Traverse(); // Iterator class can be used to // sequentially access nodes of linked list class Iterator { public: Iterator() noexcept : m_pCurrentNode (m_spRoot) { } Iterator(const Node* pNode) noexcept : m_pCurrentNode (pNode) { } Iterator& operator=(Node* pNode) { this->m_pCurrentNode = pNode; return *this; } // Prefix ++ overload Iterator& operator++() { if (m_pCurrentNode) m_pCurrentNode = m_pCurrentNode->pNext; return *this; } // Postfix ++ overload Iterator operator++(int) { Iterator iterator = *this; ++*this; return iterator; } bool operator!=(const Iterator& iterator) { return m_pCurrentNode != iterator.m_pCurrentNode; } int operator*() { return m_pCurrentNode->data; } private: const Node* m_pCurrentNode; }; private: class Node { T data; Node* pNext; // LinkedList class methods need // to access Node information friend class LinkedList; }; // Create a new Node Node* GetNode(T data) { Node* pNewNode = new Node; pNewNode->data = data; pNewNode->pNext = nullptr; return pNewNode; } // Return by reference so that it can be used in // left hand side of the assignment expression Node*& GetRootNode() { return m_spRoot; } static Node* m_spRoot;}; template <typename T>/*static*/ typename LinkedList<T>::Node* LinkedList<T>::m_spRoot = nullptr; template <typename T>void LinkedList<T>::push_back(T data){ Node* pTemp = GetNode(data); if (!GetRootNode()) { GetRootNode() = pTemp; } else { Node* pCrawler = GetRootNode(); while (pCrawler->pNext) { pCrawler = pCrawler->pNext; } pCrawler->pNext = pTemp; }} template <typename T>void LinkedList<T>::Traverse(){ Node* pCrawler = GetRootNode(); while (pCrawler) { cout << pCrawler->data << " "; pCrawler = pCrawler->pNext; } cout << endl;} //Driver programint main(){ LinkedList<int> list; // Add few items to the end of LinkedList list.push_back(1); list.push_back(2); list.push_back(3); cout << "Traversing LinkedList through method" << endl; list.Traverse(); cout << "Traversing LinkedList through Iterator" << endl; for ( LinkedList<int>::Iterator iterator = list.begin(); iterator != list.end(); iterator++) { cout << *iterator << " "; } cout << endl; return 0;} Output: Traversing LinkedList through method 1 2 3 Traversing LinkedList through Iterator 1 2 3 Exercise: The above implementation works well when we have one data. Extend this code to work for a set of data wrapped in a class. This article is contributed by Aashish Barnwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rutvik_56 pratham76 umadevi9616 STL C++ Design Pattern Linked List Linked List STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Virtual Function in C++ Operator Overloading in C++ Templates in C++ with Examples vector erase() and clear() in C++ Socket Programming in C/C++ SDE SHEET - A Complete Guide for SDE Preparation Design Patterns | Set 1 (Introduction) Singleton Design Pattern | Implementation Unified Modeling Language (UML) | Sequence Diagrams Factory method design pattern in Java
[ { "code": null, "e": 25823, "s": 25795, "text": "\n19 May, 2021" }, { "code": null, "e": 26167, "s": 25823, "text": "STL is one of the pillars of C++. It makes life a lot easier, especially when your focus is on problem-solving and you don’t want to spend time implementing something that is already available which guarantees a robust solution. One of the key aspects of Software Engineering is to avoid reinventing the wheel. Reusability is always preferred." }, { "code": null, "e": 26555, "s": 26167, "text": "While relying on library functions directly impacts our efficiency, without having a proper understanding of how it works sometimes loses the meaning of the engineering efficiency we keep on talking about. A wrongly chosen data structure may come back sometime in the future to haunt us. The solution is simple. Use library methods, but know how does it handle operations under the hood." }, { "code": null, "e": 26727, "s": 26555, "text": "Enough said! Today we will look at how we can implement our own Iterator pattern of a single Linked List. So, here is how an STL implementation of Linked List looks like: " }, { "code": null, "e": 26731, "s": 26727, "text": "C++" }, { "code": null, "e": 26736, "s": 26731, "text": "Java" }, { "code": null, "e": 26744, "s": 26736, "text": "Python3" }, { "code": null, "e": 26747, "s": 26744, "text": "C#" }, { "code": null, "e": 26758, "s": 26747, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ // creating a list vector<int> list; // elements to be added at the end. // in the above created list. list.push_back(1); list.push_back(2); list.push_back(3); // elements of list are retrieved through iterator. for (vector<int>::iterator it = list.begin(); it != list.end(); ++it) cout << *it << \" \"; return 0;}", "e": 27200, "s": 26758, "text": null }, { "code": "import java.util.*;class GFG{ public static void main(String[] args) { // creating a list ArrayList<Integer> list = new ArrayList<>(); // elements to be added at the end. // in the above created list. list.add(1); list.add(2); list.add(3); // elements of list are retrieved through iterator. Iterator<Integer> it = list.iterator(); while (it.hasNext()) { System.out.print(it.next() + \" \"); } }} // This code is contributed by pratham76", "e": 27751, "s": 27200, "text": null }, { "code": "if __name__=='__main__': # Creating a list list = [] # Elements to be added at the end. # in the above created list. list.append(1) list.append(2) list.append(3) # Elements of list are retrieved # through iterator. for it in list: print(it, end = ' ') # This code is contributed by rutvik_56", "e": 28097, "s": 27751, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG { public static void Main(String[] args) { // creating a list List<int> list = new List<int>(); // elements to be added at the end. // in the above created list. list.Add(1); list.Add(2); list.Add(3); // elements of list are retrieved through iterator. foreach (int it in list) { Console.Write(it + \" \"); } }} // This code contributed by umadevi9616", "e": 28612, "s": 28097, "text": null }, { "code": " <script> // creating a list var list = []; // elements to be added at the end. // in the above created list. list.push(1); list.push(2); list.push(3); // elements of list are retrieved through iterator. for (var i = 0; i<list.length;i++) { document.write(list[i] + \" \"); } // This code contributed by umadevi9616 </script>", "e": 29030, "s": 28612, "text": null }, { "code": null, "e": 29037, "s": 29030, "text": "Output" }, { "code": null, "e": 29043, "s": 29037, "text": "1 2 3" }, { "code": null, "e": 29393, "s": 29043, "text": "One of the beauties of cin and cout is that they don’t demand format specifiers to work with the type of data. This combined with templates makes the code much cleaner and readable. Although I prefer the naming method in C++ to start with caps, this implementation follows STL rules to mimic the exact set of method calls, viz push_back, begin, end." }, { "code": null, "e": 29466, "s": 29393, "text": "Here is our own implementation of LinkedList and its Iterator pattern: " }, { "code": null, "e": 29470, "s": 29466, "text": "C++" }, { "code": "// C++ program to implement Custom Linked List and// iterator pattern.#include <bits/stdc++.h>using namespace std; // Custom class to handle Linked List operations// Operations like push_back, push_front, pop_back,// pop_front, erase, size can be added heretemplate <typename T>class LinkedList{ // Forward declaration class Node; public: LinkedList<T>() noexcept { // caution: static members can't be // initialized by initializer list m_spRoot = nullptr; } // Forward declaration must be done // in the same access scope class Iterator; // Root of LinkedList wrapped in Iterator type Iterator begin() { return Iterator(m_spRoot); } // End of LInkedList wrapped in Iterator type Iterator end() { return Iterator(nullptr); } // Adds data to the end of list void push_back(T data); void Traverse(); // Iterator class can be used to // sequentially access nodes of linked list class Iterator { public: Iterator() noexcept : m_pCurrentNode (m_spRoot) { } Iterator(const Node* pNode) noexcept : m_pCurrentNode (pNode) { } Iterator& operator=(Node* pNode) { this->m_pCurrentNode = pNode; return *this; } // Prefix ++ overload Iterator& operator++() { if (m_pCurrentNode) m_pCurrentNode = m_pCurrentNode->pNext; return *this; } // Postfix ++ overload Iterator operator++(int) { Iterator iterator = *this; ++*this; return iterator; } bool operator!=(const Iterator& iterator) { return m_pCurrentNode != iterator.m_pCurrentNode; } int operator*() { return m_pCurrentNode->data; } private: const Node* m_pCurrentNode; }; private: class Node { T data; Node* pNext; // LinkedList class methods need // to access Node information friend class LinkedList; }; // Create a new Node Node* GetNode(T data) { Node* pNewNode = new Node; pNewNode->data = data; pNewNode->pNext = nullptr; return pNewNode; } // Return by reference so that it can be used in // left hand side of the assignment expression Node*& GetRootNode() { return m_spRoot; } static Node* m_spRoot;}; template <typename T>/*static*/ typename LinkedList<T>::Node* LinkedList<T>::m_spRoot = nullptr; template <typename T>void LinkedList<T>::push_back(T data){ Node* pTemp = GetNode(data); if (!GetRootNode()) { GetRootNode() = pTemp; } else { Node* pCrawler = GetRootNode(); while (pCrawler->pNext) { pCrawler = pCrawler->pNext; } pCrawler->pNext = pTemp; }} template <typename T>void LinkedList<T>::Traverse(){ Node* pCrawler = GetRootNode(); while (pCrawler) { cout << pCrawler->data << \" \"; pCrawler = pCrawler->pNext; } cout << endl;} //Driver programint main(){ LinkedList<int> list; // Add few items to the end of LinkedList list.push_back(1); list.push_back(2); list.push_back(3); cout << \"Traversing LinkedList through method\" << endl; list.Traverse(); cout << \"Traversing LinkedList through Iterator\" << endl; for ( LinkedList<int>::Iterator iterator = list.begin(); iterator != list.end(); iterator++) { cout << *iterator << \" \"; } cout << endl; return 0;}", "e": 33053, "s": 29470, "text": null }, { "code": null, "e": 33062, "s": 33053, "text": "Output: " }, { "code": null, "e": 33151, "s": 33062, "text": "Traversing LinkedList through method\n1 2 3 \nTraversing LinkedList through Iterator\n1 2 3" }, { "code": null, "e": 33283, "s": 33151, "text": "Exercise: The above implementation works well when we have one data. Extend this code to work for a set of data wrapped in a class." }, { "code": null, "e": 33706, "s": 33283, "text": "This article is contributed by Aashish Barnwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33716, "s": 33706, "text": "rutvik_56" }, { "code": null, "e": 33726, "s": 33716, "text": "pratham76" }, { "code": null, "e": 33738, "s": 33726, "text": "umadevi9616" }, { "code": null, "e": 33742, "s": 33738, "text": "STL" }, { "code": null, "e": 33746, "s": 33742, "text": "C++" }, { "code": null, "e": 33761, "s": 33746, "text": "Design Pattern" }, { "code": null, "e": 33773, "s": 33761, "text": "Linked List" }, { "code": null, "e": 33785, "s": 33773, "text": "Linked List" }, { "code": null, "e": 33789, "s": 33785, "text": "STL" }, { "code": null, "e": 33793, "s": 33789, "text": "CPP" }, { "code": null, "e": 33891, "s": 33793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33915, "s": 33891, "text": "Virtual Function in C++" }, { "code": null, "e": 33943, "s": 33915, "text": "Operator Overloading in C++" }, { "code": null, "e": 33974, "s": 33943, "text": "Templates in C++ with Examples" }, { "code": null, "e": 34008, "s": 33974, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 34036, "s": 34008, "text": "Socket Programming in C/C++" }, { "code": null, "e": 34085, "s": 34036, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 34124, "s": 34085, "text": "Design Patterns | Set 1 (Introduction)" }, { "code": null, "e": 34166, "s": 34124, "text": "Singleton Design Pattern | Implementation" }, { "code": null, "e": 34218, "s": 34166, "text": "Unified Modeling Language (UML) | Sequence Diagrams" } ]
Program to convert List of Integer to List of String in Java - GeeksforGeeks
11 Dec, 2018 The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes. Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the List of Integer.Convert List of Integer to Stream of Integer. This is done using List.stream().Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression.Collect Stream of String into List of String. This is done using Collectors.toList().Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Using Guava’s List.transform():Algorithm:Get the List of Integer.Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation.Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] My Personal Notes arrow_drop_upSave Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the List of Integer.Convert List of Integer to Stream of Integer. This is done using List.stream().Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression.Collect Stream of String into List of String. This is done using Collectors.toList().Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Java 8 Stream API can be used to convert List to List. Algorithm: Get the List of Integer.Convert List of Integer to Stream of Integer. This is done using List.stream().Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression.Collect Stream of String into List of String. This is done using Collectors.toList().Return/Print the List of String. Get the List of Integer. Convert List of Integer to Stream of Integer. This is done using List.stream(). Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression. Collect Stream of String into List of String. This is done using Collectors.toList(). Return/Print the List of String. Program: // Java Program to convert// List<Integer> to List<String> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); }} List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Using Guava’s List.transform():Algorithm:Get the List of Integer.Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation.Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] My Personal Notes arrow_drop_upSave Algorithm: Get the List of Integer.Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation.Return/Print the List of String. Get the List of Integer. Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation. Return/Print the List of String. Program: // Java Program to convert// List<Integer> to List<String> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); }} List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Java - util package java-list Java-List-Programs java-stream Java-Stream-programs Java-String-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25867, "s": 25839, "text": "\n11 Dec, 2018" }, { "code": null, "e": 26181, "s": 25867, "text": "The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes." }, { "code": null, "e": 29257, "s": 26181, "text": "Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the List of Integer.Convert List of Integer to Stream of Integer. This is done using List.stream().Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression.Collect Stream of String into List of String. This is done using Collectors.toList().Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println(\"List of Integer: \" + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println(\"List of String: \" + listOfString); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\nUsing Guava’s List.transform():Algorithm:Get the List of Integer.Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation.Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println(\"List of Integer: \" + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println(\"List of String: \" + listOfString); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30931, "s": 29257, "text": "Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the List of Integer.Convert List of Integer to Stream of Integer. This is done using List.stream().Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression.Collect Stream of String into List of String. This is done using Collectors.toList().Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println(\"List of Integer: \" + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println(\"List of String: \" + listOfString); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 30986, "s": 30931, "text": "Java 8 Stream API can be used to convert List to List." }, { "code": null, "e": 30997, "s": 30986, "text": "Algorithm:" }, { "code": null, "e": 31360, "s": 30997, "text": "Get the List of Integer.Convert List of Integer to Stream of Integer. This is done using List.stream().Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression.Collect Stream of String into List of String. This is done using Collectors.toList().Return/Print the List of String." }, { "code": null, "e": 31385, "s": 31360, "text": "Get the List of Integer." }, { "code": null, "e": 31465, "s": 31385, "text": "Convert List of Integer to Stream of Integer. This is done using List.stream()." }, { "code": null, "e": 31608, "s": 31465, "text": "Convert Stream of Integer to Stream of String. This is done using Stream.map() and passing s -> String.valueOf(s) method as lambda expression." }, { "code": null, "e": 31694, "s": 31608, "text": "Collect Stream of String into List of String. This is done using Collectors.toList()." }, { "code": null, "e": 31727, "s": 31694, "text": "Return/Print the List of String." }, { "code": null, "e": 31736, "s": 31727, "text": "Program:" }, { "code": "// Java Program to convert// List<Integer> to List<String> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println(\"List of Integer: \" + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println(\"List of String: \" + listOfString); }}", "e": 32762, "s": 31736, "text": null }, { "code": null, "e": 32828, "s": 32762, "text": "List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 34231, "s": 32828, "text": "Using Guava’s List.transform():Algorithm:Get the List of Integer.Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation.Return/Print the List of String.Program:// Java Program to convert// List<Integer> to List<String> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println(\"List of Integer: \" + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println(\"List of String: \" + listOfString); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34242, "s": 34231, "text": "Algorithm:" }, { "code": null, "e": 34463, "s": 34242, "text": "Get the List of Integer.Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation.Return/Print the List of String." }, { "code": null, "e": 34488, "s": 34463, "text": "Get the List of Integer." }, { "code": null, "e": 34653, "s": 34488, "text": "Convert List of Integer to List of String using Lists.transform(). This is done using passing s -> String.valueOf(s) method as lambda expression for transformation." }, { "code": null, "e": 34686, "s": 34653, "text": "Return/Print the List of String." }, { "code": null, "e": 34695, "s": 34686, "text": "Program:" }, { "code": "// Java Program to convert// List<Integer> to List<String> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List<U> convertIntListToStringList(List<T> listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List<Integer> listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println(\"List of Integer: \" + listOfInteger); // Convert List of Integer to List of String List<String> listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println(\"List of String: \" + listOfString); }}", "e": 35722, "s": 34695, "text": null }, { "code": null, "e": 35788, "s": 35722, "text": "List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 35808, "s": 35788, "text": "Java - util package" }, { "code": null, "e": 35818, "s": 35808, "text": "java-list" }, { "code": null, "e": 35837, "s": 35818, "text": "Java-List-Programs" }, { "code": null, "e": 35849, "s": 35837, "text": "java-stream" }, { "code": null, "e": 35870, "s": 35849, "text": "Java-Stream-programs" }, { "code": null, "e": 35891, "s": 35870, "text": "Java-String-Programs" }, { "code": null, "e": 35896, "s": 35891, "text": "Java" }, { "code": null, "e": 35910, "s": 35896, "text": "Java Programs" }, { "code": null, "e": 35915, "s": 35910, "text": "Java" }, { "code": null, "e": 36013, "s": 35915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36028, "s": 36013, "text": "Stream In Java" }, { "code": null, "e": 36047, "s": 36028, "text": "Interfaces in Java" }, { "code": null, "e": 36065, "s": 36047, "text": "ArrayList in Java" }, { "code": null, "e": 36097, "s": 36065, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36117, "s": 36097, "text": "Stack Class in Java" }, { "code": null, "e": 36145, "s": 36117, "text": "Initializing a List in Java" }, { "code": null, "e": 36189, "s": 36145, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 36215, "s": 36189, "text": "Java Programming Examples" }, { "code": null, "e": 36249, "s": 36215, "text": "Convert Double to Integer in Java" } ]
HTML
HTML stands for Hyper Text Markup Language. It is a formatting language used to define the appearance and contents of a web page. It allows us to organize text, graphics, audio, and video on a web page. Key Points: The word Hypertext refers to the text which acts as a link. The word Hypertext refers to the text which acts as a link. The word markup refers to the symbols that are used to define structure of the text. The markup symbols tells the browser how to display the text and are often called tags. The word markup refers to the symbols that are used to define structure of the text. The markup symbols tells the browser how to display the text and are often called tags. The word Language refers to the syntax that is similar to any other language. The word Language refers to the syntax that is similar to any other language. The following table shows the various versions of HTML: Tag is a command that tells the web browser how to display the text, audio, graphics or video on a web page. Key Points: Tags are indicated with pair of angle brackets. Tags are indicated with pair of angle brackets. They start with a less than (<) character and end with a greater than (>) character. They start with a less than (<) character and end with a greater than (>) character. The tag name is specified between the angle brackets. The tag name is specified between the angle brackets. Most of the tags usually occur in pair: the start tag and the closing tag. Most of the tags usually occur in pair: the start tag and the closing tag. The start tag is simply the tag name is enclosed in angle bracket whereas the closing tag is specified including a forward slash (/). The start tag is simply the tag name is enclosed in angle bracket whereas the closing tag is specified including a forward slash (/). Some tags are the empty i.e. they don’t have the closing tag. Some tags are the empty i.e. they don’t have the closing tag. Tags are not case sensitive. Tags are not case sensitive. The starting and closing tag name must be the same. For example <b> hello </i> is invalid as both are different. The starting and closing tag name must be the same. For example <b> hello </i> is invalid as both are different. If you don’t specify the angle brackets (<>) for a tag, the browser will treat the tag name as a simple text. If you don’t specify the angle brackets (<>) for a tag, the browser will treat the tag name as a simple text. The tag can also have attributes to provide additional information about the tag to the browser. The tag can also have attributes to provide additional information about the tag to the browser. The following table shows the Basic HTML tags that define the basic web page: The following code shows how to use basic tags. <html> <head> Heading goes here...</head> <title> Title goes here...</title> <body> Body goes here...</body> </html> The following table shows the HTML tags used for formatting the text: Following table describe the commonaly used table tags: Following table describe the commonaly used list tags: Frames help us to divide the browser’s window into multiple rectangular regions. Each region contains separate html web page and each of them work independently. The following table describes the various tags used for creating frames: Forms are used to input the values. These values are sent to the server for processing. Forms uses input elements such as text fields, check boxes, radio buttons, lists, submit buttons etc. to enter the data into it. The following table describes the commonly used tags while creating a form: 61 Lectures 8 hours Amit Rana 13 Lectures 2.5 hours Raghu Pandey 5 Lectures 38 mins Harshit Srivastava 62 Lectures 3.5 hours YouAccel 9 Lectures 36 mins Korey Sheppard 10 Lectures 57 mins Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2676, "s": 2473, "text": "HTML stands for Hyper Text Markup Language. It is a formatting language used to define the appearance and contents of a web page. It allows us to organize text, graphics, audio, and video on a web page." }, { "code": null, "e": 2689, "s": 2676, "text": "Key Points:\n" }, { "code": null, "e": 2749, "s": 2689, "text": "The word Hypertext refers to the text which acts as a link." }, { "code": null, "e": 2809, "s": 2749, "text": "The word Hypertext refers to the text which acts as a link." }, { "code": null, "e": 2982, "s": 2809, "text": "The word markup refers to the symbols that are used to define structure of the text. The markup symbols tells the browser how to display the text and are often called tags." }, { "code": null, "e": 3155, "s": 2982, "text": "The word markup refers to the symbols that are used to define structure of the text. The markup symbols tells the browser how to display the text and are often called tags." }, { "code": null, "e": 3233, "s": 3155, "text": "The word Language refers to the syntax that is similar to any other language." }, { "code": null, "e": 3311, "s": 3233, "text": "The word Language refers to the syntax that is similar to any other language." }, { "code": null, "e": 3367, "s": 3311, "text": "The following table shows the various versions of HTML:" }, { "code": null, "e": 3476, "s": 3367, "text": "Tag is a command that tells the web browser how to display the text, audio, graphics or video on a web page." }, { "code": null, "e": 3489, "s": 3476, "text": "Key Points:\n" }, { "code": null, "e": 3537, "s": 3489, "text": "Tags are indicated with pair of angle brackets." }, { "code": null, "e": 3585, "s": 3537, "text": "Tags are indicated with pair of angle brackets." }, { "code": null, "e": 3670, "s": 3585, "text": "They start with a less than (<) character and end with a greater than (>) character." }, { "code": null, "e": 3755, "s": 3670, "text": "They start with a less than (<) character and end with a greater than (>) character." }, { "code": null, "e": 3809, "s": 3755, "text": "The tag name is specified between the angle brackets." }, { "code": null, "e": 3863, "s": 3809, "text": "The tag name is specified between the angle brackets." }, { "code": null, "e": 3938, "s": 3863, "text": "Most of the tags usually occur in pair: the start tag and the closing tag." }, { "code": null, "e": 4013, "s": 3938, "text": "Most of the tags usually occur in pair: the start tag and the closing tag." }, { "code": null, "e": 4147, "s": 4013, "text": "The start tag is simply the tag name is enclosed in angle bracket whereas the closing tag is specified including a forward slash (/)." }, { "code": null, "e": 4281, "s": 4147, "text": "The start tag is simply the tag name is enclosed in angle bracket whereas the closing tag is specified including a forward slash (/)." }, { "code": null, "e": 4343, "s": 4281, "text": "Some tags are the empty i.e. they don’t have the closing tag." }, { "code": null, "e": 4405, "s": 4343, "text": "Some tags are the empty i.e. they don’t have the closing tag." }, { "code": null, "e": 4434, "s": 4405, "text": "Tags are not case sensitive." }, { "code": null, "e": 4463, "s": 4434, "text": "Tags are not case sensitive." }, { "code": null, "e": 4577, "s": 4463, "text": "The starting and closing tag name must be the same. For example <b> hello </i> is invalid as both are different." }, { "code": null, "e": 4691, "s": 4577, "text": "The starting and closing tag name must be the same. For example <b> hello </i> is invalid as both are different." }, { "code": null, "e": 4801, "s": 4691, "text": "If you don’t specify the angle brackets (<>) for a tag, the browser will treat the tag name as a simple text." }, { "code": null, "e": 4911, "s": 4801, "text": "If you don’t specify the angle brackets (<>) for a tag, the browser will treat the tag name as a simple text." }, { "code": null, "e": 5008, "s": 4911, "text": "The tag can also have attributes to provide additional information about the tag to the browser." }, { "code": null, "e": 5105, "s": 5008, "text": "The tag can also have attributes to provide additional information about the tag to the browser." }, { "code": null, "e": 5183, "s": 5105, "text": "The following table shows the Basic HTML tags that define the basic web page:" }, { "code": null, "e": 5231, "s": 5183, "text": "The following code shows how to use basic tags." }, { "code": null, "e": 5357, "s": 5231, "text": "<html>\n <head> Heading goes here...</head>\n <title> Title goes here...</title>\n <body> Body goes here...</body>\n</html>" }, { "code": null, "e": 5427, "s": 5357, "text": "The following table shows the HTML tags used for formatting the text:" }, { "code": null, "e": 5483, "s": 5427, "text": "Following table describe the commonaly used table tags:" }, { "code": null, "e": 5538, "s": 5483, "text": "Following table describe the commonaly used list tags:" }, { "code": null, "e": 5700, "s": 5538, "text": "Frames help us to divide the browser’s window into multiple rectangular regions. Each region contains separate html web page and each of them work independently." }, { "code": null, "e": 5773, "s": 5700, "text": "The following table describes the various tags used for creating frames:" }, { "code": null, "e": 5990, "s": 5773, "text": "Forms are used to input the values. These values are sent to the server for processing. Forms uses input elements such as text fields, check boxes, radio buttons, lists, submit buttons etc. to enter the data into it." }, { "code": null, "e": 6066, "s": 5990, "text": "The following table describes the commonly used tags while creating a form:" }, { "code": null, "e": 6099, "s": 6066, "text": "\n 61 Lectures \n 8 hours \n" }, { "code": null, "e": 6110, "s": 6099, "text": " Amit Rana" }, { "code": null, "e": 6145, "s": 6110, "text": "\n 13 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6159, "s": 6145, "text": " Raghu Pandey" }, { "code": null, "e": 6190, "s": 6159, "text": "\n 5 Lectures \n 38 mins\n" }, { "code": null, "e": 6210, "s": 6190, "text": " Harshit Srivastava" }, { "code": null, "e": 6245, "s": 6210, "text": "\n 62 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6255, "s": 6245, "text": " YouAccel" }, { "code": null, "e": 6286, "s": 6255, "text": "\n 9 Lectures \n 36 mins\n" }, { "code": null, "e": 6302, "s": 6286, "text": " Korey Sheppard" }, { "code": null, "e": 6334, "s": 6302, "text": "\n 10 Lectures \n 57 mins\n" }, { "code": null, "e": 6357, "s": 6334, "text": " Taurius Litvinavicius" }, { "code": null, "e": 6364, "s": 6357, "text": " Print" }, { "code": null, "e": 6375, "s": 6364, "text": " Add Notes" } ]
Deploying scikit-learn Models at Scale | by Yufeng G | Towards Data Science
Scikit-learn is great for putting together a quick model to test out your dataset. But what if you want to run it against incoming live data? Find out how to serve your scikit-learn model in an auto-scaling, serverless environment! Today, we’ll take a trained scikit-learn model and deploy it on Cloud ML Engine. Use this post to set up your own deployment pipeline, and you’ll never need to worry about how to deploy and scale your models again! towardsdatascience.com Say you have a model you’ve trained up using a scikit-learn model, and now you want to set up a prediction server. Let’s see how to do this based on our code we had in a previous episode about zoo animals. To export the model, we’ll use the joblib library from sklearn.externals. from sklearn.externals import joblibjoblib.dump(clf, 'model.joblib') We can use joblib.dump() to export the model to a file. We’ll call ours model.joblib. Once we commit and run this kernel, we’ll be able to retrieve the output from the kernel: With our trained scikit-learn model in hand, we are ready to head over to Google Cloud ML Engine to load up the model to serve predictions. That’s right, we can get all the auto-scaling, secured REST API goodness for not only TensorFlow, but also for scikit-learn (and XGBoost)! This enables you to easily transition back and forth between scikit-learn and TensorFlow. The first step to getting our model in the cloud is to upload the model.joblib file to Google Cloud Storage. Organization tip: It is required that the name of the file be literally “model.joblib”, so you’ll probably want to stick the file inside a folder with a name you’ll remember. Otherwise, later on when you create more models , they’ll all be the same name of model.joblib! Let’s create our model and version, specifying that we are loading up a scikit-learn model, and select the runtime version of Cloud ML engine, as well as the version of Python that we used to export this model. Since we were running our training on Kaggle, that’s Python 3. Give it a bit of time to setup.... And that’s basically it! We now have a scikit-learn model serving in the cloud! Now of course, a scalable model is no use without being able to call those predictions. Let’s take a look at how simple that is. I’ve gone ahead and pulled one sample row from our data, whose answer should be category “4”. We’ll present the data to Cloud ML Engine as a simple array, encoded as a json file. print(list(X_test.iloc[10:11].values)) Here I’m taking the test features dataframe and extracting row 10 row from it, and then calling .values to get the underlying numpy array. Unfortunately, numpy arrays don’t print with commas between their values, and we really want the commas, so I’ve turned the numpy array into a Python list and printed that out. (Yes, you could, and probably should really just use the json library and encode it properly rather than relying on print behavior!) I’ve saved the array to an input file, and now we can call the prediction REST API for our scikit-learn model. gcloud has a built-in utility to do this. We are expecting a response of 4, which is indeed what we get back! Huzzah! You can follow the steps in this video to deploy your scikit-learn model to production, or step it up by turning it into automated pipeline so that each time you make a new model, it gets deployed out so you can test it! Head on over to Cloud ML Engine and upload your scikit-learn model to get auto-scaling predictions at your fingertips! For a more detailed treatment on this topic, the documentation has some great guides: https://cloud.google.com/ml-engine/docs/scikit/quickstart Thanks for reading this episode of Cloud AI Adventures. If you’re enjoying the series, please let me know by clapping for the article. If you want more machine learning action, be sure to follow me on Medium or subscribe to the YouTube channel to catch future episodes as they come out. More episodes coming at you soon!
[ { "code": null, "e": 403, "s": 171, "text": "Scikit-learn is great for putting together a quick model to test out your dataset. But what if you want to run it against incoming live data? Find out how to serve your scikit-learn model in an auto-scaling, serverless environment!" }, { "code": null, "e": 618, "s": 403, "text": "Today, we’ll take a trained scikit-learn model and deploy it on Cloud ML Engine. Use this post to set up your own deployment pipeline, and you’ll never need to worry about how to deploy and scale your models again!" }, { "code": null, "e": 641, "s": 618, "text": "towardsdatascience.com" }, { "code": null, "e": 847, "s": 641, "text": "Say you have a model you’ve trained up using a scikit-learn model, and now you want to set up a prediction server. Let’s see how to do this based on our code we had in a previous episode about zoo animals." }, { "code": null, "e": 921, "s": 847, "text": "To export the model, we’ll use the joblib library from sklearn.externals." }, { "code": null, "e": 990, "s": 921, "text": "from sklearn.externals import joblibjoblib.dump(clf, 'model.joblib')" }, { "code": null, "e": 1076, "s": 990, "text": "We can use joblib.dump() to export the model to a file. We’ll call ours model.joblib." }, { "code": null, "e": 1166, "s": 1076, "text": "Once we commit and run this kernel, we’ll be able to retrieve the output from the kernel:" }, { "code": null, "e": 1306, "s": 1166, "text": "With our trained scikit-learn model in hand, we are ready to head over to Google Cloud ML Engine to load up the model to serve predictions." }, { "code": null, "e": 1535, "s": 1306, "text": "That’s right, we can get all the auto-scaling, secured REST API goodness for not only TensorFlow, but also for scikit-learn (and XGBoost)! This enables you to easily transition back and forth between scikit-learn and TensorFlow." }, { "code": null, "e": 1644, "s": 1535, "text": "The first step to getting our model in the cloud is to upload the model.joblib file to Google Cloud Storage." }, { "code": null, "e": 1915, "s": 1644, "text": "Organization tip: It is required that the name of the file be literally “model.joblib”, so you’ll probably want to stick the file inside a folder with a name you’ll remember. Otherwise, later on when you create more models , they’ll all be the same name of model.joblib!" }, { "code": null, "e": 2189, "s": 1915, "text": "Let’s create our model and version, specifying that we are loading up a scikit-learn model, and select the runtime version of Cloud ML engine, as well as the version of Python that we used to export this model. Since we were running our training on Kaggle, that’s Python 3." }, { "code": null, "e": 2304, "s": 2189, "text": "Give it a bit of time to setup.... And that’s basically it! We now have a scikit-learn model serving in the cloud!" }, { "code": null, "e": 2612, "s": 2304, "text": "Now of course, a scalable model is no use without being able to call those predictions. Let’s take a look at how simple that is. I’ve gone ahead and pulled one sample row from our data, whose answer should be category “4”. We’ll present the data to Cloud ML Engine as a simple array, encoded as a json file." }, { "code": null, "e": 2651, "s": 2612, "text": "print(list(X_test.iloc[10:11].values))" }, { "code": null, "e": 3100, "s": 2651, "text": "Here I’m taking the test features dataframe and extracting row 10 row from it, and then calling .values to get the underlying numpy array. Unfortunately, numpy arrays don’t print with commas between their values, and we really want the commas, so I’ve turned the numpy array into a Python list and printed that out. (Yes, you could, and probably should really just use the json library and encode it properly rather than relying on print behavior!)" }, { "code": null, "e": 3329, "s": 3100, "text": "I’ve saved the array to an input file, and now we can call the prediction REST API for our scikit-learn model. gcloud has a built-in utility to do this. We are expecting a response of 4, which is indeed what we get back! Huzzah!" }, { "code": null, "e": 3669, "s": 3329, "text": "You can follow the steps in this video to deploy your scikit-learn model to production, or step it up by turning it into automated pipeline so that each time you make a new model, it gets deployed out so you can test it! Head on over to Cloud ML Engine and upload your scikit-learn model to get auto-scaling predictions at your fingertips!" }, { "code": null, "e": 3813, "s": 3669, "text": "For a more detailed treatment on this topic, the documentation has some great guides: https://cloud.google.com/ml-engine/docs/scikit/quickstart" } ]
Why do we use the novalidate attribute in HTML?
The novalidate attribute in HTML is used to signify that the form won’t get validated on submit. It is a Boolean attribute and useful if you want the user to save the progress of form filing. If the form validation is disabled, the user can easily save the form and continue & submit the form later. While continuing, the user does not have to first validate all the entries. You can try to run the following code to learn how to use novalidate attribute in HTML. In the following example, if you will add text in the <input type=”number” > field, then it won’t show an error. <!DOCTYPE html> <html> <head> <title>HTML novalidate attribute</title> </head> <body> <form action = "" method = "get" novalidate> Student Name<br><input type="name" name="sname"><br> Total Marks<br><input type="number" name="mark"><br> <input type="submit" value="Submit"> </form> </body> </html>
[ { "code": null, "e": 1438, "s": 1062, "text": "The novalidate attribute in HTML is used to signify that the form won’t get validated on submit. It is a Boolean attribute and useful if you want the user to save the progress of form filing. If the form validation is disabled, the user can easily save the form and continue & submit the form later. While continuing, the user does not have to first validate all the entries." }, { "code": null, "e": 1639, "s": 1438, "text": "You can try to run the following code to learn how to use novalidate attribute in HTML. In the following example, if you will add text in the <input type=”number” > field, then it won’t show an error." }, { "code": null, "e": 1994, "s": 1639, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML novalidate attribute</title>\n </head>\n <body>\n <form action = \"\" method = \"get\" novalidate>\n Student Name<br><input type=\"name\" name=\"sname\"><br>\n Total Marks<br><input type=\"number\" name=\"mark\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" } ]
Remove a specific element from a LinkedList in Java
A specific element in the LinkedList can be removed using the java.util.LinkedList.remove() method. This method removes the specified element the first time it occurs in the LinkedList and if the element is not in the LinkedList then no change occurs. The parameter required for the LinkedList.remove() method is the element to be removed. A program that demonstrates this is given as follows. Live Demo import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Apple"); l.add("Mango"); l.add("Pear"); l.add("Orange"); l.add("Guava"); System.out.println("The LinkedList is: " + l); System.out.println("The element Mango is removed from the LinkedList? " + l.remove("Mango")); System.out.println("The LinkedList is: " + l); } } The output of the above program is as follows The LinkedList is: [Apple, Mango, Pear, Orange, Guava] The element Mango is removed from the LinkedList? true The LinkedList is: [Apple, Pear, Orange, Guava] Now let us understand the above program. The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. After that, LinkedList.remove() method is used to remove the element “Mango” from the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows LinkedList<String> l = new LinkedList<String>(); l.add("Apple"); l.add("Mango"); l.add("Pear"); l.add("Orange"); l.add("Guava"); System.out.println("The LinkedList is: " + l); System.out.println("The element Mango is removed from the LinkedList? " + l.remove("Mango")); System.out.println("The LinkedList is: " + l);
[ { "code": null, "e": 1402, "s": 1062, "text": "A specific element in the LinkedList can be removed using the java.util.LinkedList.remove()\nmethod. This method removes the specified element the first time it occurs in the LinkedList and\nif the element is not in the LinkedList then no change occurs. The parameter required for the\nLinkedList.remove() method is the element to be removed." }, { "code": null, "e": 1456, "s": 1402, "text": "A program that demonstrates this is given as follows." }, { "code": null, "e": 1467, "s": 1456, "text": " Live Demo" }, { "code": null, "e": 1938, "s": 1467, "text": "import java.util.LinkedList;\npublic class Demo {\n public static void main(String[] args) {\n LinkedList<String> l = new LinkedList<String>();\n l.add(\"Apple\");\n l.add(\"Mango\");\n l.add(\"Pear\");\n l.add(\"Orange\");\n l.add(\"Guava\");\n System.out.println(\"The LinkedList is: \" + l);\n System.out.println(\"The element Mango is removed from the LinkedList? \" + l.remove(\"Mango\"));\n System.out.println(\"The LinkedList is: \" + l);\n }\n}" }, { "code": null, "e": 1984, "s": 1938, "text": "The output of the above program is as follows" }, { "code": null, "e": 2142, "s": 1984, "text": "The LinkedList is: [Apple, Mango, Pear, Orange, Guava]\nThe element Mango is removed from the LinkedList? true\nThe LinkedList is: [Apple, Pear, Orange, Guava]" }, { "code": null, "e": 2183, "s": 2142, "text": "Now let us understand the above program." }, { "code": null, "e": 2466, "s": 2183, "text": "The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList.\nAfter that, LinkedList.remove() method is used to remove the element “Mango” from the\nLinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as\nfollows" }, { "code": null, "e": 2783, "s": 2466, "text": "LinkedList<String> l = new LinkedList<String>();\nl.add(\"Apple\");\nl.add(\"Mango\");\nl.add(\"Pear\");\nl.add(\"Orange\");\nl.add(\"Guava\");\nSystem.out.println(\"The LinkedList is: \" + l);\nSystem.out.println(\"The element Mango is removed from the LinkedList? \" +\nl.remove(\"Mango\"));\nSystem.out.println(\"The LinkedList is: \" + l);" } ]
How to find the proportion of row values in R dataframe? - GeeksforGeeks
07 Apr, 2021 The proportion of row value in a data frame is equivalent to the cell value divided by the summation of the cell values belonging to that entire row. The sum of all the row proportion values in a data frame is equivalent to 1. In this article, we are going to see how to find the proportion of row values in a data frame in R Programming Language. Example 1: An iteration over the matrix is carried out, using two for loops. We compute the row sum for each row while performing row iteration, and then divide the cell value by the row sum. This value is reassigned to the data frame original cell value. The time complexity required to perform this is equivalent to O(n * m), where n is the no. of rows and m is the number of columns in the data frame. The following code snippet illustrates the application of this approach : R # declaring a data frame in Rdata_frame = data.frame(C1= c(0,1,2,3), C2 = c(1:4), C3 = c(9:12)) print("Original data frame")print(data_frame) # looping over the rows of data framefor (i in 1:nrow(data_frame)){ # looping over the columns of data frame for (j in 1:ncol(data_frame)){ # computing sum of row i row_sum <- sum(data_frame[i,]) # calculating row proportion of the cell # value data_frame[i,j] <- data_frame[i,j]/row_sum }} # printing modified data frameprint ("Modified data frame")print (data_frame) Output: [1] "Original data frame" C1 C2 C3 1 0 1 9 2 1 2 10 3 2 3 11 4 3 4 12 [1] "Modified data frame" C1 C2 C3 1 0.00000000 0.1000000 0.9890110 2 0.07692308 0.1656051 0.9763215 3 0.12500000 0.2123894 0.9702410 4 0.15789474 0.2475570 0.9673166 Example 2 : Using rowSums() method This method loops over the data frame and iteratively computes the sum of each row in the data frame. For the application of this method, the input data frame must be numeric in nature. However, this method is also applicable for complex numbers. The following syntax in R can be used to compute the row proportion of cell values, wherein the output has to be explicitly stored into a new data frame : Syntax: mdf<-df/rowSums(df) Arguments : df – The data frame to compute the proportion of row values Code: R # declaring a data frame in Rdata_frame = data.frame(C1= c(0,1,2,3), C2 = c(2,3,2,3), C3 = c(9:12)) print("Original data frame")print(data_frame) # divides each cell value with corresponding# row sum valuedata_frame<-data_frame/rowSums(data_frame) # printing modified data frameprint ("Modified data frame")print (data_frame) Output: [1] "Original data frame" C1 C2 C3 1 0 2 9 2 1 3 10 3 2 2 11 4 3 3 12 [1] "Modified data frame" C1 C2 C3 1 0.00000000 0.1818182 0.8181818 2 0.07142857 0.2142857 0.7142857 3 0.13333333 0.1333333 0.7333333 4 0.16666667 0.1666667 0.6666667 The following code snippet illustrates the calculation of row proportion on the complex numbers’ data frame : R # declaring a data frame in Rdata_frame = data.frame(C1= c(1+2i,3i,6+5i,1+2i), C2 = c(2,3,2,3), C3 = c(9:12)) print("Original data frame")print(data_frame) # divides each cell value with corresponding row sum valuedata_frame<-data_frame/rowSums(data_frame) # printing modified data frameprint ("Modified data frame")print (data_frame) Output [1] "Original data frame" C1 C2 C3 1 1+2i 2 9 2 0+3i 3 10 3 6+5i 2 11 4 1+2i 3 12 [1] "Modified data frame" C1 C2 C3 1 0.1081081+0.1486486i 0.1621622-0.02702703i 0.7297297-0.1216216i 2 0.0505618+0.2191011i 0.2191011-0.05056180i 0.7303371-0.1685393i 3 0.3601036+0.1683938i 0.0984456-0.02590674i 0.5414508-0.1424870i 4 0.0769231+0.1153846i 0.1846154-0.02307692i 0.7384615-0.0923077i All the values are evaluated in the form of a whole number + 0i and the corresponding row proportion value is returned. Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25590, "s": 25242, "text": "The proportion of row value in a data frame is equivalent to the cell value divided by the summation of the cell values belonging to that entire row. The sum of all the row proportion values in a data frame is equivalent to 1. In this article, we are going to see how to find the proportion of row values in a data frame in R Programming Language." }, { "code": null, "e": 25996, "s": 25590, "text": "Example 1: An iteration over the matrix is carried out, using two for loops. We compute the row sum for each row while performing row iteration, and then divide the cell value by the row sum. This value is reassigned to the data frame original cell value. The time complexity required to perform this is equivalent to O(n * m), where n is the no. of rows and m is the number of columns in the data frame. " }, { "code": null, "e": 26071, "s": 25996, "text": "The following code snippet illustrates the application of this approach : " }, { "code": null, "e": 26073, "s": 26071, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(0,1,2,3), C2 = c(1:4), C3 = c(9:12)) print(\"Original data frame\")print(data_frame) # looping over the rows of data framefor (i in 1:nrow(data_frame)){ # looping over the columns of data frame for (j in 1:ncol(data_frame)){ # computing sum of row i row_sum <- sum(data_frame[i,]) # calculating row proportion of the cell # value data_frame[i,j] <- data_frame[i,j]/row_sum }} # printing modified data frameprint (\"Modified data frame\")print (data_frame)", "e": 26699, "s": 26073, "text": null }, { "code": null, "e": 26707, "s": 26699, "text": "Output:" }, { "code": null, "e": 26977, "s": 26707, "text": "[1] \"Original data frame\"\n C1 C2 C3\n1 0 1 9\n2 1 2 10\n3 2 3 11\n4 3 4 12\n[1] \"Modified data frame\"\n C1 C2 C3\n1 0.00000000 0.1000000 0.9890110\n2 0.07692308 0.1656051 0.9763215\n3 0.12500000 0.2123894 0.9702410\n4 0.15789474 0.2475570 0.9673166" }, { "code": null, "e": 27012, "s": 26977, "text": "Example 2 : Using rowSums() method" }, { "code": null, "e": 27414, "s": 27012, "text": "This method loops over the data frame and iteratively computes the sum of each row in the data frame. For the application of this method, the input data frame must be numeric in nature. However, this method is also applicable for complex numbers. The following syntax in R can be used to compute the row proportion of cell values, wherein the output has to be explicitly stored into a new data frame :" }, { "code": null, "e": 27442, "s": 27414, "text": "Syntax: mdf<-df/rowSums(df)" }, { "code": null, "e": 27514, "s": 27442, "text": "Arguments : df – The data frame to compute the proportion of row values" }, { "code": null, "e": 27520, "s": 27514, "text": "Code:" }, { "code": null, "e": 27522, "s": 27520, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(0,1,2,3), C2 = c(2,3,2,3), C3 = c(9:12)) print(\"Original data frame\")print(data_frame) # divides each cell value with corresponding# row sum valuedata_frame<-data_frame/rowSums(data_frame) # printing modified data frameprint (\"Modified data frame\")print (data_frame)", "e": 27897, "s": 27522, "text": null }, { "code": null, "e": 27905, "s": 27897, "text": "Output:" }, { "code": null, "e": 28175, "s": 27905, "text": "[1] \"Original data frame\"\n C1 C2 C3\n1 0 2 9\n2 1 3 10\n3 2 2 11\n4 3 3 12\n[1] \"Modified data frame\"\n C1 C2 C3\n1 0.00000000 0.1818182 0.8181818\n2 0.07142857 0.2142857 0.7142857\n3 0.13333333 0.1333333 0.7333333\n4 0.16666667 0.1666667 0.6666667" }, { "code": null, "e": 28286, "s": 28175, "text": "The following code snippet illustrates the calculation of row proportion on the complex numbers’ data frame : " }, { "code": null, "e": 28288, "s": 28286, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(1+2i,3i,6+5i,1+2i), C2 = c(2,3,2,3), C3 = c(9:12)) print(\"Original data frame\")print(data_frame) # divides each cell value with corresponding row sum valuedata_frame<-data_frame/rowSums(data_frame) # printing modified data frameprint (\"Modified data frame\")print (data_frame)", "e": 28672, "s": 28288, "text": null }, { "code": null, "e": 28679, "s": 28672, "text": "Output" }, { "code": null, "e": 29124, "s": 28679, "text": "[1] \"Original data frame\"\n C1 C2 C3\n1 1+2i 2 9\n2 0+3i 3 10\n3 6+5i 2 11\n4 1+2i 3 12\n[1] \"Modified data frame\"\n C1 C2 C3\n1 0.1081081+0.1486486i 0.1621622-0.02702703i 0.7297297-0.1216216i\n2 0.0505618+0.2191011i 0.2191011-0.05056180i 0.7303371-0.1685393i\n3 0.3601036+0.1683938i 0.0984456-0.02590674i 0.5414508-0.1424870i\n4 0.0769231+0.1153846i 0.1846154-0.02307692i 0.7384615-0.0923077i" }, { "code": null, "e": 29245, "s": 29124, "text": "All the values are evaluated in the form of a whole number + 0i and the corresponding row proportion value is returned. " }, { "code": null, "e": 29252, "s": 29245, "text": "Picked" }, { "code": null, "e": 29273, "s": 29252, "text": "R DataFrame-Programs" }, { "code": null, "e": 29285, "s": 29273, "text": "R-DataFrame" }, { "code": null, "e": 29296, "s": 29285, "text": "R Language" }, { "code": null, "e": 29307, "s": 29296, "text": "R Programs" }, { "code": null, "e": 29405, "s": 29307, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29457, "s": 29405, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29495, "s": 29457, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29530, "s": 29495, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29588, "s": 29530, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29637, "s": 29588, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29695, "s": 29637, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29744, "s": 29695, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29794, "s": 29744, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29837, "s": 29794, "text": "Replace Specific Characters in String in R" } ]
Can a C++ class have an object of self type? - GeeksforGeeks
31 Jul, 2018 A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type. For example, following program works fine. // A class can have a static member of self type#include<iostream> using namespace std; class Test { static Test self; // works fine /* other stuff in class*/ }; int main(){ Test t; getchar(); return 0;} And following program also works fine. // A class can have a pointer to self type#include<iostream> using namespace std; class Test { Test * self; //works fine /* other stuff in class*/ }; int main(){ Test t; getchar(); return 0;} But following program generates compilation error “field `self’ has incomplete type” // A class cannot have non-static object(s) of self type.#include<iostream> using namespace std; class Test { Test self; // Error /* other stuff in class*/ }; int main(){ Test t; getchar(); return 0;} If a non-static object is member then declaration of class is incomplete and compiler has no way to find out size of the objects of the class.Static variables do not contribute to the size of objects. So no problem in calculating size with static variables of self type.For a compiler, all pointers have a fixed size irrespective of the data type they are pointing to, so no problem with this also. Thanks to Manish Jain and Venki for their contribution to this post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples rand() and srand() in C/C++ C++ Data Types unordered_map in C++ STL Iterators in C++ STL getline (string) in C++ Stack in C++ STL
[ { "code": null, "e": 24150, "s": 24122, "text": "\n31 Jul, 2018" }, { "code": null, "e": 24302, "s": 24150, "text": "A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type." }, { "code": null, "e": 24345, "s": 24302, "text": "For example, following program works fine." }, { "code": "// A class can have a static member of self type#include<iostream> using namespace std; class Test { static Test self; // works fine /* other stuff in class*/ }; int main(){ Test t; getchar(); return 0;}", "e": 24562, "s": 24345, "text": null }, { "code": null, "e": 24601, "s": 24562, "text": "And following program also works fine." }, { "code": "// A class can have a pointer to self type#include<iostream> using namespace std; class Test { Test * self; //works fine /* other stuff in class*/ }; int main(){ Test t; getchar(); return 0;}", "e": 24805, "s": 24601, "text": null }, { "code": null, "e": 24890, "s": 24805, "text": "But following program generates compilation error “field `self’ has incomplete type”" }, { "code": "// A class cannot have non-static object(s) of self type.#include<iostream> using namespace std; class Test { Test self; // Error /* other stuff in class*/ }; int main(){ Test t; getchar(); return 0;}", "e": 25103, "s": 24890, "text": null }, { "code": null, "e": 25502, "s": 25103, "text": "If a non-static object is member then declaration of class is incomplete and compiler has no way to find out size of the objects of the class.Static variables do not contribute to the size of objects. So no problem in calculating size with static variables of self type.For a compiler, all pointers have a fixed size irrespective of the data type they are pointing to, so no problem with this also." }, { "code": null, "e": 25696, "s": 25502, "text": "Thanks to Manish Jain and Venki for their contribution to this post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25700, "s": 25696, "text": "C++" }, { "code": null, "e": 25704, "s": 25700, "text": "CPP" }, { "code": null, "e": 25802, "s": 25704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25811, "s": 25802, "text": "Comments" }, { "code": null, "e": 25824, "s": 25811, "text": "Old Comments" }, { "code": null, "e": 25852, "s": 25824, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25880, "s": 25852, "text": "Operator Overloading in C++" }, { "code": null, "e": 25915, "s": 25880, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25946, "s": 25915, "text": "Templates in C++ with Examples" }, { "code": null, "e": 25974, "s": 25946, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25989, "s": 25974, "text": "C++ Data Types" }, { "code": null, "e": 26014, "s": 25989, "text": "unordered_map in C++ STL" }, { "code": null, "e": 26035, "s": 26014, "text": "Iterators in C++ STL" }, { "code": null, "e": 26059, "s": 26035, "text": "getline (string) in C++" } ]
Program to check if a string contains any special character in C
Given a string str[], the task is to check whether the string contains any special character and if the string have a special character then print “The String is not accepted” else print “The string is accepted”. Special characters are those characters which are neither numeric nor alphabetic i.e. − !@#$%^&*()+=-\][‘;/.,{}|:”<>?`~ So in C Programming language we will use if-else approach to solve the problem. Input − str[] = {“tutorials-point”} Output − the string is not accepted Input − str[] = {“tutorialspoint”} Output − The string is accepted Traverse the whole string. Traverse the whole string. Will look for the special character, if the special character does exist in the string then, print “The string is not accepted and break”. Else, print the string is accepted. Will look for the special character, if the special character does exist in the string then, print “The string is not accepted and break”. Else, print the string is accepted. If we are coding in java or any other language which supports the concept of regular expressions, then instead of if-else approach we will use regular expressions to check that whether they are present in the given string or not. This is not only a simple approach but also a fast one. Start In function int special_character(char str[], int n) Step 1→ initialize i and flag and set flag as 0 Step 2→ Loop For i = 0 and i < n and ++i If(str[i] == '!' || str[i] == '@' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '&' || str[i] == '*' || str[i] == '(' || str[i] == ')' || str[i] == '-' || str[i] == '{' || str[i] == '}' || str[i] == '[' || str[i] == ']' || str[i] == ':' || str[i] == ';' || str[i] == '"' || str[i] == '\'' || str[i] == '<' || str[i] == '>' || str[i] == '.' || str[i] == '/' || str[i] == '?' || str[i] == '~' || str[i] == '`' then Print "String is not allowed” Set flag as 1 break Step 3→ If flag == 0 then, Print "string is accepted” In function int main(int argc, char const *argv[]) Step 1→ Declare and set str[] as {"Tutorials-point"} Step 2→ set n as strlen(str) Step 3→ special_character(str, n) Stop Live Demo #include <stdio.h> #include <string.h> int special_character(char str[], int n){ int i, flag = 0; for (i = 0; i < n; ++i){ //checking each character of the string for special character. if(str[i] == '!' || str[i] == '@' || str[i] == '#' || str[i] == '$' || str[i] == '%' || str[i] == '^' || str[i] == '&' || str[i] == '*' || str[i] == '(' || str[i] == ')' || str[i] == '-' || str[i] == '{' || str[i] == '}' || str[i] == '[' || str[i] == ']' || str[i] == ':' || str[i] == ';' || str[i] == '"' || str[i] == '\'' || str[i] == '<' || str[i] == '>' || str[i] == '.' || str[i] == '/' || str[i] == '?' || str[i] == '~' || str[i] == '`' ){ printf("String is not allowed\n"); flag = 1; break; } } //if there is no special charcter if (flag == 0){ printf("string is accepted\n"); } return 0; } int main(int argc, char const *argv[]){ char str[] = {"Tutorials-point"}; int n = strlen(str); special_character(str, n); return 0; } If run the above code it will generate the following output − String is not allowed
[ { "code": null, "e": 1275, "s": 1062, "text": "Given a string str[], the task is to check whether the string contains any special character and if the string have a special character then print “The String is not accepted” else print “The string is accepted”." }, { "code": null, "e": 1395, "s": 1275, "text": "Special characters are those characters which are neither numeric nor alphabetic i.e. − !@#$%^&*()+=-\\][‘;/.,{}|:”<>?`~" }, { "code": null, "e": 1475, "s": 1395, "text": "So in C Programming language we will use if-else approach to solve the problem." }, { "code": null, "e": 1511, "s": 1475, "text": "Input − str[] = {“tutorials-point”}" }, { "code": null, "e": 1547, "s": 1511, "text": "Output − the string is not accepted" }, { "code": null, "e": 1582, "s": 1547, "text": "Input − str[] = {“tutorialspoint”}" }, { "code": null, "e": 1614, "s": 1582, "text": "Output − The string is accepted" }, { "code": null, "e": 1641, "s": 1614, "text": "Traverse the whole string." }, { "code": null, "e": 1668, "s": 1641, "text": "Traverse the whole string." }, { "code": null, "e": 1843, "s": 1668, "text": "Will look for the special character, if the special character does exist in the string then, print “The string is not accepted and break”. Else, print the string is accepted." }, { "code": null, "e": 2018, "s": 1843, "text": "Will look for the special character, if the special character does exist in the string then, print “The string is not accepted and break”. Else, print the string is accepted." }, { "code": null, "e": 2304, "s": 2018, "text": "If we are coding in java or any other language which supports the concept of regular expressions, then instead of if-else approach we will use regular expressions to check that whether they are present in the given string or not. This is not only a simple approach but also a fast one." }, { "code": null, "e": 3272, "s": 2304, "text": "Start\nIn function int special_character(char str[], int n)\n Step 1→ initialize i and flag and set flag as 0\n Step 2→ Loop For i = 0 and i < n and ++i\n If(str[i] == '!' || str[i] == '@' || str[i] == '#' || str[i] == '$'\n || str[i] == '%' || str[i] == '^' || str[i] == '&' || str[i] == '*'\n || str[i] == '(' || str[i] == ')' || str[i] == '-' || str[i] == '{'\n || str[i] == '}' || str[i] == '[' || str[i] == ']' || str[i] == ':'\n || str[i] == ';' || str[i] == '\"' || str[i] == '\\'' || str[i] == '<'\n || str[i] == '>' || str[i] == '.' || str[i] == '/' || str[i] == '?'\n || str[i] == '~' || str[i] == '`' then\n Print \"String is not allowed”\n Set flag as 1\n break\n Step 3→ If flag == 0 then,\n Print \"string is accepted”\nIn function int main(int argc, char const *argv[])\n Step 1→ Declare and set str[] as {\"Tutorials-point\"}\n Step 2→ set n as strlen(str)\n Step 3→ special_character(str, n)\nStop" }, { "code": null, "e": 3283, "s": 3272, "text": " Live Demo" }, { "code": null, "e": 4321, "s": 3283, "text": "#include <stdio.h>\n#include <string.h>\nint special_character(char str[], int n){\n int i, flag = 0;\n for (i = 0; i < n; ++i){\n //checking each character of the string for special character.\n if(str[i] == '!' || str[i] == '@' || str[i] == '#' || str[i] == '$'\n || str[i] == '%' || str[i] == '^' || str[i] == '&' || str[i] == '*'\n || str[i] == '(' || str[i] == ')' || str[i] == '-' || str[i] == '{'\n || str[i] == '}' || str[i] == '[' || str[i] == ']' || str[i] == ':'\n || str[i] == ';' || str[i] == '\"' || str[i] == '\\'' || str[i] == '<'\n || str[i] == '>' || str[i] == '.' || str[i] == '/' || str[i] == '?'\n || str[i] == '~' || str[i] == '`' ){\n printf(\"String is not allowed\\n\");\n flag = 1;\n break;\n }\n }\n //if there is no special charcter\n if (flag == 0){\n printf(\"string is accepted\\n\");\n }\n return 0;\n}\nint main(int argc, char const *argv[]){\n char str[] = {\"Tutorials-point\"};\n int n = strlen(str);\n special_character(str, n);\n return 0;\n}" }, { "code": null, "e": 4383, "s": 4321, "text": "If run the above code it will generate the following output −" }, { "code": null, "e": 4405, "s": 4383, "text": "String is not allowed" } ]
TypeScript | toPrecision() Function - GeeksforGeeks
11 Jun, 2020 The toPrecision() method in TypeScript is used to return the string representation in exponential or fixed-point to the specified precision. Syntax: number.toPrecision( [ precision ] ) Parameter: It represents an integer value specifying the number of significant digits. Return Value: The toPrecision() method in TypeScript returns a string representing a Number in fixed-point or exponential notation round to precision significant digits. Below examples illustrate the working of toPrecision() function in TypeScript: Example 1: <script> // toPrecision() methodvar num = new Number(6.218956); console.log(num.toPrecision()); console.log(num.toPrecision(4)); console.log(num.toPrecision(3));</script> Output: 6.218956 6.2189 6.21 Example 2: <script> // toPrecision() methodlet myNumber: number = 32.5779; console.log("Number Method: toPrecision()"); console.log(myNumber.toPrecision(1)); console.log(myNumber.toPrecision(3)); </script> Output: Number Method: toPrecision() 3e+1 32.6 TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Difference Between PUT and PATCH Request Set the value of an input field in JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 24922, "s": 24894, "text": "\n11 Jun, 2020" }, { "code": null, "e": 25063, "s": 24922, "text": "The toPrecision() method in TypeScript is used to return the string representation in exponential or fixed-point to the specified precision." }, { "code": null, "e": 25071, "s": 25063, "text": "Syntax:" }, { "code": null, "e": 25108, "s": 25071, "text": "number.toPrecision( [ precision ] )\n" }, { "code": null, "e": 25195, "s": 25108, "text": "Parameter: It represents an integer value specifying the number of significant digits." }, { "code": null, "e": 25365, "s": 25195, "text": "Return Value: The toPrecision() method in TypeScript returns a string representing a Number in fixed-point or exponential notation round to precision significant digits." }, { "code": null, "e": 25444, "s": 25365, "text": "Below examples illustrate the working of toPrecision() function in TypeScript:" }, { "code": null, "e": 25455, "s": 25444, "text": "Example 1:" }, { "code": "<script> // toPrecision() methodvar num = new Number(6.218956); console.log(num.toPrecision()); console.log(num.toPrecision(4)); console.log(num.toPrecision(3));</script>", "e": 25627, "s": 25455, "text": null }, { "code": null, "e": 25635, "s": 25627, "text": "Output:" }, { "code": null, "e": 25659, "s": 25635, "text": "6.218956 \n6.2189 \n6.21\n" }, { "code": null, "e": 25670, "s": 25659, "text": "Example 2:" }, { "code": "<script> // toPrecision() methodlet myNumber: number = 32.5779; console.log(\"Number Method: toPrecision()\"); console.log(myNumber.toPrecision(1)); console.log(myNumber.toPrecision(3)); </script>", "e": 25870, "s": 25670, "text": null }, { "code": null, "e": 25878, "s": 25870, "text": "Output:" }, { "code": null, "e": 25918, "s": 25878, "text": "Number Method: toPrecision()\n3e+1\n32.6\n" }, { "code": null, "e": 25929, "s": 25918, "text": "TypeScript" }, { "code": null, "e": 25940, "s": 25929, "text": "JavaScript" }, { "code": null, "e": 25957, "s": 25940, "text": "Web Technologies" }, { "code": null, "e": 26055, "s": 25957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26064, "s": 26055, "text": "Comments" }, { "code": null, "e": 26077, "s": 26064, "text": "Old Comments" }, { "code": null, "e": 26122, "s": 26077, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26183, "s": 26122, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26255, "s": 26183, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26296, "s": 26255, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26342, "s": 26296, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 26384, "s": 26342, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26417, "s": 26384, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26467, "s": 26417, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26529, "s": 26467, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to extract the regression coefficients, standard error of coefficients, t scores, and p-values from a regression model in R?
Regression analysis output in R gives us so many values but if we believe that our model is good enough, we might want to extract only coefficients, standard errors, and t-scores or p-values because these are the values that ultimately matters, specifically the coefficients as they help us to interpret the model. We can extract these values from the regression model summary with delta $ operator. Consider the below data − > set.seed(99) > x1<-rpois(50,2) > x2<-rpois(50,10) > x3<-rpois(50,25) > x4<-rnorm(50,1) > x5<-rnorm(50,2.5) > x6<-rnorm(50,1.5) > x7<-runif(50,2,20) > y<-sample(1:1000,50,replace=TRUE) Creating the regression model − > Regression_Model<-lm(y~x1+x2+x3+x4+x5+x6+x7) Getting the output of the model &minus > summary(Regression_Model) Call: lm(formula = y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7) Residuals: Min 1Q Median 3Q Max -580.06 -268.03 71.54 248.45 450.20 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 885.966696 336.412681 2.634 0.0118 * x1 -33.463082 34.748162 -0.963 0.3411 x2 -8.056429 13.866217 -0.581 0.5643 x3 -0.003585 9.641347 0.000 0.9997 x4 -62.751405 47.195104 -1.330 0.1908 x5 -53.421667 40.706602 -1.312 0.1965 x6 -46.645285 41.017385 -1.137 0.2619 x7 7.705532 8.543121 0.902 0.3722 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 309.4 on 42 degrees of freedom Multiple R-squared: 0.1242, Adjusted R-squared: -0.02181 F-statistic: 0.8506 on 7 and 42 DF, p-value: 0.5526 Extracting all regression coefficients, standard error of coefficients, t scores, and p-values from the model − > summary(Regression_Model)$coefficients Estimate Std. Error t value Pr(>|t|) (Intercept) 885.966696369 336.412681 2.6335710454 0.01177664 x1 -33.463081817 34.748162 -0.9630173179 0.34105093 x2 -8.056428960 13.866217 -0.5810113022 0.56433788 x3 -0.003584907 9.641347 -0.0003718264 0.99970509 x4 -62.751404764 47.195104 -1.3296168453 0.19082124 x5 -53.421667389 40.706602 -1.3123588063 0.19652614 x6 -46.645285482 41.017385 -1.1372076842 0.26189795 x7 7.705532157 8.543121 0.9019575482 0.37222303 Extracting individual regression coefficients, standard error of coefficients, t scores, and p-values from the model − > summary(Regression_Model)$coefficients[1,2] [1] 336.4127 > summary(Regression_Model)$coefficients[1,1] [1] 885.9667 > summary(Regression_Model)$coefficients[1,4] [1] 0.01177664 > summary(Regression_Model)$coefficients[3,1] [1] -8.056429 > summary(Regression_Model)$coefficients[7,1] [1] -46.64529 > summary(Regression_Model)$coefficients[7,4] [1] 0.261898 > summary(Regression_Model)$coefficients[8,4] [1] 0.372223 > summary(Regression_Model)$coefficients[1,3] [1] 2.633571 > summary(Regression_Model)$coefficients[2,1] [1] -33.46308 > summary(Regression_Model)$coefficients[2,2] [1] 34.74816 > summary(Regression_Model)$coefficients[2,4] [1] 0.3410509 > summary(Regression_Model)$coefficients[4,4] [1] 0.9997051 > summary(Regression_Model)$coefficients[4,3] [1] -0.0003718264 > summary(Regression_Model)$coefficients[5,4] [1] 0.1908212 > summary(Regression_Model)$coefficients[5,1] [1] -62.7514 > summary(Regression_Model)$coefficients[5,2] [1] 47.1951 > summary(Regression_Model)$coefficients[6,1] [1] -53.42167 > summary(Regression_Model)$coefficients[6,4] [1] 0.1965261
[ { "code": null, "e": 1462, "s": 1062, "text": "Regression analysis output in R gives us so many values but if we believe that our model is good enough, we might want to extract only coefficients, standard errors, and t-scores or p-values because these are the values that ultimately matters, specifically the coefficients as they help us to interpret the model. We can extract these values from the regression model summary with delta $ operator." }, { "code": null, "e": 1488, "s": 1462, "text": "Consider the below data −" }, { "code": null, "e": 1674, "s": 1488, "text": "> set.seed(99)\n> x1<-rpois(50,2)\n> x2<-rpois(50,10)\n> x3<-rpois(50,25)\n> x4<-rnorm(50,1)\n> x5<-rnorm(50,2.5)\n> x6<-rnorm(50,1.5)\n> x7<-runif(50,2,20)\n> y<-sample(1:1000,50,replace=TRUE)" }, { "code": null, "e": 1706, "s": 1674, "text": "Creating the regression model −" }, { "code": null, "e": 1753, "s": 1706, "text": "> Regression_Model<-lm(y~x1+x2+x3+x4+x5+x6+x7)" }, { "code": null, "e": 1792, "s": 1753, "text": "Getting the output of the model &minus" }, { "code": null, "e": 2542, "s": 1792, "text": "> summary(Regression_Model)\nCall:\nlm(formula = y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7)\nResiduals:\nMin 1Q Median 3Q Max\n-580.06 -268.03 71.54 248.45 450.20\nCoefficients:\nEstimate Std. Error t value Pr(>|t|)\n(Intercept) 885.966696 336.412681 2.634 0.0118 *\nx1 -33.463082 34.748162 -0.963 0.3411\nx2 -8.056429 13.866217 -0.581 0.5643\nx3 -0.003585 9.641347 0.000 0.9997\nx4 -62.751405 47.195104 -1.330 0.1908\nx5 -53.421667 40.706602 -1.312 0.1965\nx6 -46.645285 41.017385 -1.137 0.2619\nx7 7.705532 8.543121 0.902 0.3722\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\nResidual standard error: 309.4 on 42 degrees of freedom\nMultiple R-squared: 0.1242, Adjusted R-squared: -0.02181\nF-statistic: 0.8506 on 7 and 42 DF, p-value: 0.5526" }, { "code": null, "e": 2654, "s": 2542, "text": "Extracting all regression coefficients, standard error of coefficients, t scores, and p-values from the model −" }, { "code": null, "e": 3157, "s": 2654, "text": "> summary(Regression_Model)$coefficients\nEstimate Std. Error t value Pr(>|t|)\n(Intercept) 885.966696369 336.412681 2.6335710454 0.01177664\nx1 -33.463081817 34.748162 -0.9630173179 0.34105093\nx2 -8.056428960 13.866217 -0.5810113022 0.56433788\nx3 -0.003584907 9.641347 -0.0003718264 0.99970509\nx4 -62.751404764 47.195104 -1.3296168453 0.19082124\nx5 -53.421667389 40.706602 -1.3123588063 0.19652614\nx6 -46.645285482 41.017385 -1.1372076842 0.26189795\nx7 7.705532157 8.543121 0.9019575482 0.37222303" }, { "code": null, "e": 3276, "s": 3157, "text": "Extracting individual regression coefficients, standard error of coefficients, t scores, and p-values from the model −" }, { "code": null, "e": 4352, "s": 3276, "text": "> summary(Regression_Model)$coefficients[1,2]\n[1] 336.4127\n> summary(Regression_Model)$coefficients[1,1]\n[1] 885.9667\n> summary(Regression_Model)$coefficients[1,4]\n[1] 0.01177664\n> summary(Regression_Model)$coefficients[3,1]\n[1] -8.056429\n> summary(Regression_Model)$coefficients[7,1]\n[1] -46.64529\n> summary(Regression_Model)$coefficients[7,4]\n[1] 0.261898\n> summary(Regression_Model)$coefficients[8,4]\n[1] 0.372223\n> summary(Regression_Model)$coefficients[1,3]\n[1] 2.633571\n> summary(Regression_Model)$coefficients[2,1]\n[1] -33.46308\n> summary(Regression_Model)$coefficients[2,2]\n[1] 34.74816\n> summary(Regression_Model)$coefficients[2,4]\n[1] 0.3410509\n> summary(Regression_Model)$coefficients[4,4]\n[1] 0.9997051\n> summary(Regression_Model)$coefficients[4,3]\n[1] -0.0003718264\n> summary(Regression_Model)$coefficients[5,4]\n[1] 0.1908212\n> summary(Regression_Model)$coefficients[5,1]\n[1] -62.7514\n> summary(Regression_Model)$coefficients[5,2]\n[1] 47.1951\n> summary(Regression_Model)$coefficients[6,1]\n[1] -53.42167\n> summary(Regression_Model)$coefficients[6,4]\n[1] 0.1965261" } ]
JPA - Quick Guide
Any enterprise application performs database operations by storing and retrieving vast amounts of data. Despite all the available technologies for storage management, application developers normally struggle to perform database operations efficiently. Generally, Java developers use lots of code, or use the proprietary framework to interact with the database, whereas using JPA, the burden of interacting with the database reduces significantly. It forms a bridge between object models (Java program) and relational models (database program). Relational objects are represented in a tabular format, while object models are represented in an interconnected graph of object format. While storing and retrieving an object model from a relational database, some mismatch occurs due to the following reasons: Granularity : Object model has more granularity than relational model. Granularity : Object model has more granularity than relational model. Subtypes : Subtypes (means inheritance) are not supported by all types of relational databases. Subtypes : Subtypes (means inheritance) are not supported by all types of relational databases. Identity : Like object model, relational model does not expose identity while writing equality. Identity : Like object model, relational model does not expose identity while writing equality. Associations : Relational models cannot determine multiple relationships while looking into object domain model. Associations : Relational models cannot determine multiple relationships while looking into object domain model. Data navigation : Data navigation between objects in an object network is different in both models. Data navigation : Data navigation between objects in an object network is different in both models. Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle Corporation. To reduce the burden of writing codes for relational object management, a programmer follows the ‘JPA Provider’ framework, which allows easy interaction with database instance. Here the required framework is taken over by JPA. Earlier versions of EJB, defined persistence layer combined with business logic layer using javax.ejb.EntityBean Interface. While introducing EJB 3.0, the persistence layer was separated and specified as JPA 1.0 (Java Persistence API). The specifications of this API were released along with the specifications of JAVA EE5 on May 11, 2006 using JSR 220. While introducing EJB 3.0, the persistence layer was separated and specified as JPA 1.0 (Java Persistence API). The specifications of this API were released along with the specifications of JAVA EE5 on May 11, 2006 using JSR 220. JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a part of Java Community Process JSR 317. JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a part of Java Community Process JSR 317. JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR 338. JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR 338. JPA is an open source API, therefore various enterprise vendors such as Oracle, Redhat, Eclipse, etc. provide new products by adding the JPA persistence flavor in them. Some of these products include: Hibernate, Eclipselink, Toplink, Spring Data JPA, etc. Java Persistence API is a source to store business entities as relational entities. It shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations. The following image shows the class level architecture of JPA. It shows the core classes and interfaces of JPA. The following table describes each of the units shown in the above architecture. The above classes and interfaces are used for storing entities into a database as a record. They help programmers by reducing their efforts to write codes for storing data into a database so that they can concentrate on more important activities such as writing codes for mapping the classes with database tables. In the above architecture, the relations between the classes and interfaces belong to the javax.persistence package. The following diagram shows the relationship between them. The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances. The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances. The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance. The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance. The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance. The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance. The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities. The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities. Most contemporary applications use relational database to store data. Recently, many vendors switched to object database to reduce their burden on data maintenance. It means object database or object relational technologies are taking care of storing, retrieving, updating, and maintaining data. The core part of this object relational technology is mapping orm.xml files. As xml does not require compilation, we can easily make changes to multiple data sources with less administration. Object Relational Mapping (ORM) briefly tells you about what is ORM and how it works. ORM is a programming ability to covert data from object type to relational type and vice versa. The main feature of ORM is mapping or binding an object to its data in the database. While mapping, we have to consider the data, the type of data, and its relations with self-entity or entities in any other table. Idiomatic persistence : It enables you to write the persistence classes using object oriented classes. Idiomatic persistence : It enables you to write the persistence classes using object oriented classes. High Performance : It has many fetching techniques and hopeful locking techniques. High Performance : It has many fetching techniques and hopeful locking techniques. Reliable : It is highly stable and Used by many professional programmers. Reliable : It is highly stable and Used by many professional programmers. The ORM architecture looks as follows. The above architecture explains how object data is stored into relational database in three phases. The first phase, named as the object data phase, contains POJO classes, service interfaces, and classes. It is the main business component layer, which has business logic operations and attributes. For example let us take an employee database as schema. Employee POJO class contains attributes such as ID, name, salary, and designation. It also contains methods like setter and getter of those attributes. Employee POJO class contains attributes such as ID, name, salary, and designation. It also contains methods like setter and getter of those attributes. Employee DAO/Service classes contain service methods such as create employee, find employee, and delete employee. Employee DAO/Service classes contain service methods such as create employee, find employee, and delete employee. The second phase, named as mapping or persistence phase, contains JPA provider, mapping file (ORM.xml), JPA Loader, and Object Grid. JPA Provider : It is the vendor product that contains the JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc. JPA Provider : It is the vendor product that contains the JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc. Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database. Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database. JPA Loader : The JPA loader works like a cache memory. It can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (attributes of POJO class). JPA Loader : The JPA loader works like a cache memory. It can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (attributes of POJO class). Object Grid : It is a temporary location that can store a copy of relational data, like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it affects the main database. Object Grid : It is a temporary location that can store a copy of relational data, like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it affects the main database. The third phase is the relational data phase. It contains the relational data that is logically connected to the business component. As discussed above, only when the business component commits the data, it is stored into the database physically. Until then, the modified data is stored in a cache memory as a grid format. The process of the obtaining the data is identical to that of storing the data. The mechanism of the programmatic interaction of above three phases is called as object relational mapping. The mapping.xml file is to instruct the JPA vendor to map the Entity classes with the database tables. Let us take an example of Employee entity which contains four attributes. The POJO class of Employee entity named Employee.java is as follows: public class Employee { private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } } The above code is the Employee entity POJO class. It contain four attributes eid, ename, salary, and deg. Consider these attributes as the table fields in a table and eid as the primary key of this table. Now we have to design the hibernate mapping file for it. The mapping file named mapping.xml is as follows: <? xml version="1.0" encoding="UTF-8" ?> <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0"> <description> XML Mapping file</description> <entity class="Employee"> <table name="EMPLOYEETABLE"/> <attributes> <id name="eid"> <generated-value strategy="TABLE"/> </id> <basic name="ename"> <column name="EMP_NAME" length="100"/> </basic> <basic name="salary"> </basic> <basic name="deg"> </basic> </attributes> </entity> </entity-mappings> The above script is used for mapping the entity class with the database table. In this file <entity-mappings> : tag defines the schema definition to allow entity tags into xml file. <entity-mappings> : tag defines the schema definition to allow entity tags into xml file. <description> : tag provides a description about application. <description> : tag provides a description about application. <entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name. <entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name. <table> : tag defines the table name. If you want to have identical names for both the class as well as the table, then this tag is not necessary. <table> : tag defines the table name. If you want to have identical names for both the class as well as the table, then this tag is not necessary. <attributes> : tag defines the attributes (fields in a table). <attributes> : tag defines the attributes (fields in a table). <id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence. <id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence. <basic> : tag is used for defining remaining attributes for table. <basic> : tag is used for defining remaining attributes for table. <column-name> : tag is used to define user-defined table field names in the table. <column-name> : tag is used to define user-defined table field names in the table. Generally xml files are used to configure specific components, or mapping two different specifications of components. In our case, we have to maintain xml files separately in a framework. That means while writing a mapping xml file, we need to compare the POJO class attributes with entity tags in the mapping.xml file. Here is the solution. In the class definition, we can write the configuration part using annotations. Annotations are used for classes, properties, and methods. Annotations start with ‘@’ symbol. Annotations are declared prior to a class, property, or method. All annotations of JPA are defined in the javax.persistence package. Here list of annotations used in our examples are given below. The Java class encapsulates the instance values and their behaviors into a single unit called object. Java Bean is a temporary storage and reusable component or an object. It is a serializable class which has a default constructor and getter and setter methods to initialize the instance attributes individually. Bean contains its default constructor or a file that contains serialized instance. Therefore, a bean can instantiate another bean. Bean contains its default constructor or a file that contains serialized instance. Therefore, a bean can instantiate another bean. The properties of a bean can be segregated into Boolean properties or non-Boolean properties. The properties of a bean can be segregated into Boolean properties or non-Boolean properties. Non-Boolean property contains getter and setter methods. Non-Boolean property contains getter and setter methods. Boolean property contain setter and is method. Boolean property contain setter and is method. Getter method of any property should start with small lettered get (java method convention) and continued with a field name that starts with capital letter. For example, the field name is salary therefore the getter method of this field is getSalary (). Getter method of any property should start with small lettered get (java method convention) and continued with a field name that starts with capital letter. For example, the field name is salary therefore the getter method of this field is getSalary (). Setter method of any property should start with small lettered set (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. For example, the field name is salary therefore the setter method of this field is setSalary ( double sal ). Setter method of any property should start with small lettered set (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. For example, the field name is salary therefore the setter method of this field is setSalary ( double sal ). For Boolean property, is method to check if it is true or false. For Example the Boolean property empty, the is method of this field is isEmpty (). For Boolean property, is method to check if it is true or false. For Example the Boolean property empty, the is method of this field is isEmpty (). This chapter takes you through the process of setting up JPA on Windows and Linux based systems. JPA can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation. Let us now proceed with the steps to install JPA. First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Open command console and type: \>java –version Java version "1.7.0_60" Java (TM) SE Run Time Environment (build 1.7.0_60-b19) Java Hotspot (TM) 64-bit Server VM (build 24.60-b09,mixed mode) Open command terminal and type: $java –version java version "1.7.0_25" Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode) We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system. We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system. In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Append the full path of Java compiler location to the System Path. Execute the command java -version from the command prompt as explained above. You can go through the JPA installation by using any of the JPA Providers from this tutorial, e.g., Eclipselink, Hibernate. Let us follow the JPA installation using Eclipselink. For JPA programming, we require to follow the specific folder framework, therefore it is better to use IDE. Download Eclipse IDE form following link https://www.eclipse.org/downloads/ Choose the EclipseIDE for JavaEE developer that is Eclipse indigo. Unzip the Eclipse zip file in C drive. Open Eclipse IDE. Eclipselink is a library therefore we cannot add it directly to Eclipse IDE. For installing JPA using Eclipselink you need to follow the steps given below. Create a new JPA project by selecting File->New->JPA Project in the Eclipse IDE as follows: Create a new JPA project by selecting File->New->JPA Project in the Eclipse IDE as follows: You will get a dialog box named New JPA Project. Enter project name tutorialspoint_JPA_Eclipselink, check the jre version and click next: You will get a dialog box named New JPA Project. Enter project name tutorialspoint_JPA_Eclipselink, check the jre version and click next: Click on download library (if you do not have the library) in the user library section. Click on download library (if you do not have the library) in the user library section. Select the latest version of Eclipselink library in the Download library dialog box and click next as follows: Select the latest version of Eclipselink library in the Download library dialog box and click next as follows: Accept the terms of license and click finish for download library. Accept the terms of license and click finish for download library. 6. Downloading starts as is shown in the following screenshot. 6. Downloading starts as is shown in the following screenshot. After downloading, select the downloaded library in the user library section and click finish. After downloading, select the downloaded library in the user library section and click finish. Finally you get the project file in the Package Explorer in Eclipse IDE. Extract all files, you will get the folder and file hierarchy as follows: Finally you get the project file in the Package Explorer in Eclipse IDE. Extract all files, you will get the folder and file hierarchy as follows: Any example that we discuss here requires database connectivity. Let us consider MySQL database for database operations. It requires mysql-connector jar to interact with a Java program. Follow the steps to configure the database jar in your project. Go to Project properties -> Java Build Path by right click on it. You will get a dialog box as shown in the following screen-shot. Click on Add External Jars. Go to Project properties -> Java Build Path by right click on it. You will get a dialog box as shown in the following screen-shot. Click on Add External Jars. Go to the jar location in your system memory, select the file and click on open. Go to the jar location in your system memory, select the file and click on open. Click ok on properties dialog. You will get the MySQL-connector Jar into your project. Now you are able to do database operations using MySQL. Click ok on properties dialog. You will get the MySQL-connector Jar into your project. Now you are able to do database operations using MySQL. This chapter uses a simple example to demonstrate how JPA works. Let us consider Employee Management as an example. Suppose the Employee Management creates, updates, finds, and deletes the records of an employee. As mentioned, we are using MySQL database for database operations. The main modules for this example are as follows: Model or POJO Employee.java Model or POJO Employee.java Persistence Persistence.xml Persistence Persistence.xml Service CreatingEmployee.java UpdatingEmployee.java FindingEmployee.java DeletingEmployee.java Service CreatingEmployee.java UpdatingEmployee.java FindingEmployee.java DeletingEmployee.java Let us take the package hierarchy which we have used in the JPA installation with Eclipselink. Follow the hierarchy for this example as shown below: Entities are nothing but beans or models. In this example, we will use Employee as an entity. eid, ename, salary, and deg are the attributes of this entity. It contains a default constructor as well as the setter and getter methods of those attributes. In the above shown hierarchy, create a package named ‘com.tutorialspoint.eclipselink.entity’, under ‘src’ (Source) package. Create a class named Employee.java under given package as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table public class Employee { @Id @GeneratedValue(strategy= GenerationType.AUTO) private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } @Override public String toString() { return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]"; } } In the above code, we have used @Entity annotation to make this POJO class an entity. Before going to next module we need to create database for relational entity, which will register the database in persistence.xml file. Open MySQL workbench and type hte following query. create database jpadb use jpadb This module plays a crucial role in the concept of JPA. In this xml file we will register the database and specify the entity class. In the above shown package hierarchy, persistence.xml under JPA Content package is as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> In the above xml, <persistence-unit> tag is defined with a specific name for JPA persistence. The <class> tag defines entity class with package name. The <properties> tag defines all the properties, and <property> tag defines each property such as database registration, URL specification, username, and password. These are the Eclipselink properties. This file will configure the database. Persistence operations are used for interacting with a database and they are load and store operations. In a business component, all the persistence operations fall under service classes. In the above shown package hierarchy, create a package named ‘com.tutorialspoint.eclipselink.service’, under ‘src’ (source) package. All the service classes named as CreateEmloyee.java, UpdateEmployee.java, FindEmployee.java, and DeleteEmployee.java. comes under the given package as follows: The following code segment shows how to create an Employee class named CreateEmployee.java. package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Employee; public class CreateEmployee { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); Employee employee = new Employee( ); employee.setEid( 1201 ); employee.setEname( "Gopal" ); employee.setSalary( 40000 ); employee.setDeg( "Technical Manager" ); entitymanager.persist( employee ); entitymanager.getTransaction( ).commit( ); entitymanager.close( ); emfactory.close( ); } } In the above code the createEntityManagerFactory () creates a persistence unit by providing the same unique name which we provide for persistence-unit in persistent.xml file. The entitymanagerfactory object will create the entitymanger instance by using createEntityManager () method. The entitymanager object creates entitytransaction instance for transaction management. By using entitymanager object, we can persist entities into the database. After compilation and execution of the above program you will get notifications from eclipselink library on the console panel of eclipse IDE. For result, open the MySQL workbench and type the following queries. use jpadb select * from employee The effected database table named employee will be shown in a tabular format as follows: To update the records of an employee, we need to retrieve the existing records form the database, make changes, and finally commit it to the database. The class named UpdateEmployee.java is shown as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Employee; public class UpdateEmployee { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); Employee employee=entitymanager. find( Employee.class, 1201 ); //before update System.out.println( employee ); employee.setSalary( 46000 ); entitymanager.getTransaction( ).commit( ); //after update System.out.println( employee ); entitymanager.close(); emfactory.close(); } } After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE. For result, open the MySQL workbench and type the following queries. use jpadb select * from employee The effected database table named employee will be shown in a tabular format as follows: The salary of employee, 1201 is updated to 46000. To find the records of an employee, we will have to retrieve the existing data from the database and display it. In this operation, EntityTransaction is not applied while retrieving a record. The class named FindEmployee.java as follows. package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Employee; public class FindEmployee { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence .createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager(); Employee employee = entitymanager. find( Employee.class, 1201 ); System.out.println("employee ID = "+employee.getEid( )); System.out.println("employee NAME = "+employee.getEname( )); System.out.println("employee SALARY = "+employee.getSalary( )); System.out.println("employee DESIGNATION = "+employee.getDeg( )); } } After compiling and executing the above program, you will get the following output from the Eclipselink library on the console panel of eclipse IDE. employee ID = 1201 employee NAME = Gopal employee SALARY = 46000.0 employee DESIGNATION = Technical Manager To delete the records of an employee, first we will find the existing records and then delete it. Here EntityTransaction plays an important role. The class named DeleteEmployee.java as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Employee; public class DeleteEmployee { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); Employee employee=entitymanager. find( Employee.class, 1201 ); entitymanager.remove( employee ); entitymanager.getTransaction( ).commit( ); entitymanager.close( ); emfactory.close( ); } } After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE. For result, open the MySQL workbench and type the following queries. use jpadb select * from employee The effected database named employee will have null records. After completion of all the modules in this example, the package and file hierarchy looks as follows: This chapter describes about JPQL and how it works with persistence units. In this chapter, the given examples follow the same package hierarchy, which we used in the previous chapter. JPQL stands for Java Persistence Query Language. It is used to create queries against entities to store in a relational database. JPQL is developed based on SQL syntax. But it won’t affect the database directly. JPQL can retrieve data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause. JPQL syntax is very similar to the syntax of SQL. Having SQL like syntax is an advantage because SQL is simple and being widely used. SQL works directly against relational database tables, records, and fields, whereas JPQL works with Java classes and instances. For example, a JPQL query can retrieve an entity object rather than field result set from a database, as with SQL. The JPQL query structure as follows. SELECT ... FROM ... [WHERE ...] [GROUP BY ... [HAVING ...]] [ORDER BY ...] The structure of JPQL DELETE and UPDATE queries are as follows. DELETE FROM ... [WHERE ...] UPDATE ... SET ... [WHERE ...] Scalar functions return resultant values based on input values. Aggregate functions return the resultant values by calculating the input values. We will use the same example Employee Management as in the previous chapter. Here we will go through the service classes using scalar and aggregate functions of JPQL. Let us assume the jpadb.employee table contains following records. Create a class named ScalarandAggregateFunctions.java under com.tutorialspoint.eclipselink.service package as follows. package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; public class ScalarandAggregateFunctions { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager(); //Scalar function Query query = entitymanager. createQuery("Select UPPER(e.ename) from Employee e"); List<String> list=query.getResultList(); for(String e:list) { System.out.println("Employee NAME :"+e); } //Aggregate function Query query1 = entitymanager. createQuery("Select MAX(e.salary) from Employee e"); Double result=(Double) query1.getSingleResult(); System.out.println("Max Employee Salary :"+result); } } After compilation and execution of the above program you will get the following output on the console panel of Eclipse IDE. Employee NAME :GOPAL Employee NAME :MANISHA Employee NAME :MASTHANVALI Employee NAME :SATISH Employee NAME :KRISHNA Employee NAME :KIRAN ax Employee Salary :40000.0 Between, And, and Like are the main keywords of JPQL. These keywords are used after Where clause in a query. Create a class named BetweenAndLikeFunctions.java under com.tutorialspoint.eclipselink.service package as follows: package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.tutorialspoint.eclipselink.entity.Employee; public class BetweenAndLikeFunctions { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager(); //Between Query query = entitymanager. createQuery( "Select e " + "from Employee e " + "where e.salary " + "Between 30000 and 40000" ) List<Employee> list=(List<Employee>)query.getResultList( ); for( Employee e:list ) { System.out.print("Employee ID :"+e.getEid( )); System.out.println("\t Employee salary :"+e.getSalary( )); } //Like Query query1 = entitymanager. createQuery("Select e " + "from Employee e " + "where e.ename LIKE 'M%'"); List<Employee> list1=(List<Employee>)query1.getResultList( ); for( Employee e:list1 ) { System.out.print("Employee ID :"+e.getEid( )); System.out.println("\t Employee name :"+e.getEname( )); } } } After compiling and executing the above program, you will get the following output in the console panel of Eclipse IDE. Employee ID :1201 Employee salary :40000.0 Employee ID :1202 Employee salary :40000.0 Employee ID :1203 Employee salary :40000.0 Employee ID :1204 Employee salary :30000.0 Employee ID :1205 Employee salary :30000.0 Employee ID :1206 Employee salary :35000.0 Employee ID :1202 Employee name :Manisha Employee ID :1203 Employee name :Masthanvali To order the records in JPQL, we use the ORDER BY clause. The usage of this clause is same as in SQL, but it deals with entities. The following example shows how to use the ORDER BY clause. Create a class Ordering.java under com.tutorialspoint.eclipselink.service package as follows: package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.tutorialspoint.eclipselink.entity.Employee; public class Ordering { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager(); //Between Query query = entitymanager. createQuery( "Select e " + "from Employee e " + "ORDER BY e.ename ASC" ); List<Employee> list=(List<Employee>)query.getResultList( ); for( Employee e:list ) { System.out.print("Employee ID :"+e.getEid( )); System.out.println("\t Employee Name :"+e.getEname( )); } } } compiling and executing the above program you will produce the following output in the console panel of Eclipse IDE. Employee ID :1201 Employee Name :Gopal Employee ID :1206 Employee Name :Kiran Employee ID :1205 Employee Name :Krishna Employee ID :1202 Employee Name :Manisha Employee ID :1203 Employee Name :Masthanvali Employee ID :1204 Employee Name :Satish A @NamedQuery annotation is defined as a query with a predefined query string that is unchangeable. In contrast to dynamic queries, named queries may improve code organization by separating the JPQL query strings from POJO. It also passes the query parameters rather than embedding the literals dynamically into the query string and therefore produces more efficient queries. First of all, add @NamedQuery annotation to the Employee entity class named Employee.java under com.tutorialspoint.eclipselink.entity package as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table @NamedQuery(query = "Select e from Employee e where e.eid = :id", name = "find employee by id") public class Employee { @Id @GeneratedValue(strategy= GenerationType.AUTO) private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } @Override public String toString() { return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]"; } } Create a class named NamedQueries.java under com.tutorialspoint.eclipselink.service package as follows: package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.tutorialspoint.eclipselink.entity.Employee; public class NamedQueries { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager(); Query query = entitymanager.createNamedQuery( "find employee by id"); query.setParameter("id", 1204); List<Employee> list = query.getResultList( ); for( Employee e:list ) { System.out.print("Employee ID :"+e.getEid( )); System.out.println("\t Employee Name :"+e.getEname( )); } } } After compiling and executing of the above program you will get the following output in the console panel of Eclipse IDE. Employee ID :1204 Employee Name :Satish After adding all the above classes the package hierarchy looks as follows: The most important concept of JPA is to make a duplicate copy of the database in the cache memory. While transacting with a database, the JPA first creates a duplicate set of data and only when it is committed using an entity manager, the changes are effected into the database. There are two ways of fetching records from the database. In eager fetching, related child objects are uploaded automatically while fetching a particular record. In lazy fetching, related objects are not uploaded automatically unless you specifically request for them. First of all, it checks the availability of related objects and notifies. Later, if you call any of the getter method of that entity, then it fetches all the records. Lazy fetch is possible when you try to fetch the records for the first time. That way, a copy of the whole record is already stored in the cache memory. Performance-wise, lazy fetch is preferable. JPA is a library which is released with Java specifications. Therefore, it supports all the object-oriented concepts for entity persistence. Till now, we are done with the basics of object relational mapping. This chapter takes you through the advanced mappings between objects and relational entities. Inheritance is the core concept of any object-oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies: SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS. Let us consider an example. The following diagram shows three classes, viz. Staff, TeachingStaff, and NonTeachingStaff, and their relationships. In the above diagram, Staff is an entity, while TeachingStaff and NonTeachingStaff are the sub-entities of Staff. Here we will use the above example to demonstrate all three three strategies of inheritance. Single-table strategy takes all classes fields (both super and sub classes) and map them down into a single table known as SINGLE_TABLE strategy. Here the discriminator value plays a key role in differentiating the values of three entities in one table. Let us consider the above example. TeachingStaff and NonTeachingStaff are the sub-classes of Staff. As per the concept of inheritance, a sub-class inherits the properties of its super-class. Therefore sid and sname are the fields that belong to both TeachingStaff and NonTeachingStaff. Create a JPA project. All the modules of this project are as follows: Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.io.Serializable; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table @Inheritance( strategy = InheritanceType.SINGLE_TABLE ) @DiscriminatorColumn( name="type" ) public class Staff implements Serializable { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int sid; private String sname; public Staff( int sid, String sname ) { super( ); this.sid = sid; this.sname = sname; } public Staff( ) { super( ); } public int getSid( ) { return sid; } public void setSid( int sid ) { this.sid = sid; } public String getSname( ) { return sname; } public void setSname( String sname ) { this.sname = sname; } } In the above code @DescriminatorColumn specifies the field name (type) and its values show the remaining (Teaching and NonTeachingStaff) fields. Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue( value="TS" ) public class TeachingStaff extends Staff { private String qualification; private String subjectexpertise; public TeachingStaff( int sid, String sname, String qualification,String subjectexpertise ) { super( sid, sname ); this.qualification = qualification; this.subjectexpertise = subjectexpertise; } public TeachingStaff( ) { super( ); } public String getQualification( ) { return qualification; } public void setQualification( String qualification ) { this.qualification = qualification; } public String getSubjectexpertise( ) { return subjectexpertise; } public void setSubjectexpertise( String subjectexpertise ) { this.subjectexpertise = subjectexpertise; } } Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue( value = "NS" ) public class NonTeachingStaff extends Staff { private String areaexpertise; public NonTeachingStaff( int sid, String sname, String areaexpertise ) { super( sid, sname ); this.areaexpertise = areaexpertise; } public NonTeachingStaff( ) { super( ); } public String getAreaexpertise( ) { return areaexpertise; } public void setAreaexpertise( String areaexpertise ) { this.areaexpertise = areaexpertise; } } Persistence.xml contains the configuration information of database and the registration information of entity classes. The xml file is shown as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Staff</class> <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class> <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.NonTeachingStaff; import com.tutorialspoint.eclipselink.entity.TeachingStaff; public class SaveClient { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Teaching staff entity TeachingStaff ts1=new TeachingStaff( 1,"Gopal","MSc MEd","Maths"); TeachingStaff ts2=new TeachingStaff( 2, "Manisha", "BSc BEd", "English"); //Non-Teaching Staff entity NonTeachingStaff nts1=new NonTeachingStaff( 3, "Satish", "Accounts"); NonTeachingStaff nts2=new NonTeachingStaff( 4, "Krishna", "Office Admin"); //storing all entities entitymanager.persist(ts1); entitymanager.persist(ts2); entitymanager.persist(nts1); entitymanager.persist(nts2); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } After compiling and executing the above program you will get notifications on the console panel of Eclipse IDE. Check MySQL workbench for output. The output in a tabular format is shown as follows: Finally you will get a single table containing the field of all the three classes with a discriminator column named Type (field). Joined table strategy is to share the referenced column that contains unique values to join the table and make easy transactions. Let us consider the same example as above. Create a JPA Project. All the project modules are shown below. Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table @Inheritance( strategy = InheritanceType.JOINED ) public class Staff implements Serializable { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int sid; private String sname; public Staff( int sid, String sname ) { super( ); this.sid = sid; this.sname = sname; } public Staff( ) { super( ); } public int getSid( ) { return sid; } public void setSid( int sid ) { this.sid = sid; } public String getSname( ) { return sname; } public void setSname( String sname ) { this.sname = sname; } } Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @PrimaryKeyJoinColumn(referencedColumnName="sid") public class TeachingStaff extends Staff { private String qualification; private String subjectexpertise; public TeachingStaff( int sid, String sname, String qualification,String subjectexpertise ) { super( sid, sname ); this.qualification = qualification; this.subjectexpertise = subjectexpertise; } public TeachingStaff( ) { super( ); } public String getQualification( ) { return qualification; } public void setQualification( String qualification ) { this.qualification = qualification; } public String getSubjectexpertise( ) { return subjectexpertise; } public void setSubjectexpertise( String subjectexpertise ) { this.subjectexpertise = subjectexpertise; } } Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @PrimaryKeyJoinColumn(referencedColumnName="sid") public class NonTeachingStaff extends Staff { private String areaexpertise; public NonTeachingStaff( int sid, String sname, String areaexpertise ) { super( sid, sname ); this.areaexpertise = areaexpertise; } public NonTeachingStaff( ) { super( ); } public String getAreaexpertise( ) { return areaexpertise; } public void setAreaexpertise( String areaexpertise ) { this.areaexpertise = areaexpertise; } } Persistence.xml file contains the configuration information of the database and the registration information of entity classes. The xml file is shown as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Staff</class> <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class> <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. Create a class named SaveClient.java under the given package to store fields of Staff, TeachingStaff, and NonTeachingStaff class. Then SaveClient class is shown as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.NonTeachingStaff; import com.tutorialspoint.eclipselink.entity.TeachingStaff; public class SaveClient { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Teaching staff entity TeachingStaff ts1=new TeachingStaff( 1,"Gopal","MSc MEd","Maths"); TeachingStaff ts2=new TeachingStaff( 2, "Manisha", "BSc BEd", "English"); //Non-Teaching Staff entity NonTeachingStaff nts1=new NonTeachingStaff( 3, "Satish", "Accounts"); NonTeachingStaff nts2=new NonTeachingStaff( 4, "Krishna", "Office Admin"); //storing all entities entitymanager.persist(ts1); entitymanager.persist(ts2); entitymanager.persist(nts1); entitymanager.persist(nts2); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } After compiling and executing the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench. Here three tables are created and the result of staff table is displayed in a tabular format. The result of TeachingStaff table is displayed as follows: In the above table sid is the foreign key (reference field form staff table) The result of NonTeachingStaff table is displayed as follows: Finally, the three tables are created using their respective fields and the SID field is shared by all the three tables. In the Staff table, SID is the primary key. In the remaining two tables (TeachingStaff and NonTeachingStaff), SID is the foreign key. Table per class strategy is to create a table for each sub-entity. The Staff table will be created, but it will contain null values. The field values of Staff table must be shared by both TeachingStaff and NonTeachingStaff tables. Let us consider the same example as above. Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table @Inheritance( strategy = InheritanceType.TABLE_PER_CLASS ) public class Staff implements Serializable { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int sid; private String sname; public Staff( int sid, String sname ) { super( ); this.sid = sid; this.sname = sname; } public Staff( ) { super( ); } public int getSid( ) { return sid; } public void setSid( int sid ) { this.sid = sid; } public String getSname( ) { return sname; } public void setSname( String sname ) { this.sname = sname; } } Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity public class TeachingStaff extends Staff { private String qualification; private String subjectexpertise; public TeachingStaff( int sid, String sname, String qualification,String subjectexpertise ) { super( sid, sname ); this.qualification = qualification; this.subjectexpertise = subjectexpertise; } public TeachingStaff( ) { super( ); } public String getQualification( ) { return qualification; } public void setQualification( String qualification ) { this.qualification = qualification; } public String getSubjectexpertise( ) { return subjectexpertise; } public void setSubjectexpertise( String subjectexpertise ) { this.subjectexpertise = subjectexpertise; } } Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity public class NonTeachingStaff extends Staff { private String areaexpertise; public NonTeachingStaff( int sid, String sname, String areaexpertise ) { super( sid, sname ); this.areaexpertise = areaexpertise; } public NonTeachingStaff( ) { super( ); } public String getAreaexpertise( ) { return areaexpertise; } public void setAreaexpertise( String areaexpertise ) { this.areaexpertise = areaexpertise; } } Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Staff</class> <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class> <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows: package com.tutorialspoint.eclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.NonTeachingStaff; import com.tutorialspoint.eclipselink.entity.TeachingStaff; public class SaveClient { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Teaching staff entity TeachingStaff ts1=new TeachingStaff( 1,"Gopal","MSc MEd","Maths"); TeachingStaff ts2=new TeachingStaff( 2, "Manisha", "BSc BEd", "English"); //Non-Teaching Staff entity NonTeachingStaff nts1=new NonTeachingStaff( 3, "Satish", "Accounts"); NonTeachingStaff nts2=new NonTeachingStaff( 4, "Krishna", "Office Admin"); //storing all entities entitymanager.persist(ts1); entitymanager.persist(ts2); entitymanager.persist(nts1); entitymanager.persist(nts2); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } After compiling and executing the above program, you will get notifications on the console panel of Eclipse IDE. For output, check MySQL workbench. Here the three tables are created and the Staff table contains null records. The result of TeachingStaff is displayed as follows: The above table TeachingStaff contains fields of both Staff and TeachingStaff Entities. The result of NonTeachingStaff is displayed as follows: The above table NonTeachingStaff contains fields of both Staff and NonTeachingStaff Entities. This chapter takes you through the relationships between Entities. Generally the relations are more effective between tables in the database. Here the entity classes are treated as relational tables (concept of JPA), therefore the relationships between Entity classes are as follows: @ManyToOne Relation @OneToMany Relation @OneToOne Relation @ManyToMany Relation Many-To-One relation between entities exists where one entity (column or set of columns) is referenced with another entity (column or set of columns) containing unique values. In relational databases, these relations are applied by using foreign key/primary key between the tables. Let us consider an example of a relation between Employee and Department entities. In unidirectional manner, i.e., from Employee to Department, Many-To-One relation is applicable. That means each record of employee contains one department id, which should be a primary key in the Department table. Here in the Employee table, Department id is the foreign Key. The following diagram shows the Many-To-One relation between the two tables. Create a JPA project in eclipse IDE named JPA_Eclipselink_MTO. All the modules of this project are discussed below. Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName( ) { return name; } public void setName( String deptName ) { this.name = deptName; } } Create the second entity in this relation - Employee entity class named Employee.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Employee { @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; @ManyToOne private Department department; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } Persistence.xml file is required to configure the database and the registration of entity classes. Persitence.xml will be created by the eclipse IDE while creating a JPA Project. The configuration details are user specifications. The persistence.xml file is shown as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <class>com.tutorialspoint.eclipselink.entity.Department</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> This module contains the service classes, which implements the relational part using the attribute initialization. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named ManyToOne.java is created under given package. The DAO class is shown as follows: package com.tutorialspointeclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Department; import com.tutorialspoint.eclipselink.entity.Employee; public class ManyToOne { public static void main( String[ ] args ) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Department Entity Department department = new Department(); department.setName("Development"); //Store Department entitymanager.persist(department); //Create Employee1 Entity Employee employee1 = new Employee(); employee1.setEname("Satish"); employee1.setSalary(45000.0); employee1.setDeg("Technical Writer"); employee1.setDepartment(department); //Create Employee2 Entity Employee employee2 = new Employee(); employee2.setEname("Krishna"); employee2.setSalary(45000.0); employee2.setDeg("Technical Writer"); employee2.setDepartment(department); //Create Employee3 Entity Employee employee3 = new Employee(); employee3.setEname("Masthanvali"); employee3.setSalary(50000.0); employee3.setDeg("Technical Writer"); employee3.setDepartment(department); //Store Employees entitymanager.persist(employee1); entitymanager.persist(employee2); entitymanager.persist(employee3); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } After compiling and executing the above program, you will get notifications on the console panel of Eclipse IDE. For output, check MySQL workbench. In this example, two tables are created. Pass the following query in MySQL interface and the result of Department table will be displayed as follows: Select * from department Pass the following query in MySQL interface and the result of Employee table will be displayed as follows. Select * from employee In the above table Deparment_Id is the foreign key (reference field) from the Department table. In this relationship, each row of one entity is referenced to many child records in other entity. The important thing is that child records cannot have multiple parents. In a one-to-many relationship between Table A and Table B, each row in Table A can be linked to one or multiple rows in Table B. Let us consider the above example. Suppose Employee and Department tables in the above example are connected in a reverse unidirectional manner, then the relation becomes One-To-Many relation. Create a JPA project in eclipse IDE named JPA_Eclipselink_OTM. All the modules of this project are discussed below. Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) private int id; private String name; @OneToMany( targetEntity=Employee.class ) private List employeelist; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName( ) { return name; } public void setName( String deptName ) { this.name = deptName; } public List getEmployeelist() { return employeelist; } public void setEmployeelist(List employeelist) { this.employeelist = employeelist; } } Create the second entity in this relation -Employee entity class, named Employee.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } } The persistence.xml file is as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <class>com.tutorialspoint.eclipselink.entity.Department</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> This module contains the service classes, which implements the relational part using the attribute initialization. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named OneToMany.java is created under given package. The DAO class is shown as follows: package com.tutorialspointeclipselink.service; import java.util.List; import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Department; import com.tutorialspoint.eclipselink.entity.Employee; public class OneToMany { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Employee1 Entity Employee employee1 = new Employee(); employee1.setEname("Satish"); employee1.setSalary(45000.0); employee1.setDeg("Technical Writer"); //Create Employee2 Entity Employee employee2 = new Employee(); employee2.setEname("Krishna"); employee2.setSalary(45000.0); employee2.setDeg("Technical Writer"); //Create Employee3 Entity Employee employee3 = new Employee(); employee3.setEname("Masthanvali"); employee3.setSalary(50000.0); employee3.setDeg("Technical Writer"); //Store Employee entitymanager.persist(employee1); entitymanager.persist(employee2); entitymanager.persist(employee3); //Create Employeelist List<Employee> emplist = new ArrayList(); emplist.add(employee1); emplist.add(employee2); emplist.add(employee3); //Create Department Entity Department department= new Department(); department.setName("Development"); department.setEmployeelist(emplist); //Store Department entitymanager.persist(department); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output check MySQL workbench as follows. In this project three tables are created. Pass the following query in MySQL interface and the result of department_employee table will be displayed as follows: Select * from department_Id; In the above table, deparment_id and employee_id are the foreign keys (reference fields) from department and employee tables. Pass the following query in MySQL interface and the result of department table will be displayed in a tabular format as follows. Select * from department; Pass the following query in MySQL interface and the result of employee table will be displayed as follows: Select * from employee; In One-To-One relationship, one item can be linked to only one other item. It means each row of one entity is referred to one and only one row of another entity. Let us consider the above example. Employee and Department in a reverse unidirectional manner, the relation is One-To-One relation. It means each employee belongs to only one department. Create a JPA project in eclipse IDE named JPA_Eclipselink_OTO. All the modules of this project are discussed below. Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Department { @Id @GeneratedValue( strategy=GenerationType.AUTO ) private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName( ) { return name; } public void setName( String deptName ) { this.name = deptName; } } Create the second entity in this relation -Employee entity class, named Employee.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Employee { @Id @GeneratedValue( strategy= GenerationType.AUTO ) private int eid; private String ename; private double salary; private String deg; @OneToOne private Department department; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } Persistence.xml file as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <class>com.tutorialspoint.eclipselink.entity.Department</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named OneToOne.java is created under the given package. The DAO class is shown as follows: package com.tutorialspointeclipselink.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Department; import com.tutorialspoint.eclipselink.entity.Employee; public class OneToOne { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Department Entity Department department = new Department(); department.setName("Development"); //Store Department entitymanager.persist(department); //Create Employee Entity Employee employee = new Employee(); employee.setEname("Satish"); employee.setSalary(45000.0); employee.setDeg("Technical Writer"); employee.setDepartment(department); //Store Employee entitymanager.persist(employee); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench as follows. In the above example, two tables are created. Pass the following query in MySQL interface and the result of department table will be displayed as follows: Select * from department Pass the following query in MySQL interface and the result of employee table will be displayed as follows: Select * from employee Many-To-Many relationship is where one or more rows from one entity are associated with more than one row in other entity. Let us consider an example of a relation between two entities: Class and Teacher. In bidirectional manner, both Class and Teacher have Many-To-One relation. That means each record of Class is referred by Teacher set (teacher ids), which should be primary keys in the Teacher table and stored in the Teacher_Class table and vice versa. Here, the Teachers_Class table contains both the foreign key fields. Create a JPA project in eclipse IDE named JPA_Eclipselink_MTM. All the modules of this project are discussed below. Create entities by following the schema shown in the diagram above. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Clas.java under given package. The class Department entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Clas { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int cid; private String cname; @ManyToMany(targetEntity=Teacher.class) private Set teacherSet; public Clas() { super(); } public Clas(int cid, String cname, Set teacherSet) { super(); this.cid = cid; this.cname = cname; this.teacherSet = teacherSet; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Set getTeacherSet() { return teacherSet; } public void setTeacherSet(Set teacherSet) { this.teacherSet = teacherSet; } } Create the second entity in this relation -Employee entity class, named Teacher.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows: package com.tutorialspoint.eclipselink.entity; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Teacher { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private int tid; private String tname; private String subject; @ManyToMany(targetEntity=Clas.class) private Set clasSet; public Teacher() { super(); } public Teacher(int tid, String tname, String subject, Set clasSet) { super(); this.tid = tid; this.tname = tname; this.subject = subject; this.clasSet = clasSet; } public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public Set getClasSet() { return clasSet; } public void setClasSet(Set clasSet) { this.clasSet = clasSet; } } Persistence.xml file as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <class>com.tutorialspoint.eclipselink.entity.Department</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named ManyToMany.java is created under given package. The DAO class is shown as follows: package com.tutorialspoint.eclipselink.service; import java.util.HashSet; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.tutorialspoint.eclipselink.entity.Clas; import com.tutorialspoint.eclipselink.entity.Teacher; public class ManyToMany { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); entitymanager.getTransaction( ).begin( ); //Create Clas Entity Clas clas1=new Clas(0,"1st",null); Clas clas2=new Clas(0,"2nd",null); Clas clas3=new Clas(0,"3rd",null); //Store Clas entitymanager.persist(clas1); entitymanager.persist(clas2); entitymanager.persist(clas3); //Create Clas Set1 Set<Clas> classSet1 = new HashSet(); classSet1.add(clas1); classSet1.add(clas2); classSet1.add(clas3); //Create Clas Set2 Set<Clas> classSet2 = new HashSet(); classSet2.add(clas3); classSet2.add(clas1); classSet2.add(clas2); //Create Clas Set3 Set<Clas> classSet3 = new HashSet(); classSet3.add(clas2); classSet3.add(clas3); classSet3.add(clas1); //Create Teacher Entity Teacher teacher1 = new Teacher(0, "Satish","Java",classSet1); Teacher teacher2 = new Teacher(0, "Krishna","Adv Java",classSet2); Teacher teacher3 = new Teacher(0, "Masthanvali","DB2",classSet3); //Store Teacher entitymanager.persist(teacher1); entitymanager.persist(teacher2); entitymanager.persist(teacher3); entitymanager.getTransaction( ).commit( ); entitymanager.close( ); emfactory.close( ); } } In this example project, three tables are created. Pass the following query in MySQL interface and the result of teacher_clas table will be displayed as follows: Select * form teacher_clas In the above table teacher_tid is the foreign key from teacher table, and classet_cid is the foreign key from class table. Therefore different teachers are allotted to different class. Pass the following query in MySQL interface and the result of teacher table will be displayed as follows: Select * from teacher Pass the following query in MySQL interface and the result of clas table will be displayed as follows: Select * from clas Criteria is a predefined API that is used to define queries for entities. It is an alternative way of defining a JPQL query. These queries are type-safe, portable, and easy to modify by changing the syntax. Similar to JPQL, it follows an abstract schema (easy to edit schema) and embedded objects. The metadata API is mingled with criteria API to model persistent entity for criteria queries. The major advantage of Criteria API is that errors can be detected earlier during the compile time. String-based JPQL queries and JPA criteria based queries are same in performance and efficiency. The criteria is included into all versions of JPA therefore each step of criteria is notified in the specifications of JPA. In JPA 2.0, the criteria query API, standardization of queries are developed. In JPA 2.1, Criteria update and delete (bulk update and delete) are included. The Criteria and the JPQL are closely related and are allowed to design using similar operators in their queries. It follows javax.persistence.criteria package to design a query. The query structure means the syntax criteria query. The following simple criteria query returns all instances of the entity class in the data source. EntityManager em = ...; CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Entity class> cq = cb.createQuery(Entity.class); Root<Entity> from = cq.from(Entity.class); cq.select(Entity); TypedQuery<Entity> q = em.createQuery(cq); List<Entity> allitems = q.getResultList(); The query demonstrates the basic steps to create a criteria. EntityManager instance is used to create a CriteriaBuilder object. EntityManager instance is used to create a CriteriaBuilder object. CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query. CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query. CriteriaQuery.form method is called to set the query root. CriteriaQuery.form method is called to set the query root. CriteriaQuery.select is called to set the result list type. CriteriaQuery.select is called to set the result list type. TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result. TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result. getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List. getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List. Let us consider the example of employee database. Let us assume the jpadb.employee table contains following records: Eid Ename Salary Deg 401 Gopal 40000 Technical Manager 402 Manisha 40000 Proof reader 403 Masthanvali 35000 Technical Writer 404 Satish 30000 Technical writer 405 Krishna 30000 Technical Writer 406 Kiran 35000 Proof reader Create a JPA Project in the eclipse IDE named JPA_Eclipselink_Criteria. All the modules of this project are discussed below: Create a package named com.tutorialspoint.eclipselink.entity under ‘src’ Create a class named Employee.java under given package. The class Employee entity is shown as follows: package com.tutorialspoint.eclipselink.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue(strategy= GenerationType.AUTO) private int eid; private String ename; private double salary; private String deg; public Employee(int eid, String ename, double salary, String deg) { super( ); this.eid = eid; this.ename = ename; this.salary = salary; this.deg = deg; } public Employee( ) { super(); } public int getEid( ) { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname( ) { return ename; } public void setEname(String ename) { this.ename = ename; } public double getSalary( ) { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDeg( ) { return deg; } public void setDeg(String deg) { this.deg = deg; } @Override public String toString() { return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]"; } } Persistence.xml file is as follows: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL"> <class>com.tutorialspoint.eclipselink.entity.Employee</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="eclipselink.logging.level" value="FINE"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> This module contains the service classes, which implements the Criteria query part using the MetaData API initialization. Create a package named ‘com.tutorialspoint.eclipselink.service’. The class named CriteriaAPI.java is created under given package. The DAO class is shown as follows: package com.tutorialspoint.eclipselink.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import com.tutorialspoint.eclipselink.entity.Employee; public class CriteriaApi { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence. createEntityManagerFactory( "Eclipselink_JPA" ); EntityManager entitymanager = emfactory. createEntityManager( ); CriteriaBuilder criteriaBuilder = entitymanager .getCriteriaBuilder(); CriteriaQuery<Object> criteriaQuery = criteriaBuilder .createQuery(); Root<Employee> from = criteriaQuery.from(Employee.class); //select all records System.out.println(“Select all records”); CriteriaQuery<Object> select =criteriaQuery.select(from); TypedQuery<Object> typedQuery = entitymanager .createQuery(select); List<Object> resultlist= typedQuery.getResultList(); for(Object o:resultlist) { Employee e=(Employee)o; System.out.println("EID : "+e.getEid() +" Ename : "+e.getEname()); } //Ordering the records System.out.println(“Select all records by follow ordering”); CriteriaQuery<Object> select1 = criteriaQuery.select(from); select1.orderBy(criteriaBuilder.asc(from.get("ename"))); TypedQuery<Object> typedQuery1 = entitymanager .createQuery(select); List<Object> resultlist1= typedQuery1.getResultList(); for(Object o:resultlist1) { Employee e=(Employee)o; System.out.println("EID : "+e.getEid() +" Ename : "+e.getEname()); } entitymanager.close( ); emfactory.close( ); } } After compiling and executing the above program you will get the following output in the console panel of Eclipse IDE. Select All records EID : 401 Ename : Gopal EID : 402 Ename : Manisha EID : 403 Ename : Masthanvali EID : 404 Ename : Satish EID : 405 Ename : Krishna EID : 406 Ename : Kiran Select All records by follow Ordering EID : 401 Ename : Gopal EID : 406 Ename : Kiran EID : 405 Ename : Krishna EID : 402 Ename : Manisha EID : 403 Ename : Masthanvali EID : 404 Ename : Satish Print Add Notes Bookmark this page
[ { "code": null, "e": 1991, "s": 1739, "text": "Any enterprise application performs database operations by storing and retrieving vast amounts of data. Despite all the available technologies for storage management, application developers normally struggle to perform database operations efficiently." }, { "code": null, "e": 2283, "s": 1991, "text": "Generally, Java developers use lots of code, or use the proprietary framework to interact with the database, whereas using JPA, the burden of interacting with the database reduces significantly. It forms a bridge between object models (Java program) and relational models (database program)." }, { "code": null, "e": 2544, "s": 2283, "text": "Relational objects are represented in a tabular format, while object models are represented in an interconnected graph of object format. While storing and retrieving an object model from a relational database, some mismatch occurs due to the following reasons:" }, { "code": null, "e": 2615, "s": 2544, "text": "Granularity : Object model has more granularity than relational model." }, { "code": null, "e": 2686, "s": 2615, "text": "Granularity : Object model has more granularity than relational model." }, { "code": null, "e": 2782, "s": 2686, "text": "Subtypes : Subtypes (means inheritance) are not supported by all types of relational databases." }, { "code": null, "e": 2878, "s": 2782, "text": "Subtypes : Subtypes (means inheritance) are not supported by all types of relational databases." }, { "code": null, "e": 2974, "s": 2878, "text": "Identity : Like object model, relational model does not expose identity while writing equality." }, { "code": null, "e": 3070, "s": 2974, "text": "Identity : Like object model, relational model does not expose identity while writing equality." }, { "code": null, "e": 3183, "s": 3070, "text": "Associations : Relational models cannot determine multiple relationships while looking into object domain model." }, { "code": null, "e": 3296, "s": 3183, "text": "Associations : Relational models cannot determine multiple relationships while looking into object domain model." }, { "code": null, "e": 3396, "s": 3296, "text": "Data navigation : Data navigation between objects in an object network is different in both models." }, { "code": null, "e": 3496, "s": 3396, "text": "Data navigation : Data navigation between objects in an object network is different in both models." }, { "code": null, "e": 3664, "s": 3496, "text": "Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle Corporation." }, { "code": null, "e": 3891, "s": 3664, "text": "To reduce the burden of writing codes for relational object management, a programmer follows the ‘JPA Provider’ framework, which allows easy interaction with database instance. Here the required framework is taken over by JPA." }, { "code": null, "e": 4015, "s": 3891, "text": "Earlier versions of EJB, defined persistence layer combined with business logic layer using javax.ejb.EntityBean Interface." }, { "code": null, "e": 4245, "s": 4015, "text": "While introducing EJB 3.0, the persistence layer was separated and specified as JPA 1.0 (Java Persistence API). The specifications of this API were released along with the specifications of JAVA EE5 on May 11, 2006 using JSR 220." }, { "code": null, "e": 4475, "s": 4245, "text": "While introducing EJB 3.0, the persistence layer was separated and specified as JPA 1.0 (Java Persistence API). The specifications of this API were released along with the specifications of JAVA EE5 on May 11, 2006 using JSR 220." }, { "code": null, "e": 4598, "s": 4475, "text": "JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a part of Java Community Process JSR 317." }, { "code": null, "e": 4721, "s": 4598, "text": "JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a part of Java Community Process JSR 317." }, { "code": null, "e": 4810, "s": 4721, "text": "JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR 338." }, { "code": null, "e": 4899, "s": 4810, "text": "JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR 338." }, { "code": null, "e": 5100, "s": 4899, "text": "JPA is an open source API, therefore various enterprise vendors such as Oracle, Redhat, Eclipse, etc. provide new products by adding the JPA persistence flavor in them. Some of these products include:" }, { "code": null, "e": 5155, "s": 5100, "text": "Hibernate, Eclipselink, Toplink, Spring Data JPA, etc." }, { "code": null, "e": 5349, "s": 5155, "text": "Java Persistence API is a source to store business entities as relational entities. It shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations." }, { "code": null, "e": 5461, "s": 5349, "text": "The following image shows the class level architecture of JPA. It shows the core classes and interfaces of JPA." }, { "code": null, "e": 5542, "s": 5461, "text": "The following table describes each of the units shown in the above architecture." }, { "code": null, "e": 5856, "s": 5542, "text": "The above classes and interfaces are used for storing entities into a database as a record. They help programmers by reducing their efforts to write codes for storing data into a database so that they can concentrate on more important activities such as writing codes for mapping the classes with database tables." }, { "code": null, "e": 6032, "s": 5856, "text": "In the above architecture, the relations between the classes and interfaces belong to the javax.persistence package. The following diagram shows the relationship between them." }, { "code": null, "e": 6162, "s": 6032, "text": "The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances." }, { "code": null, "e": 6292, "s": 6162, "text": "The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances." }, { "code": null, "e": 6442, "s": 6292, "text": "The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance." }, { "code": null, "e": 6592, "s": 6442, "text": "The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance." }, { "code": null, "e": 6726, "s": 6592, "text": "The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance." }, { "code": null, "e": 6860, "s": 6726, "text": "The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance." }, { "code": null, "e": 6983, "s": 6860, "text": "The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities." }, { "code": null, "e": 7106, "s": 6983, "text": "The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities." }, { "code": null, "e": 7594, "s": 7106, "text": "Most contemporary applications use relational database to store data. Recently, many vendors switched to object database to reduce their burden on data maintenance. It means object database or object relational technologies are taking care of storing, retrieving, updating, and maintaining data. The core part of this object relational technology is mapping orm.xml files. As xml does not require compilation, we can easily make changes to multiple data sources with less administration." }, { "code": null, "e": 7776, "s": 7594, "text": "Object Relational Mapping (ORM) briefly tells you about what is ORM and how it works. ORM is a programming ability to covert data from object type to relational type and vice versa." }, { "code": null, "e": 7991, "s": 7776, "text": "The main feature of ORM is mapping or binding an object to its data in the database. While mapping, we have to consider the data, the type of data, and its relations with self-entity or entities in any other table." }, { "code": null, "e": 8094, "s": 7991, "text": "Idiomatic persistence : It enables you to write the persistence classes using object oriented classes." }, { "code": null, "e": 8197, "s": 8094, "text": "Idiomatic persistence : It enables you to write the persistence classes using object oriented classes." }, { "code": null, "e": 8280, "s": 8197, "text": "High Performance : It has many fetching techniques and hopeful locking techniques." }, { "code": null, "e": 8363, "s": 8280, "text": "High Performance : It has many fetching techniques and hopeful locking techniques." }, { "code": null, "e": 8437, "s": 8363, "text": "Reliable : It is highly stable and Used by many professional programmers." }, { "code": null, "e": 8511, "s": 8437, "text": "Reliable : It is highly stable and Used by many professional programmers." }, { "code": null, "e": 8550, "s": 8511, "text": "The ORM architecture looks as follows." }, { "code": null, "e": 8650, "s": 8550, "text": "The above architecture explains how object data is stored into relational database in three phases." }, { "code": null, "e": 8848, "s": 8650, "text": "The first phase, named as the object data phase, contains POJO classes, service interfaces, and classes. It is the main business component layer, which has business logic operations and attributes." }, { "code": null, "e": 8904, "s": 8848, "text": "For example let us take an employee database as schema." }, { "code": null, "e": 9056, "s": 8904, "text": "Employee POJO class contains attributes such as ID, name, salary, and designation. It also contains methods like setter and getter of those attributes." }, { "code": null, "e": 9208, "s": 9056, "text": "Employee POJO class contains attributes such as ID, name, salary, and designation. It also contains methods like setter and getter of those attributes." }, { "code": null, "e": 9322, "s": 9208, "text": "Employee DAO/Service classes contain service methods such as create employee, find employee, and delete employee." }, { "code": null, "e": 9436, "s": 9322, "text": "Employee DAO/Service classes contain service methods such as create employee, find employee, and delete employee." }, { "code": null, "e": 9569, "s": 9436, "text": "The second phase, named as mapping or persistence phase, contains JPA provider, mapping file (ORM.xml), JPA Loader, and Object Grid." }, { "code": null, "e": 9709, "s": 9569, "text": "JPA Provider : It is the vendor product that contains the JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc." }, { "code": null, "e": 9849, "s": 9709, "text": "JPA Provider : It is the vendor product that contains the JPA flavor (javax.persistence). For example Eclipselink, Toplink, Hibernate, etc." }, { "code": null, "e": 9990, "s": 9849, "text": "Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database." }, { "code": null, "e": 10131, "s": 9990, "text": "Mapping file : The mapping file (ORM.xml) contains mapping configuration between the data in a POJO class and data in a relational database." }, { "code": null, "e": 10332, "s": 10131, "text": "JPA Loader : The JPA loader works like a cache memory. It can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (attributes of POJO class)." }, { "code": null, "e": 10533, "s": 10332, "text": "JPA Loader : The JPA loader works like a cache memory. It can load the relational grid data. It works like a copy of database to interact with service classes for POJO data (attributes of POJO class)." }, { "code": null, "e": 10778, "s": 10533, "text": "Object Grid : It is a temporary location that can store a copy of relational data, like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it affects the main database." }, { "code": null, "e": 11023, "s": 10778, "text": "Object Grid : It is a temporary location that can store a copy of relational data, like a cache memory. All queries against the database is first effected on the data in the object grid. Only after it is committed, it affects the main database." }, { "code": null, "e": 11426, "s": 11023, "text": "The third phase is the relational data phase. It contains the relational data that is logically connected to the business component. As discussed above, only when the business component commits the data, it is stored into the database physically. Until then, the modified data is stored in a cache memory as a grid format. The process of the obtaining the data is identical to that of storing the data." }, { "code": null, "e": 11534, "s": 11426, "text": "The mechanism of the programmatic interaction of above three phases is called as object relational mapping." }, { "code": null, "e": 11637, "s": 11534, "text": "The mapping.xml file is to instruct the JPA vendor to map the Entity classes with the database tables." }, { "code": null, "e": 11780, "s": 11637, "text": "Let us take an example of Employee entity which contains four attributes. The POJO class of Employee entity named Employee.java is as follows:" }, { "code": null, "e": 12547, "s": 11780, "text": "public class Employee \n{\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\tpublic Employee(int eid, String ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\t\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n public String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\n}" }, { "code": null, "e": 12859, "s": 12547, "text": "The above code is the Employee entity POJO class. It contain four attributes eid, ename, salary, and deg. Consider these attributes as the table fields in a table and eid as the primary key of this table. Now we have to design the hibernate mapping file for it. The mapping file named mapping.xml is as follows:" }, { "code": null, "e": 13727, "s": 12859, "text": "<? xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<entity-mappings xmlns=\"http://java.sun.com/xml/ns/persistence/orm\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence/orm \n http://java.sun.com/xml/ns/persistence/orm_1_0.xsd\"\n version=\"1.0\">\n <description> XML Mapping file</description>\n <entity class=\"Employee\"> \n <table name=\"EMPLOYEETABLE\"/>\n <attributes>\n <id name=\"eid\">\n <generated-value strategy=\"TABLE\"/>\n </id>\n <basic name=\"ename\">\n <column name=\"EMP_NAME\" length=\"100\"/>\n </basic>\n <basic name=\"salary\">\n </basic>\n <basic name=\"deg\">\n </basic>\n </attributes>\n </entity>\n</entity-mappings>" }, { "code": null, "e": 13819, "s": 13727, "text": "The above script is used for mapping the entity class with the database table. In this file" }, { "code": null, "e": 13909, "s": 13819, "text": "<entity-mappings> : tag defines the schema definition to allow entity tags into xml file." }, { "code": null, "e": 13999, "s": 13909, "text": "<entity-mappings> : tag defines the schema definition to allow entity tags into xml file." }, { "code": null, "e": 14061, "s": 13999, "text": "<description> : tag provides a description about application." }, { "code": null, "e": 14123, "s": 14061, "text": "<description> : tag provides a description about application." }, { "code": null, "e": 14267, "s": 14123, "text": "<entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name." }, { "code": null, "e": 14411, "s": 14267, "text": "<entity> : tag defines the entity class which you want to convert into table in a database. Attribute class defines the POJO entity class name." }, { "code": null, "e": 14558, "s": 14411, "text": "<table> : tag defines the table name. If you want to have identical names for both the class as well as the table, then this tag is not necessary." }, { "code": null, "e": 14705, "s": 14558, "text": "<table> : tag defines the table name. If you want to have identical names for both the class as well as the table, then this tag is not necessary." }, { "code": null, "e": 14768, "s": 14705, "text": "<attributes> : tag defines the attributes (fields in a table)." }, { "code": null, "e": 14831, "s": 14768, "text": "<attributes> : tag defines the attributes (fields in a table)." }, { "code": null, "e": 15002, "s": 14831, "text": "<id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence.\n" }, { "code": null, "e": 15172, "s": 15002, "text": "<id> : tag defines the primary key of the table. The <generated-value> tag defines how to assign the primary key value such as Automatic, Manual, or taken from Sequence." }, { "code": null, "e": 15239, "s": 15172, "text": "<basic> : tag is used for defining remaining attributes for table." }, { "code": null, "e": 15306, "s": 15239, "text": "<basic> : tag is used for defining remaining attributes for table." }, { "code": null, "e": 15389, "s": 15306, "text": "<column-name> : tag is used to define user-defined table field names in the table." }, { "code": null, "e": 15472, "s": 15389, "text": "<column-name> : tag is used to define user-defined table field names in the table." }, { "code": null, "e": 15792, "s": 15472, "text": "Generally xml files are used to configure specific components, or mapping two different specifications of components. In our case, we have to maintain xml files separately in a framework. That means while writing a mapping xml file, we need to compare the POJO class attributes with entity tags in the mapping.xml file." }, { "code": null, "e": 16121, "s": 15792, "text": "Here is the solution. In the class definition, we can write the configuration part using annotations. Annotations are used for classes, properties, and methods. Annotations start with ‘@’ symbol. Annotations are declared prior to a class, property, or method. All annotations of JPA are defined in the javax.persistence package." }, { "code": null, "e": 16184, "s": 16121, "text": "Here list of annotations used in our examples are given below." }, { "code": null, "e": 16497, "s": 16184, "text": "The Java class encapsulates the instance values and their behaviors into a single unit called object. Java Bean is a temporary storage and reusable component or an object. It is a serializable class which has a default constructor and getter and setter methods to initialize the instance attributes individually." }, { "code": null, "e": 16628, "s": 16497, "text": "Bean contains its default constructor or a file that contains serialized instance. Therefore, a bean can instantiate another bean." }, { "code": null, "e": 16759, "s": 16628, "text": "Bean contains its default constructor or a file that contains serialized instance. Therefore, a bean can instantiate another bean." }, { "code": null, "e": 16853, "s": 16759, "text": "The properties of a bean can be segregated into Boolean properties or non-Boolean properties." }, { "code": null, "e": 16947, "s": 16853, "text": "The properties of a bean can be segregated into Boolean properties or non-Boolean properties." }, { "code": null, "e": 17004, "s": 16947, "text": "Non-Boolean property contains getter and setter methods." }, { "code": null, "e": 17061, "s": 17004, "text": "Non-Boolean property contains getter and setter methods." }, { "code": null, "e": 17108, "s": 17061, "text": "Boolean property contain setter and is method." }, { "code": null, "e": 17155, "s": 17108, "text": "Boolean property contain setter and is method." }, { "code": null, "e": 17409, "s": 17155, "text": "Getter method of any property should start with small lettered get (java method convention) and continued with a field name that starts with capital letter. For example, the field name is salary therefore the getter method of this field is getSalary ()." }, { "code": null, "e": 17663, "s": 17409, "text": "Getter method of any property should start with small lettered get (java method convention) and continued with a field name that starts with capital letter. For example, the field name is salary therefore the getter method of this field is getSalary ()." }, { "code": null, "e": 17965, "s": 17663, "text": "Setter method of any property should start with small lettered set (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. For example, the field name is salary therefore the setter method of this field is setSalary ( double sal )." }, { "code": null, "e": 18267, "s": 17965, "text": "Setter method of any property should start with small lettered set (java method convention), continued with a field name that starts with capital letter and the argument value to set to field. For example, the field name is salary therefore the setter method of this field is setSalary ( double sal )." }, { "code": null, "e": 18415, "s": 18267, "text": "For Boolean property, is method to check if it is true or false. For Example the Boolean property empty, the is method of this field is isEmpty ()." }, { "code": null, "e": 18563, "s": 18415, "text": "For Boolean property, is method to check if it is true or false. For Example the Boolean property empty, the is method of this field is isEmpty ()." }, { "code": null, "e": 18857, "s": 18563, "text": "This chapter takes you through the process of setting up JPA on Windows and Linux based systems. JPA can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation." }, { "code": null, "e": 18907, "s": 18857, "text": "Let us now proceed with the steps to install JPA." }, { "code": null, "e": 19104, "s": 18907, "text": "First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on." }, { "code": null, "e": 19288, "s": 19104, "text": "If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table." }, { "code": null, "e": 19319, "s": 19288, "text": "Open command console and type:" }, { "code": null, "e": 19335, "s": 19319, "text": "\\>java –version" }, { "code": null, "e": 19359, "s": 19335, "text": "Java version \"1.7.0_60\"" }, { "code": null, "e": 19414, "s": 19359, "text": "Java (TM) SE Run Time Environment (build 1.7.0_60-b19)" }, { "code": null, "e": 19478, "s": 19414, "text": "Java Hotspot (TM) 64-bit Server VM (build 24.60-b09,mixed mode)" }, { "code": null, "e": 19510, "s": 19478, "text": "Open command terminal and type:" }, { "code": null, "e": 19525, "s": 19510, "text": "$java –version" }, { "code": null, "e": 19549, "s": 19525, "text": "java version \"1.7.0_25\"" }, { "code": null, "e": 19607, "s": 19549, "text": "Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)" }, { "code": null, "e": 19662, "s": 19607, "text": "Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)" }, { "code": null, "e": 19759, "s": 19662, "text": "We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system." }, { "code": null, "e": 19856, "s": 19759, "text": "We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system." }, { "code": null, "e": 20014, "s": 19856, "text": "In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed." }, { "code": null, "e": 20172, "s": 20014, "text": "In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed." }, { "code": null, "e": 20305, "s": 20172, "text": "Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example," }, { "code": null, "e": 20372, "s": 20305, "text": "Append the full path of Java compiler location to the System Path." }, { "code": null, "e": 20450, "s": 20372, "text": "Execute the command java -version from the command prompt as explained above." }, { "code": null, "e": 20736, "s": 20450, "text": "You can go through the JPA installation by using any of the JPA Providers from this tutorial, e.g., Eclipselink, Hibernate. Let us follow the JPA installation using Eclipselink. For JPA programming, we require to follow the specific folder framework, therefore it is better to use IDE." }, { "code": null, "e": 20879, "s": 20736, "text": "Download Eclipse IDE form following link https://www.eclipse.org/downloads/ Choose the EclipseIDE for JavaEE developer that is Eclipse indigo." }, { "code": null, "e": 20936, "s": 20879, "text": "Unzip the Eclipse zip file in C drive. Open Eclipse IDE." }, { "code": null, "e": 21092, "s": 20936, "text": "Eclipselink is a library therefore we cannot add it directly to Eclipse IDE. For installing JPA using Eclipselink you need to follow the steps given below." }, { "code": null, "e": 21185, "s": 21092, "text": "Create a new JPA project by selecting File->New->JPA Project in the Eclipse IDE as follows:\n" }, { "code": null, "e": 21277, "s": 21185, "text": "Create a new JPA project by selecting File->New->JPA Project in the Eclipse IDE as follows:" }, { "code": null, "e": 21416, "s": 21277, "text": "You will get a dialog box named New JPA Project. Enter project name tutorialspoint_JPA_Eclipselink, check the jre version and click next:\n" }, { "code": null, "e": 21554, "s": 21416, "text": "You will get a dialog box named New JPA Project. Enter project name tutorialspoint_JPA_Eclipselink, check the jre version and click next:" }, { "code": null, "e": 21643, "s": 21554, "text": "Click on download library (if you do not have the library) in the user library section.\n" }, { "code": null, "e": 21731, "s": 21643, "text": "Click on download library (if you do not have the library) in the user library section." }, { "code": null, "e": 21843, "s": 21731, "text": "Select the latest version of Eclipselink library in the Download library dialog box and click next as follows:\n" }, { "code": null, "e": 21954, "s": 21843, "text": "Select the latest version of Eclipselink library in the Download library dialog box and click next as follows:" }, { "code": null, "e": 22022, "s": 21954, "text": "Accept the terms of license and click finish for download library.\n" }, { "code": null, "e": 22089, "s": 22022, "text": "Accept the terms of license and click finish for download library." }, { "code": null, "e": 22153, "s": 22089, "text": "6.\tDownloading starts as is shown in the following screenshot.\n" }, { "code": null, "e": 22216, "s": 22153, "text": "6.\tDownloading starts as is shown in the following screenshot." }, { "code": null, "e": 22312, "s": 22216, "text": "After downloading, select the downloaded library in the user library section and click finish.\n" }, { "code": null, "e": 22407, "s": 22312, "text": "After downloading, select the downloaded library in the user library section and click finish." }, { "code": null, "e": 22555, "s": 22407, "text": "Finally you get the project file in the Package Explorer in Eclipse IDE. Extract all files, you will get the folder and file hierarchy as follows:\n" }, { "code": null, "e": 22702, "s": 22555, "text": "Finally you get the project file in the Package Explorer in Eclipse IDE. Extract all files, you will get the folder and file hierarchy as follows:" }, { "code": null, "e": 22888, "s": 22702, "text": "Any example that we discuss here requires database connectivity. Let us consider MySQL database for database operations. It requires mysql-connector jar to interact with a Java program." }, { "code": null, "e": 22952, "s": 22888, "text": "Follow the steps to configure the database jar in your project." }, { "code": null, "e": 23112, "s": 22952, "text": "Go to Project properties -> Java Build Path by right click on it. You will get a dialog box as shown in the following screen-shot. Click on Add External Jars.\n" }, { "code": null, "e": 23271, "s": 23112, "text": "Go to Project properties -> Java Build Path by right click on it. You will get a dialog box as shown in the following screen-shot. Click on Add External Jars." }, { "code": null, "e": 23353, "s": 23271, "text": "Go to the jar location in your system memory, select the file and click on open.\n" }, { "code": null, "e": 23434, "s": 23353, "text": "Go to the jar location in your system memory, select the file and click on open." }, { "code": null, "e": 23577, "s": 23434, "text": "Click ok on properties dialog. You will get the MySQL-connector Jar into your project. Now you are able to do database operations using MySQL." }, { "code": null, "e": 23720, "s": 23577, "text": "Click ok on properties dialog. You will get the MySQL-connector Jar into your project. Now you are able to do database operations using MySQL." }, { "code": null, "e": 24000, "s": 23720, "text": "This chapter uses a simple example to demonstrate how JPA works. Let us consider Employee Management as an example. Suppose the Employee Management creates, updates, finds, and deletes the records of an employee. As mentioned, we are using MySQL database for database operations." }, { "code": null, "e": 24050, "s": 24000, "text": "The main modules for this example are as follows:" }, { "code": null, "e": 24078, "s": 24050, "text": "Model or POJO\nEmployee.java" }, { "code": null, "e": 24092, "s": 24078, "text": "Model or POJO" }, { "code": null, "e": 24106, "s": 24092, "text": "Employee.java" }, { "code": null, "e": 24134, "s": 24106, "text": "Persistence\nPersistence.xml" }, { "code": null, "e": 24146, "s": 24134, "text": "Persistence" }, { "code": null, "e": 24162, "s": 24146, "text": "Persistence.xml" }, { "code": null, "e": 24258, "s": 24162, "text": "Service\nCreatingEmployee.java\nUpdatingEmployee.java\nFindingEmployee.java\nDeletingEmployee.java\n" }, { "code": null, "e": 24266, "s": 24258, "text": "Service" }, { "code": null, "e": 24288, "s": 24266, "text": "CreatingEmployee.java" }, { "code": null, "e": 24310, "s": 24288, "text": "UpdatingEmployee.java" }, { "code": null, "e": 24331, "s": 24310, "text": "FindingEmployee.java" }, { "code": null, "e": 24353, "s": 24331, "text": "DeletingEmployee.java" }, { "code": null, "e": 24502, "s": 24353, "text": "Let us take the package hierarchy which we have used in the JPA installation with Eclipselink. Follow the hierarchy for this example as shown below:" }, { "code": null, "e": 24755, "s": 24502, "text": "Entities are nothing but beans or models. In this example, we will use Employee as an entity. eid, ename, salary, and deg are the attributes of this entity. It contains a default constructor as well as the setter and getter methods of those attributes." }, { "code": null, "e": 24946, "s": 24755, "text": "In the above shown hierarchy, create a package named ‘com.tutorialspoint.eclipselink.entity’, under ‘src’ (Source) package. Create a class named Employee.java under given package as follows:" }, { "code": null, "e": 26154, "s": 24946, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table\npublic class Employee \n{\n\t@Id\n\t@GeneratedValue(strategy= GenerationType.AUTO) \t\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\tpublic Employee(int eid, String ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\t\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n public String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Employee [eid=\" + eid + \", ename=\" + ename + \", salary=\"\n\t\t\t\t+ salary + \", deg=\" + deg + \"]\";\n\t}\n}" }, { "code": null, "e": 26240, "s": 26154, "text": "In the above code, we have used @Entity annotation to make this POJO class an entity." }, { "code": null, "e": 26427, "s": 26240, "text": "Before going to next module we need to create database for relational entity, which will register the database in persistence.xml file. Open MySQL workbench and type hte following query." }, { "code": null, "e": 26459, "s": 26427, "text": "create database jpadb\nuse jpadb" }, { "code": null, "e": 26592, "s": 26459, "text": "This module plays a crucial role in the concept of JPA. In this xml file we will register the database and specify the entity class." }, { "code": null, "e": 26687, "s": 26592, "text": "In the above shown package hierarchy, persistence.xml under JPA Content package is as follows:" }, { "code": null, "e": 27746, "s": 26687, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n \t<class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\t<properties>\n\t <property name=\"javax.persistence.jdbc.url\"\n value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n \t <property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t <property name=\"javax.persistence.jdbc.password\" value=\"root\"/>\n\t <property name=\"javax.persistence.jdbc.driver\"\n value=\"com.mysql.jdbc.Driver\"/>\n <property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t <property name=\"eclipselink.ddl-generation\" \n\t\t value=\"create-tables\"/>\n\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 28138, "s": 27746, "text": "In the above xml, <persistence-unit> tag is defined with a specific name for JPA persistence. The <class> tag defines entity class with package name. The <properties> tag defines all the properties, and <property> tag defines each property such as database registration, URL specification, username, and password. These are the Eclipselink properties. This file will configure the database." }, { "code": null, "e": 28326, "s": 28138, "text": "Persistence operations are used for interacting with a database and they are load and store operations. In a business component, all the persistence operations fall under service classes." }, { "code": null, "e": 28620, "s": 28326, "text": "In the above shown package hierarchy, create a package named ‘com.tutorialspoint.eclipselink.service’, under ‘src’ (source) package. All the service classes named as CreateEmloyee.java, UpdateEmployee.java, FindEmployee.java, and DeleteEmployee.java. comes under the given package as follows:" }, { "code": null, "e": 28712, "s": 28620, "text": "The following code segment shows how to create an Employee class named CreateEmployee.java." }, { "code": null, "e": 29549, "s": 28712, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class CreateEmployee \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\tEmployee employee = new Employee( ); \n\t\temployee.setEid( 1201 );\n\t\temployee.setEname( \"Gopal\" );\n\t\temployee.setSalary( 40000 );\n\t\temployee.setDeg( \"Technical Manager\" );\n\t\tentitymanager.persist( employee );\n\t\tentitymanager.getTransaction( ).commit( );\n\t\t\n\t\tentitymanager.close( );\n\t\temfactory.close( );\n\t}\n}" }, { "code": null, "e": 29997, "s": 29549, "text": "In the above code the createEntityManagerFactory () creates a persistence unit by providing the same unique name which we provide for persistence-unit in persistent.xml file. The entitymanagerfactory object will create the entitymanger instance by using createEntityManager () method. The entitymanager object creates entitytransaction instance for transaction management. By using entitymanager object, we can persist entities into the database." }, { "code": null, "e": 30139, "s": 29997, "text": "After compilation and execution of the above program you will get notifications from eclipselink library on the console panel of eclipse IDE." }, { "code": null, "e": 30208, "s": 30139, "text": "For result, open the MySQL workbench and type the following queries." }, { "code": null, "e": 30241, "s": 30208, "text": "use jpadb\nselect * from employee" }, { "code": null, "e": 30330, "s": 30241, "text": "The effected database table named employee will be shown in a tabular format as follows:" }, { "code": null, "e": 30538, "s": 30330, "text": "To update the records of an employee, we need to retrieve the existing records form the database, make changes, and finally commit it to the database. The class named UpdateEmployee.java is shown as follows:" }, { "code": null, "e": 31369, "s": 30538, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class UpdateEmployee \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\t\t\tentitymanager.getTransaction( ).begin( );\n\t\tEmployee employee=entitymanager.\n\t\t\t\tfind( Employee.class, 1201 );\n\t\t//before update\n\t\tSystem.out.println( employee );\n\t\temployee.setSalary( 46000 );\n\t\tentitymanager.getTransaction( ).commit( );\n //after update\n\t\tSystem.out.println( employee );\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 31511, "s": 31369, "text": "After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE." }, { "code": null, "e": 31580, "s": 31511, "text": "For result, open the MySQL workbench and type the following queries." }, { "code": null, "e": 31613, "s": 31580, "text": "use jpadb\nselect * from employee" }, { "code": null, "e": 31702, "s": 31613, "text": "The effected database table named employee will be shown in a tabular format as follows:" }, { "code": null, "e": 31752, "s": 31702, "text": "The salary of employee, 1201 is updated to 46000." }, { "code": null, "e": 31944, "s": 31752, "text": "To find the records of an employee, we will have to retrieve the existing data from the database and display it. In this operation, EntityTransaction is not applied while retrieving a record." }, { "code": null, "e": 31990, "s": 31944, "text": "The class named FindEmployee.java as follows." }, { "code": null, "e": 32802, "s": 31990, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class FindEmployee \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence\n\t\t\t\t.createEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager();\n\t\tEmployee employee = entitymanager.\n\t\t\t\tfind( Employee.class, 1201 );\n\t\t\n\t\tSystem.out.println(\"employee ID = \"+employee.getEid( ));\n\t\tSystem.out.println(\"employee NAME = \"+employee.getEname( ));\n\t\tSystem.out.println(\"employee SALARY = \"+employee.getSalary( ));\n\t\tSystem.out.println(\"employee DESIGNATION = \"+employee.getDeg( ));\n\t}\n}" }, { "code": null, "e": 32951, "s": 32802, "text": "After compiling and executing the above program, you will get the following output from the Eclipselink library on the console panel of eclipse IDE." }, { "code": null, "e": 33059, "s": 32951, "text": "employee ID = 1201\nemployee NAME = Gopal\nemployee SALARY = 46000.0\nemployee DESIGNATION = Technical Manager" }, { "code": null, "e": 33205, "s": 33059, "text": "To delete the records of an employee, first we will find the existing records and then delete it. Here EntityTransaction plays an important role." }, { "code": null, "e": 33253, "s": 33205, "text": "The class named DeleteEmployee.java as follows:" }, { "code": null, "e": 33980, "s": 33253, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class DeleteEmployee \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\tEmployee employee=entitymanager.\n\t\t\t\tfind( Employee.class, 1201 );\n\t\tentitymanager.remove( employee );\n\t\tentitymanager.getTransaction( ).commit( );\n\t\tentitymanager.close( );\n\t\temfactory.close( );\n\t}\n}" }, { "code": null, "e": 34122, "s": 33980, "text": "After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE." }, { "code": null, "e": 34191, "s": 34122, "text": "For result, open the MySQL workbench and type the following queries." }, { "code": null, "e": 34224, "s": 34191, "text": "use jpadb\nselect * from employee" }, { "code": null, "e": 34285, "s": 34224, "text": "The effected database named employee will have null records." }, { "code": null, "e": 34387, "s": 34285, "text": "After completion of all the modules in this example, the package and file hierarchy looks as follows:" }, { "code": null, "e": 34572, "s": 34387, "text": "This chapter describes about JPQL and how it works with persistence units. In this chapter, the given examples follow the same package hierarchy, which we used in the previous chapter." }, { "code": null, "e": 34784, "s": 34572, "text": "JPQL stands for Java Persistence Query Language. It is used to create queries against entities to store in a relational database. JPQL is developed based on SQL syntax. But it won’t affect the database directly." }, { "code": null, "e": 34887, "s": 34784, "text": "JPQL can retrieve data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause." }, { "code": null, "e": 35149, "s": 34887, "text": "JPQL syntax is very similar to the syntax of SQL. Having SQL like syntax is an advantage because SQL is simple and being widely used. SQL works directly against relational database tables, records, and fields, whereas JPQL works with Java classes and instances." }, { "code": null, "e": 35301, "s": 35149, "text": "For example, a JPQL query can retrieve an entity object rather than field result set from a database, as with SQL. The JPQL query structure as follows." }, { "code": null, "e": 35376, "s": 35301, "text": "SELECT ... FROM ...\n[WHERE ...]\n[GROUP BY ... [HAVING ...]]\n[ORDER BY ...]" }, { "code": null, "e": 35440, "s": 35376, "text": "The structure of JPQL DELETE and UPDATE queries are as follows." }, { "code": null, "e": 35501, "s": 35440, "text": "DELETE FROM ... [WHERE ...]\n \nUPDATE ... SET ... [WHERE ...]" }, { "code": null, "e": 35646, "s": 35501, "text": "Scalar functions return resultant values based on input values. Aggregate functions return the resultant values by calculating the input values." }, { "code": null, "e": 35813, "s": 35646, "text": "We will use the same example Employee Management as in the previous chapter. Here we will go through the service classes using scalar and aggregate functions of JPQL." }, { "code": null, "e": 35880, "s": 35813, "text": "Let us assume the jpadb.employee table contains following records." }, { "code": null, "e": 35999, "s": 35880, "text": "Create a class named ScalarandAggregateFunctions.java under com.tutorialspoint.eclipselink.service package as follows." }, { "code": null, "e": 36939, "s": 35999, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\npublic class ScalarandAggregateFunctions \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager();\n\t\t//Scalar function\n\t\tQuery query = entitymanager.\n\t\tcreateQuery(\"Select UPPER(e.ename) from Employee e\");\n\t\tList<String> list=query.getResultList();\n\t\t\n\t\tfor(String e:list)\n\t\t{\n\t\t\tSystem.out.println(\"Employee NAME :\"+e);\n\t\t}\n\t\t//Aggregate function\n\t\tQuery query1 = entitymanager.\n\t\t\t\tcreateQuery(\"Select MAX(e.salary) from Employee e\");\n\t\tDouble result=(Double) query1.getSingleResult();\n\t\tSystem.out.println(\"Max Employee Salary :\"+result);\n\t}\n}" }, { "code": null, "e": 37063, "s": 36939, "text": "After compilation and execution of the above program you will get the following output on the console panel of Eclipse IDE." }, { "code": null, "e": 37228, "s": 37063, "text": "Employee NAME :GOPAL\nEmployee NAME :MANISHA\nEmployee NAME :MASTHANVALI\nEmployee NAME :SATISH\nEmployee NAME :KRISHNA\nEmployee NAME :KIRAN\nax Employee Salary :40000.0" }, { "code": null, "e": 37337, "s": 37228, "text": "Between, And, and Like are the main keywords of JPQL. These keywords are used after Where clause in a query." }, { "code": null, "e": 37452, "s": 37337, "text": "Create a class named BetweenAndLikeFunctions.java under com.tutorialspoint.eclipselink.service package as follows:" }, { "code": null, "e": 38728, "s": 37452, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class BetweenAndLikeFunctions \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\tcreateEntityManager();\n\t\t//Between\n\t\tQuery query = entitymanager.\n\t\t\tcreateQuery( \"Select e \" +\n\t\t\t\t\t \"from Employee e \" +\n\t\t\t\t\t \"where e.salary \" +\n\t\t\t\t\t \"Between 30000 and 40000\" )\n\t\tList<Employee> list=(List<Employee>)query.getResultList( );\n\t\t \n\t\tfor( Employee e:list )\n\t\t{\n\t\t\tSystem.out.print(\"Employee ID :\"+e.getEid( ));\n\t\t\tSystem.out.println(\"\\t Employee salary :\"+e.getSalary( ));\n\t\t}\n\t\t\n\t\t//Like\n\t\tQuery query1 = entitymanager.\n\t\t\tcreateQuery(\"Select e \" +\n\t\t\t\t\t \"from Employee e \" +\n\t\t\t\t\t \"where e.ename LIKE 'M%'\");\n\t\tList<Employee> list1=(List<Employee>)query1.getResultList( );\n\t\tfor( Employee e:list1 )\n\t\t{\n\t\t\tSystem.out.print(\"Employee ID :\"+e.getEid( ));\n\t\t\tSystem.out.println(\"\\t Employee name :\"+e.getEname( ));\n\t\t}\n\t}\n}" }, { "code": null, "e": 38848, "s": 38728, "text": "After compiling and executing the above program, you will get the following output in the console panel of Eclipse IDE." }, { "code": null, "e": 39201, "s": 38848, "text": "Employee ID :1201\t Employee salary :40000.0\nEmployee ID :1202\t Employee salary :40000.0\nEmployee ID :1203\t Employee salary :40000.0\nEmployee ID :1204\t Employee salary :30000.0\nEmployee ID :1205\t Employee salary :30000.0\nEmployee ID :1206\t Employee salary :35000.0\n\nEmployee ID :1202\t Employee name :Manisha\nEmployee ID :1203\t Employee name :Masthanvali" }, { "code": null, "e": 39391, "s": 39201, "text": "To order the records in JPQL, we use the ORDER BY clause. The usage of this clause is same as in SQL, but it deals with entities. The following example shows how to use the ORDER BY clause." }, { "code": null, "e": 39485, "s": 39391, "text": "Create a class Ordering.java under com.tutorialspoint.eclipselink.service package as follows:" }, { "code": null, "e": 40364, "s": 39485, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class Ordering \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\tcreateEntityManager();\n\t\t//Between\n\t\tQuery query = entitymanager.\n\t\t\tcreateQuery( \"Select e \" +\n\t\t\t\t\t \"from Employee e \" +\n\t\t\t\t\t \"ORDER BY e.ename ASC\" );\n\t\tList<Employee> list=(List<Employee>)query.getResultList( );\n\t\t \n\t\tfor( Employee e:list )\n\t\t{\n\t\t\tSystem.out.print(\"Employee ID :\"+e.getEid( ));\n\t\t\tSystem.out.println(\"\\t Employee Name :\"+e.getEname( ));\n\t\t}\n\t}\n}" }, { "code": null, "e": 40481, "s": 40364, "text": "compiling and executing the above program you will produce the following output in the console panel of Eclipse IDE." }, { "code": null, "e": 40732, "s": 40481, "text": "Employee ID :1201\t Employee Name :Gopal\nEmployee ID :1206\t Employee Name :Kiran\nEmployee ID :1205\t Employee Name :Krishna\nEmployee ID :1202\t Employee Name :Manisha\nEmployee ID :1203\t Employee Name :Masthanvali\nEmployee ID :1204\t Employee Name :Satish" }, { "code": null, "e": 41108, "s": 40732, "text": "A @NamedQuery annotation is defined as a query with a predefined query string that is unchangeable. In contrast to dynamic queries, named queries may improve code organization by separating the JPQL query strings from POJO. It also passes the query parameters rather than embedding the literals dynamically into the query string and therefore produces more efficient queries." }, { "code": null, "e": 41262, "s": 41108, "text": "First of all, add @NamedQuery annotation to the Employee entity class named Employee.java under com.tutorialspoint.eclipselink.entity package as follows:" }, { "code": null, "e": 42603, "s": 41262, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\n@Entity\n@Table\n@NamedQuery(query = \"Select e from Employee e where e.eid = :id\", \n\t\tname = \"find employee by id\")\npublic class Employee \n{\n\t@Id\n\t@GeneratedValue(strategy= GenerationType.AUTO) \t\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\tpublic Employee(int eid, String ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n\t\n\tpublic String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Employee [eid=\" + eid + \", ename=\" + ename + \", salary=\"\n\t\t\t\t+ salary + \", deg=\" + deg + \"]\";\n\t}\n}" }, { "code": null, "e": 42707, "s": 42603, "text": "Create a class named NamedQueries.java under com.tutorialspoint.eclipselink.service package as follows:" }, { "code": null, "e": 43541, "s": 42707, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class NamedQueries \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\tcreateEntityManager();\n\t\tQuery query = entitymanager.createNamedQuery(\n\t\t\t\"find employee by id\");\n\t\tquery.setParameter(\"id\", 1204);\n\t\tList<Employee> list = query.getResultList( );\n\t\tfor( Employee e:list )\n\t\t{\n\t\t\tSystem.out.print(\"Employee ID :\"+e.getEid( ));\n\t\t\tSystem.out.println(\"\\t Employee Name :\"+e.getEname( ));\n\t\t}\n\t}\n}" }, { "code": null, "e": 43663, "s": 43541, "text": "After compiling and executing of the above program you will get the following output in the console panel of Eclipse IDE." }, { "code": null, "e": 43704, "s": 43663, "text": "Employee ID :1204\t Employee Name :Satish" }, { "code": null, "e": 43779, "s": 43704, "text": "After adding all the above classes the package hierarchy looks as follows:" }, { "code": null, "e": 44058, "s": 43779, "text": "The most important concept of JPA is to make a duplicate copy of the database in the cache memory. While transacting with a database, the JPA first creates a duplicate set of data and only when it is committed using an entity manager, the changes are effected into the database." }, { "code": null, "e": 44116, "s": 44058, "text": "There are two ways of fetching records from the database." }, { "code": null, "e": 44220, "s": 44116, "text": "In eager fetching, related child objects are uploaded automatically while fetching a particular record." }, { "code": null, "e": 44494, "s": 44220, "text": "In lazy fetching, related objects are not uploaded automatically unless you specifically request for them. First of all, it checks the availability of related objects and notifies. Later, if you call any of the getter method of that entity, then it fetches all the records." }, { "code": null, "e": 44691, "s": 44494, "text": "Lazy fetch is possible when you try to fetch the records for the first time. That way, a copy of the whole record is already stored in the cache memory. Performance-wise, lazy fetch is preferable." }, { "code": null, "e": 44994, "s": 44691, "text": "JPA is a library which is released with Java specifications. Therefore, it supports all the object-oriented concepts for entity persistence. Till now, we are done with the basics of object relational mapping. This chapter takes you through the advanced mappings between objects and relational entities." }, { "code": null, "e": 45247, "s": 44994, "text": "Inheritance is the core concept of any object-oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies: SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS." }, { "code": null, "e": 45392, "s": 45247, "text": "Let us consider an example. The following diagram shows three classes, viz. Staff, TeachingStaff, and NonTeachingStaff, and their relationships." }, { "code": null, "e": 45599, "s": 45392, "text": "In the above diagram, Staff is an entity, while TeachingStaff and NonTeachingStaff are the sub-entities of Staff. Here we will use the above example to demonstrate all three three strategies of inheritance." }, { "code": null, "e": 45853, "s": 45599, "text": "Single-table strategy takes all classes fields (both super and sub classes) and map them down into a single table known as SINGLE_TABLE strategy. Here the discriminator value plays a key role in differentiating the values of three entities in one table." }, { "code": null, "e": 46209, "s": 45853, "text": "Let us consider the above example. TeachingStaff and NonTeachingStaff are the sub-classes of Staff. As per the concept of inheritance, a sub-class inherits the properties of its super-class. Therefore sid and sname are the fields that belong to both TeachingStaff and NonTeachingStaff. Create a JPA project. All the modules of this project are as follows:" }, { "code": null, "e": 46399, "s": 46209, "text": "Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:" }, { "code": null, "e": 47380, "s": 46399, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.io.Serializable;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n@Entity\n@Table\n@Inheritance( strategy = InheritanceType.SINGLE_TABLE )\n@DiscriminatorColumn( name=\"type\" )\npublic class Staff implements Serializable \n{\n\t@Id\n\t@GeneratedValue( strategy = GenerationType.AUTO )\n\tprivate int sid;\n\tprivate String sname;\n\tpublic Staff( int sid, String sname ) \n\t{\n\t\tsuper( );\n\t\tthis.sid = sid;\n\t\tthis.sname = sname;\n\t}\n\tpublic Staff( ) \n\t{\n\t\tsuper( );\n\t}\n\tpublic int getSid( ) \n\t{\n\t\treturn sid;\n\t}\n\tpublic void setSid( int sid ) \n\t{\n\t\tthis.sid = sid;\n\t}\n\tpublic String getSname( ) \n\t{\n\t\treturn sname;\n\t}\n\tpublic void setSname( String sname ) \n\t{\n\t\tthis.sname = sname;\n\t}\n}" }, { "code": null, "e": 47525, "s": 47380, "text": "In the above code @DescriminatorColumn specifies the field name (type) and its values show the remaining (Teaching and NonTeachingStaff) fields." }, { "code": null, "e": 47700, "s": 47525, "text": "Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:" }, { "code": null, "e": 48586, "s": 47700, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@DiscriminatorValue( value=\"TS\" )\npublic class TeachingStaff extends Staff \n{\n\tprivate String qualification;\n\tprivate String subjectexpertise;\n\t\n\tpublic TeachingStaff( int sid, String sname, \n\t\t\tString qualification,String subjectexpertise ) \n\t{\n\t\tsuper( sid, sname );\n\t\tthis.qualification = qualification;\n\t\tthis.subjectexpertise = subjectexpertise;\n\t}\n\t\n\tpublic TeachingStaff( ) \n\t{\n\t\tsuper( );\n\t}\n\n\tpublic String getQualification( )\n\t{\n\t\treturn qualification;\n\t}\n\n\tpublic void setQualification( String qualification )\n\t{\n\t\tthis.qualification = qualification;\n\t}\n\n\tpublic String getSubjectexpertise( ) \n\t{\n\t\treturn subjectexpertise;\n\t}\n\n\tpublic void setSubjectexpertise( String subjectexpertise )\n\t{\n\t\tthis.subjectexpertise = subjectexpertise;\n\t}\n}" }, { "code": null, "e": 48767, "s": 48586, "text": "Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:" }, { "code": null, "e": 49377, "s": 48767, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@DiscriminatorValue( value = \"NS\" )\npublic class NonTeachingStaff extends Staff \n{\n\tprivate String areaexpertise;\n\n\tpublic NonTeachingStaff( int sid, String sname, \n\t\t\tString areaexpertise ) \n\t{\n\t\tsuper( sid, sname );\n\t\tthis.areaexpertise = areaexpertise;\n\t}\n\n\tpublic NonTeachingStaff( ) \n\t{\n\t\tsuper( );\n\t}\n\n\tpublic String getAreaexpertise( ) \n\t{\n\t\treturn areaexpertise;\n\t}\n\n\tpublic void setAreaexpertise( String areaexpertise )\n\t{\n\t\tthis.areaexpertise = areaexpertise;\n\t}\n}" }, { "code": null, "e": 49530, "s": 49377, "text": "Persistence.xml contains the configuration information of database and the registration information of entity classes. The xml file is shown as follows:" }, { "code": null, "e": 50742, "s": 49530, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t <class>com.tutorialspoint.eclipselink.entity.Staff</class>\n\t\t<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>\n\t\t<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 50894, "s": 50742, "text": "Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’." }, { "code": null, "e": 51063, "s": 50894, "text": "Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:" }, { "code": null, "e": 52265, "s": 51063, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.NonTeachingStaff;\nimport com.tutorialspoint.eclipselink.entity.TeachingStaff;\n\npublic class SaveClient \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Teaching staff entity \n\t\tTeachingStaff ts1=new TeachingStaff(\n\t\t\t\t1,\"Gopal\",\"MSc MEd\",\"Maths\");\n\t\tTeachingStaff ts2=new TeachingStaff(\n\t\t\t\t2, \"Manisha\", \"BSc BEd\", \"English\");\n\t\t//Non-Teaching Staff entity\n\t\tNonTeachingStaff nts1=new NonTeachingStaff(\n\t\t\t\t3, \"Satish\", \"Accounts\");\n\t\tNonTeachingStaff nts2=new NonTeachingStaff(\n\t\t\t\t4, \"Krishna\", \"Office Admin\");\n\t\t\n\t\t//storing all entities\n\t\tentitymanager.persist(ts1);\n\t\tentitymanager.persist(ts2);\n\t\tentitymanager.persist(nts1);\n\t\tentitymanager.persist(nts2);\n\t\tentitymanager.getTransaction().commit();\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 52463, "s": 52265, "text": "After compiling and executing the above program you will get notifications on the console panel of Eclipse IDE. Check MySQL workbench for output. The output in a tabular format is shown as follows:" }, { "code": null, "e": 52593, "s": 52463, "text": "Finally you will get a single table containing the field of all the three classes with a discriminator column named Type (field)." }, { "code": null, "e": 52766, "s": 52593, "text": "Joined table strategy is to share the referenced column that contains unique values to join the table and make easy transactions. Let us consider the same example as above." }, { "code": null, "e": 52829, "s": 52766, "text": "Create a JPA Project. All the project modules are shown below." }, { "code": null, "e": 53019, "s": 52829, "text": "Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:" }, { "code": null, "e": 53913, "s": 53019, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.io.Serializable;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n@Entity\n@Table\n@Inheritance( strategy = InheritanceType.JOINED )\npublic class Staff implements Serializable \n{\n\t@Id\n\t@GeneratedValue( strategy = GenerationType.AUTO )\n\tprivate int sid;\n\tprivate String sname;\n\tpublic Staff( int sid, String sname ) \n\t{\n\t\tsuper( );\n\t\tthis.sid = sid;\n\t\tthis.sname = sname;\n\t}\n\tpublic Staff( ) \n\t{\n\t\tsuper( );\n\t}\n\tpublic int getSid( ) \n\t{\n\t\treturn sid;\n\t}\n\tpublic void setSid( int sid ) \n\t{\n\t\tthis.sid = sid;\n\t}\n\tpublic String getSname( ) \n\t{\n\t\treturn sname;\n\t}\n\tpublic void setSname( String sname ) \n\t{\n\t\tthis.sname = sname;\n\t}\n}" }, { "code": null, "e": 54088, "s": 53913, "text": "Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:" }, { "code": null, "e": 54993, "s": 54088, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@PrimaryKeyJoinColumn(referencedColumnName=\"sid\")\npublic class TeachingStaff extends Staff \n{\n\tprivate String qualification;\n\tprivate String subjectexpertise;\n\t\n\tpublic TeachingStaff( int sid, String sname, \n\t\t\tString qualification,String subjectexpertise ) \n\t{\n\t\tsuper( sid, sname );\n\t\tthis.qualification = qualification;\n\t\tthis.subjectexpertise = subjectexpertise;\n\t}\n\t\n\tpublic TeachingStaff( ) \n\t{\n\t\tsuper( );\n\t\t\n\t}\n\n\tpublic String getQualification( )\n\t{\n\t\treturn qualification;\n\t}\n\n\tpublic void setQualification( String qualification )\n\t{\n\t\tthis.qualification = qualification;\n\t}\n\n\tpublic String getSubjectexpertise( ) \n\t{\n\t\treturn subjectexpertise;\n\t}\n\n\tpublic void setSubjectexpertise( String subjectexpertise )\n\t{\n\t\tthis.subjectexpertise = subjectexpertise;\n\t}\n}" }, { "code": null, "e": 55174, "s": 54993, "text": "Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:" }, { "code": null, "e": 55798, "s": 55174, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@PrimaryKeyJoinColumn(referencedColumnName=\"sid\")\npublic class NonTeachingStaff extends Staff \n{\n\tprivate String areaexpertise;\n\n\tpublic NonTeachingStaff( int sid, String sname, \n\t\t\tString areaexpertise ) \n\t{\n\t\tsuper( sid, sname );\n\t\tthis.areaexpertise = areaexpertise;\n\t}\n\n\tpublic NonTeachingStaff( ) \n\t{\n\t\tsuper( );\n\t}\n\n\tpublic String getAreaexpertise( ) \n\t{\n\t\treturn areaexpertise;\n\t}\n\n\tpublic void setAreaexpertise( String areaexpertise )\n\t{\n\t\tthis.areaexpertise = areaexpertise;\n\t}\n}" }, { "code": null, "e": 55960, "s": 55798, "text": "Persistence.xml file contains the configuration information of the database and the registration information of entity classes. The xml file is shown as follows:" }, { "code": null, "e": 57166, "s": 55960, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Staff</class>\n\t<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>\n\t<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 57318, "s": 57166, "text": "Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’." }, { "code": null, "e": 57491, "s": 57318, "text": "Create a class named SaveClient.java under the given package to store fields of Staff, TeachingStaff, and NonTeachingStaff class. Then SaveClient class is shown as follows:" }, { "code": null, "e": 58694, "s": 57491, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.NonTeachingStaff;\nimport com.tutorialspoint.eclipselink.entity.TeachingStaff;\n\npublic class SaveClient \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Teaching staff entity \n\t\tTeachingStaff ts1=new TeachingStaff(\n\t\t\t\t1,\"Gopal\",\"MSc MEd\",\"Maths\");\n\t\tTeachingStaff ts2=new TeachingStaff(\n\t\t\t\t2, \"Manisha\", \"BSc BEd\", \"English\");\n\t\t//Non-Teaching Staff entity\n\t\tNonTeachingStaff nts1=new NonTeachingStaff(\n\t\t\t\t3, \"Satish\", \"Accounts\");\n\t\tNonTeachingStaff nts2=new NonTeachingStaff(\n\t\t4, \"Krishna\", \"Office Admin\");\n\t\t\n\t\t//storing all entities\n\t\tentitymanager.persist(ts1);\n\t\tentitymanager.persist(ts2);\n\t\tentitymanager.persist(nts1);\n\t\tentitymanager.persist(nts2);\n\t\t\n\t\tentitymanager.getTransaction().commit();\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 58841, "s": 58694, "text": "After compiling and executing the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench." }, { "code": null, "e": 58935, "s": 58841, "text": "Here three tables are created and the result of staff table is displayed in a tabular format." }, { "code": null, "e": 58994, "s": 58935, "text": "The result of TeachingStaff table is displayed as follows:" }, { "code": null, "e": 59133, "s": 58994, "text": "In the above table sid is the foreign key (reference field form staff table) The result of NonTeachingStaff table is displayed as follows:" }, { "code": null, "e": 59388, "s": 59133, "text": "Finally, the three tables are created using their respective fields and the SID field is shared by all the three tables. In the Staff table, SID is the primary key. In the remaining two tables (TeachingStaff and NonTeachingStaff), SID is the foreign key." }, { "code": null, "e": 59619, "s": 59388, "text": "Table per class strategy is to create a table for each sub-entity. The Staff table will be created, but it will contain null values. The field values of Staff table must be shared by both TeachingStaff and NonTeachingStaff tables." }, { "code": null, "e": 59662, "s": 59619, "text": "Let us consider the same example as above." }, { "code": null, "e": 59852, "s": 59662, "text": "Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:" }, { "code": null, "e": 60755, "s": 59852, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.io.Serializable;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n@Entity\n@Table\n@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )\npublic class Staff implements Serializable \n{\n\t@Id\n\t@GeneratedValue( strategy = GenerationType.AUTO )\n\tprivate int sid;\n\tprivate String sname;\n\tpublic Staff( int sid, String sname ) \n\t{\n\t\tsuper( );\n\t\tthis.sid = sid;\n\t\tthis.sname = sname;\n\t}\n\tpublic Staff( ) \n\t{\n\t\tsuper( );\n\t}\n\tpublic int getSid( ) \n\t{\n\t\treturn sid;\n\t}\n\tpublic void setSid( int sid ) \n\t{\n\t\tthis.sid = sid;\n\t}\n\tpublic String getSname( ) \n\t{\n\t\treturn sname;\n\t}\n\tpublic void setSname( String sname ) \n\t{\n\t\tthis.sname = sname;\n\t}\n}" }, { "code": null, "e": 60930, "s": 60755, "text": "Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:" }, { "code": null, "e": 61784, "s": 60930, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\npublic class TeachingStaff extends Staff \n{\n\tprivate String qualification;\n\tprivate String subjectexpertise;\n\t\n\tpublic TeachingStaff( int sid, String sname, \n\t\t\tString qualification,String subjectexpertise ) \n\t{\n\t\tsuper( sid, sname );\n\t\tthis.qualification = qualification;\n\t\tthis.subjectexpertise = subjectexpertise;\n\t}\n\t\n\tpublic TeachingStaff( ) \n\t{\n\t\tsuper( );\n\t\t\n\t}\n\n\tpublic String getQualification( )\n\t{\n\t\treturn qualification;\n\t}\n\tpublic void setQualification( String qualification )\n\t{\n\t\tthis.qualification = qualification;\n\t}\n\n\tpublic String getSubjectexpertise( ) \n\t{\n\t\treturn subjectexpertise;\n\t}\n\n\tpublic void setSubjectexpertise( String subjectexpertise )\n\t{\n\t\tthis.subjectexpertise = subjectexpertise;\n\t}\n}" }, { "code": null, "e": 61965, "s": 61784, "text": "Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:" }, { "code": null, "e": 62540, "s": 61965, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\npublic class NonTeachingStaff extends Staff \n{\n\tprivate String areaexpertise;\n\n\tpublic NonTeachingStaff( int sid, String sname, \n\t\t\tString areaexpertise )\n\t\t\t{\n\t\tsuper( sid, sname );\n\t\tthis.areaexpertise = areaexpertise;\n\t}\n\n\tpublic NonTeachingStaff( ) \n\t{\n\t\tsuper( );\n\t}\n\n\tpublic String getAreaexpertise( ) \n\t{\n\t\treturn areaexpertise;\n\t}\n\n\tpublic void setAreaexpertise( String areaexpertise )\n\t{\n\t\tthis.areaexpertise = areaexpertise;\n\t}\n}" }, { "code": null, "e": 62694, "s": 62540, "text": "Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:" }, { "code": null, "e": 63901, "s": 62694, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Staff</class>\n\t<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>\n\t<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n value=\"create-tables\"/>\n\t\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 64053, "s": 63901, "text": "Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’." }, { "code": null, "e": 64222, "s": 64053, "text": "Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:" }, { "code": null, "e": 65426, "s": 64222, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.NonTeachingStaff;\nimport com.tutorialspoint.eclipselink.entity.TeachingStaff;\npublic class SaveClient \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Teaching staff entity \n\t\tTeachingStaff ts1=new TeachingStaff(\n\t\t\t\t1,\"Gopal\",\"MSc MEd\",\"Maths\");\n\t\tTeachingStaff ts2=new TeachingStaff(\n\t\t\t\t2, \"Manisha\", \"BSc BEd\", \"English\");\n\t\t//Non-Teaching Staff entity\n\t\tNonTeachingStaff nts1=new NonTeachingStaff(\n\t\t\t\t3, \"Satish\", \"Accounts\");\n\t\tNonTeachingStaff nts2=new NonTeachingStaff(\n\t\t\t\t4, \"Krishna\", \"Office Admin\");\n\t\t\n\t\t//storing all entities\n\t\tentitymanager.persist(ts1);\n\t\tentitymanager.persist(ts2);\n\t\tentitymanager.persist(nts1);\n\t\tentitymanager.persist(nts2);\n\t\t\n\t\tentitymanager.getTransaction().commit();\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 65574, "s": 65426, "text": "After compiling and executing the above program, you will get notifications on the console panel of Eclipse IDE. For output, check MySQL workbench." }, { "code": null, "e": 65651, "s": 65574, "text": "Here the three tables are created and the Staff table contains null records." }, { "code": null, "e": 65704, "s": 65651, "text": "The result of TeachingStaff is displayed as follows:" }, { "code": null, "e": 65792, "s": 65704, "text": "The above table TeachingStaff contains fields of both Staff and TeachingStaff Entities." }, { "code": null, "e": 65848, "s": 65792, "text": "The result of NonTeachingStaff is displayed as follows:" }, { "code": null, "e": 65942, "s": 65848, "text": "The above table NonTeachingStaff contains fields of both Staff and NonTeachingStaff Entities." }, { "code": null, "e": 66226, "s": 65942, "text": "This chapter takes you through the relationships between Entities. Generally the relations are more effective between tables in the database. Here the entity classes are treated as relational tables (concept of JPA), therefore the relationships between Entity classes are as follows:" }, { "code": null, "e": 66246, "s": 66226, "text": "@ManyToOne Relation" }, { "code": null, "e": 66266, "s": 66246, "text": "@OneToMany Relation" }, { "code": null, "e": 66285, "s": 66266, "text": "@OneToOne Relation" }, { "code": null, "e": 66306, "s": 66285, "text": "@ManyToMany Relation" }, { "code": null, "e": 66588, "s": 66306, "text": "Many-To-One relation between entities exists where one entity (column or set of columns) is referenced with another entity (column or set of columns) containing unique values. In relational databases, these relations are applied by using foreign key/primary key between the tables." }, { "code": null, "e": 66948, "s": 66588, "text": "Let us consider an example of a relation between Employee and Department entities. In unidirectional manner, i.e., from Employee to Department, Many-To-One relation is applicable. That means each record of employee contains one department id, which should be a primary key in the Department table. Here in the Employee table, Department id is the foreign Key." }, { "code": null, "e": 67025, "s": 66948, "text": "The following diagram shows the Many-To-One relation between the two tables." }, { "code": null, "e": 67141, "s": 67025, "text": "Create a JPA project in eclipse IDE named JPA_Eclipselink_MTO. All the modules of this project are discussed below." }, { "code": null, "e": 67385, "s": 67141, "text": "Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows:" }, { "code": null, "e": 67992, "s": 67385, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class Department \n{\n @Id \n @GeneratedValue( strategy=GenerationType.AUTO )\n private int id;\n private String name;\n\n public int getId() \n {\n \treturn id;\n }\n \n public void setId(int id) \n {\n \tthis.id = id;\n }\n \n public String getName( )\n {\n \treturn name;\n }\n \n public void setName( String deptName )\n {\n \tthis.name = deptName;\n }\n}" }, { "code": null, "e": 68180, "s": 67992, "text": "Create the second entity in this relation - Employee entity class named Employee.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows:" }, { "code": null, "e": 69442, "s": 68180, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToOne;\n\n@Entity\npublic class Employee \n{\n\t@Id\n\t@GeneratedValue( strategy= GenerationType.AUTO ) \t\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\t@ManyToOne\n\tprivate Department department;\n\t\n\tpublic Employee(int eid, \n\t\t\tString ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\t\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n\t\n\tpublic String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\n\t\t\n\tpublic Department getDepartment() {\n\t\treturn department;\n\t}\n\n\tpublic void setDepartment(Department department) {\n\t\tthis.department = department;\n\t}\n}" }, { "code": null, "e": 69541, "s": 69442, "text": "Persistence.xml file is required to configure the database and the registration of entity classes." }, { "code": null, "e": 69719, "s": 69541, "text": "Persitence.xml will be created by the eclipse IDE while creating a JPA Project. The configuration details are user specifications. The persistence.xml file is shown as follows: " }, { "code": null, "e": 70865, "s": 69719, "text": "\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" \n xmlns=\"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\t<class>com.tutorialspoint.eclipselink.entity.Department</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n\t\t\t value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\"\n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n\t\t\t value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n\t\t\t value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 71167, "s": 70865, "text": "This module contains the service classes, which implements the relational part using the attribute initialization. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named ManyToOne.java is created under given package. The DAO class is shown as follows:" }, { "code": null, "e": 72784, "s": 71167, "text": "package com.tutorialspointeclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Department;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class ManyToOne \n{\n\tpublic static void main( String[ ] args ) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Create Department Entity\n\t\tDepartment department = new Department();\n\t\tdepartment.setName(\"Development\");\n\t\t//Store Department\n\t\tentitymanager.persist(department);\n\t\t\n\t\t//Create Employee1 Entity\n\t\tEmployee employee1 = new Employee();\n\t\temployee1.setEname(\"Satish\");\n\t\temployee1.setSalary(45000.0);\n\t\temployee1.setDeg(\"Technical Writer\");\n\t\temployee1.setDepartment(department);\n\n\t\t//Create Employee2 Entity\n\t\tEmployee employee2 = new Employee();\n\t\temployee2.setEname(\"Krishna\");\n\t\temployee2.setSalary(45000.0);\n\t\temployee2.setDeg(\"Technical Writer\");\n\t\temployee2.setDepartment(department);\n\n\t\t//Create Employee3 Entity\n\t\tEmployee employee3 = new Employee();\n\t\temployee3.setEname(\"Masthanvali\");\n\t\temployee3.setSalary(50000.0);\n\t\temployee3.setDeg(\"Technical Writer\");\n\t\temployee3.setDepartment(department);\n\t\t\n\t\t//Store Employees\n\t\tentitymanager.persist(employee1);\n\t\tentitymanager.persist(employee2);\n\t\tentitymanager.persist(employee3);\n\t\t\t\t\n\t\tentitymanager.getTransaction().commit();\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 72973, "s": 72784, "text": "After compiling and executing the above program, you will get notifications on the console panel of Eclipse IDE. For output, check MySQL workbench. In this example, two tables are created." }, { "code": null, "e": 73082, "s": 72973, "text": "Pass the following query in MySQL interface and the result of Department table will be displayed as follows:" }, { "code": null, "e": 73107, "s": 73082, "text": "Select * from department" }, { "code": null, "e": 73214, "s": 73107, "text": "Pass the following query in MySQL interface and the result of Employee table will be displayed as follows." }, { "code": null, "e": 73237, "s": 73214, "text": "Select * from employee" }, { "code": null, "e": 73333, "s": 73237, "text": "In the above table Deparment_Id is the foreign key (reference field) from the Department table." }, { "code": null, "e": 73632, "s": 73333, "text": "In this relationship, each row of one entity is referenced to many child records in other entity. The important thing is that child records cannot have multiple parents. In a one-to-many relationship between Table A and Table B, each row in Table A can be linked to one or multiple rows in Table B." }, { "code": null, "e": 73941, "s": 73632, "text": "Let us consider the above example. Suppose Employee and Department tables in the above example are connected in a reverse unidirectional manner, then the relation becomes One-To-Many relation. Create a JPA project in eclipse IDE named JPA_Eclipselink_OTM. All the modules of this project are discussed below." }, { "code": null, "e": 74185, "s": 73941, "text": "Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows:" }, { "code": null, "e": 75103, "s": 74185, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.util.List;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\n\n@Entity\npublic class Department \n{\n @Id \n @GeneratedValue( strategy=GenerationType.AUTO )\n private int id;\n private String name;\n \n @OneToMany( targetEntity=Employee.class )\n private List employeelist;\n\n public int getId() \n {\n \treturn id;\n }\n \n public void setId(int id) \n {\n \tthis.id = id;\n }\n \n public String getName( )\n {\n \treturn name;\n }\n \n public void setName( String deptName )\n {\n \tthis.name = deptName;\n }\n\n public List getEmployeelist() \n {\n\treturn employeelist;\n }\n\n public void setEmployeelist(List employeelist) \n {\n\tthis.employeelist = employeelist;\n }\n}" }, { "code": null, "e": 75291, "s": 75103, "text": "Create the second entity in this relation -Employee entity class, named Employee.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows:" }, { "code": null, "e": 76323, "s": 75291, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class Employee \n{\n\t@Id\n\t@GeneratedValue( strategy= GenerationType.AUTO ) \t\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\t\t\n\tpublic Employee(int eid, \n\t\t\tString ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\t\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n\t\n\tpublic String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\t\n}" }, { "code": null, "e": 76363, "s": 76323, "text": "The persistence.xml file is as follows:" }, { "code": null, "e": 77509, "s": 76363, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" \n xmlns=\"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\t<class>com.tutorialspoint.eclipselink.entity.Department</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n\t\t\t value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n\t\t\t value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n\t\t\t value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 77811, "s": 77509, "text": "This module contains the service classes, which implements the relational part using the attribute initialization. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named OneToMany.java is created under given package. The DAO class is shown as follows:" }, { "code": null, "e": 79564, "s": 77811, "text": "package com.tutorialspointeclipselink.service;\n\nimport java.util.List;\nimport java.util.ArrayList;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Department;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class OneToMany \n{\n\tpublic static void main(String[] args) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Create Employee1 Entity\n\t\tEmployee employee1 = new Employee();\n\t\temployee1.setEname(\"Satish\");\n\t\temployee1.setSalary(45000.0);\n\t\temployee1.setDeg(\"Technical Writer\");\n\t\t\t\t\t\t\t\t\n\t\t//Create Employee2 Entity\n\t\tEmployee employee2 = new Employee();\n\t\temployee2.setEname(\"Krishna\");\n\t\temployee2.setSalary(45000.0);\n\t\temployee2.setDeg(\"Technical Writer\");\n\t\t\t\t\t\t\t\t\n\t\t//Create Employee3 Entity\n\t\tEmployee employee3 = new Employee();\n\t\temployee3.setEname(\"Masthanvali\");\n\t\temployee3.setSalary(50000.0);\n\t\temployee3.setDeg(\"Technical Writer\");\n\t\t\n\t\t//Store Employee\n\t\tentitymanager.persist(employee1);\n\t\tentitymanager.persist(employee2);\n\t\tentitymanager.persist(employee3);\n\t\t\n\t\t//Create Employeelist\n\t\tList<Employee> emplist = new ArrayList();\n\t\templist.add(employee1);\n\t\templist.add(employee2);\n\t\templist.add(employee3);\n\t\t\n\t\t//Create Department Entity\n\t\tDepartment department= new Department();\n\t\tdepartment.setName(\"Development\");\n\t\tdepartment.setEmployeelist(emplist);\n\t\t\t\t\n\t\t//Store Department\n\t\tentitymanager.persist(department);\n\t\t\n\t\tentitymanager.getTransaction().commit();\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 79726, "s": 79564, "text": "After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output check MySQL workbench as follows." }, { "code": null, "e": 79886, "s": 79726, "text": "In this project three tables are created. Pass the following query in MySQL interface and the result of department_employee table will be displayed as follows:" }, { "code": null, "e": 79915, "s": 79886, "text": "Select * from department_Id;" }, { "code": null, "e": 80041, "s": 79915, "text": "In the above table, deparment_id and employee_id are the foreign keys (reference fields) from department and employee tables." }, { "code": null, "e": 80170, "s": 80041, "text": "Pass the following query in MySQL interface and the result of department table will be displayed in a tabular format as follows." }, { "code": null, "e": 80196, "s": 80170, "text": "Select * from department;" }, { "code": null, "e": 80303, "s": 80196, "text": "Pass the following query in MySQL interface and the result of employee table will be displayed as follows:" }, { "code": null, "e": 80327, "s": 80303, "text": "Select * from employee;" }, { "code": null, "e": 80489, "s": 80327, "text": "In One-To-One relationship, one item can be linked to only one other item. It means each row of one entity is referred to one and only one row of another entity." }, { "code": null, "e": 80792, "s": 80489, "text": "Let us consider the above example. Employee and Department in a reverse unidirectional manner, the relation is One-To-One relation. It means each employee belongs to only one department. Create a JPA project in eclipse IDE named JPA_Eclipselink_OTO. All the modules of this project are discussed below." }, { "code": null, "e": 81036, "s": 80792, "text": "Follow the above given diagram for creating entities. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Department.java under given package. The class Department entity is shown as follows:" }, { "code": null, "e": 81646, "s": 81036, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class Department \n{\n @Id \n @GeneratedValue( strategy=GenerationType.AUTO )\n private int id;\n private String name;\n \n public int getId() \n {\n \treturn id;\n }\n \n public void setId(int id) \n {\n \tthis.id = id;\n }\n \n public String getName( )\n {\n \treturn name;\n }\n \n public void setName( String deptName )\n {\n \tthis.name = deptName;\n }\n}" }, { "code": null, "e": 81834, "s": 81646, "text": "Create the second entity in this relation -Employee entity class, named Employee.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows:" }, { "code": null, "e": 83100, "s": 81834, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\n\n@Entity\npublic class Employee \n{\n\t@Id\n\t@GeneratedValue( strategy= GenerationType.AUTO ) \t\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\t\n\t@OneToOne\n\tprivate Department department;\n\t\t\n\tpublic Employee(int eid, \n\t\t\tString ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\t\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n\t\n\tpublic String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\n\n\tpublic Department getDepartment() \n\t{\n\t\treturn department;\n\t}\n\n\tpublic void setDepartment(Department department) \n\t{\n\t\tthis.department = department;\n\t}\t\n}" }, { "code": null, "e": 83133, "s": 83100, "text": "Persistence.xml file as follows:" }, { "code": null, "e": 84279, "s": 83133, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" \n xmlns=\"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\t<class>com.tutorialspoint.eclipselink.entity.Department</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n\t\t\t value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n\t\t\t value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n\t\t\t value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 84469, "s": 84279, "text": "Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named OneToOne.java is created under the given package. The DAO class is shown as follows:" }, { "code": null, "e": 85575, "s": 84469, "text": "package com.tutorialspointeclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Department;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class OneToOne \n{\n\tpublic static void main(String[] args) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Create Department Entity\n\t\tDepartment department = new Department();\n\t\tdepartment.setName(\"Development\");\n\t\t\n\t\t//Store Department\n\t\tentitymanager.persist(department);\n\t\t\n\t\t//Create Employee Entity\n\t\tEmployee employee = new Employee();\n\t\temployee.setEname(\"Satish\");\n\t\temployee.setSalary(45000.0);\n\t\temployee.setDeg(\"Technical Writer\");\n\t\temployee.setDepartment(department);\n\t\t\n\t\t//Store Employee\n\t\tentitymanager.persist(employee);\n\t\t\n\t\tentitymanager.getTransaction().commit();\n\t\tentitymanager.close();\n\t\temfactory.close();\n\t}\n}" }, { "code": null, "e": 85738, "s": 85575, "text": "After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench as follows." }, { "code": null, "e": 85893, "s": 85738, "text": "In the above example, two tables are created. Pass the following query in MySQL interface and the result of department table will be displayed as follows:" }, { "code": null, "e": 85918, "s": 85893, "text": "Select * from department" }, { "code": null, "e": 86025, "s": 85918, "text": "Pass the following query in MySQL interface and the result of employee table will be displayed as follows:" }, { "code": null, "e": 86048, "s": 86025, "text": "Select * from employee" }, { "code": null, "e": 86171, "s": 86048, "text": "Many-To-Many relationship is where one or more rows from one entity are associated with more than one row in other entity." }, { "code": null, "e": 86691, "s": 86171, "text": "Let us consider an example of a relation between two entities: Class and Teacher. In bidirectional manner, both Class and Teacher have Many-To-One relation. That means each record of Class is referred by Teacher set (teacher ids), which should be primary keys in the Teacher table and stored in the Teacher_Class table and vice versa. Here, the Teachers_Class table contains both the foreign key fields. Create a JPA project in eclipse IDE named JPA_Eclipselink_MTM. All the modules of this project are discussed below." }, { "code": null, "e": 86943, "s": 86691, "text": "Create entities by following the schema shown in the diagram above. Create a package named ‘com.tutorialspoin.eclipselink.entity’ under ‘src’ package. Create a class named Clas.java under given package. The class Department entity is shown as follows:" }, { "code": null, "e": 87923, "s": 86943, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.util.Set;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\n\n@Entity\npublic class Clas \n{\n\t@Id\n\t@GeneratedValue( strategy = GenerationType.AUTO )\n\tprivate int cid;\n\tprivate String cname;\n\t\n\t@ManyToMany(targetEntity=Teacher.class)\n\tprivate Set teacherSet;\n\t\n\tpublic Clas() \n\t{\n\t\tsuper();\n\t}\n\tpublic Clas(int cid, \n\t\t\tString cname, Set teacherSet) \n\t{\n\t\tsuper();\n\t\tthis.cid = cid;\n\t\tthis.cname = cname;\n\t\tthis.teacherSet = teacherSet;\n\t}\n\tpublic int getCid() \n\t{\n\t\treturn cid;\n\t}\n\tpublic void setCid(int cid) \n\t{\n\t\tthis.cid = cid;\n\t}\n\tpublic String getCname() \n\t{\n\t\treturn cname;\n\t}\n\tpublic void setCname(String cname) \n\t{\n\t\tthis.cname = cname;\n\t}\n\tpublic Set getTeacherSet() \n\t{\n\t\treturn teacherSet;\n\t}\n\tpublic void setTeacherSet(Set teacherSet) \n\t{\n\t\tthis.teacherSet = teacherSet;\n\t}\t \n}" }, { "code": null, "e": 88110, "s": 87923, "text": "Create the second entity in this relation -Employee entity class, named Teacher.java under ‘com.tutorialspoint.eclipselink.entity’ package. The Employee entity class is shown as follows:" }, { "code": null, "e": 89256, "s": 88110, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.util.Set;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\n\n@Entity\npublic class Teacher \n{\n\t@Id\n\t@GeneratedValue( strategy = GenerationType.AUTO )\n\tprivate int tid;\n\tprivate String tname;\n\tprivate String subject;\n\t\n\t@ManyToMany(targetEntity=Clas.class)\n\tprivate Set clasSet;\n\t\n\tpublic Teacher() \n\t{\n\t\tsuper();\n\t}\n\tpublic Teacher(int tid, String tname, String subject, \n\t\t\tSet clasSet) \n\t{\n\t\tsuper();\n\t\tthis.tid = tid;\n\t\tthis.tname = tname;\n\t\tthis.subject = subject;\n\t\tthis.clasSet = clasSet;\n\t}\n\tpublic int getTid() \n\t{\n\t\treturn tid;\n\t}\n\tpublic void setTid(int tid) \n\t{\n\t\tthis.tid = tid;\n\t}\n\tpublic String getTname() \n\t{\n\t\treturn tname;\n\t}\n\tpublic void setTname(String tname) \n\t{\n\t\tthis.tname = tname;\n\t}\n\tpublic String getSubject() \n\t{\n\t\treturn subject;\n\t}\n\tpublic void setSubject(String subject) \n\t{\n\t\tthis.subject = subject;\n\t}\n\tpublic Set getClasSet() \n\t{\n\t\treturn clasSet;\n\t}\n\tpublic void setClasSet(Set clasSet) \n\t{\n\t\tthis.clasSet = clasSet;\n\t}\n}" }, { "code": null, "e": 89290, "s": 89256, "text": "Persistence.xml file as follows:" }, { "code": null, "e": 90436, "s": 89290, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" \n xmlns=\"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\t<class>com.tutorialspoint.eclipselink.entity.Department</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n\t\t\t value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n\t\t\t value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n\t\t\t value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 90624, "s": 90436, "text": "Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’. The DAO class named ManyToMany.java is created under given package. The DAO class is shown as follows:" }, { "code": null, "e": 92366, "s": 90624, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.Clas;\nimport com.tutorialspoint.eclipselink.entity.Teacher;\n\npublic class ManyToMany \n{\n\tpublic static void main(String[] args) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tentitymanager.getTransaction( ).begin( );\n\t\t\n\t\t//Create Clas Entity\n\t\tClas clas1=new Clas(0,\"1st\",null);\n\t\tClas clas2=new Clas(0,\"2nd\",null);\n\t\tClas clas3=new Clas(0,\"3rd\",null);\n\t\t\n\t\t//Store Clas\n\t\tentitymanager.persist(clas1);\n\t\tentitymanager.persist(clas2);\n\t\tentitymanager.persist(clas3);\n\t\t\n\t\t//Create Clas Set1\n\t\tSet<Clas> classSet1 = new HashSet();\n\t\tclassSet1.add(clas1);\n\t\tclassSet1.add(clas2);\n\t\tclassSet1.add(clas3);\n\t\t\n\t\t//Create Clas Set2\n\t\tSet<Clas> classSet2 = new HashSet();\n\t\tclassSet2.add(clas3);\n\t\tclassSet2.add(clas1);\n\t\tclassSet2.add(clas2);\n\t\t\t\t\n\t\t//Create Clas Set3\n\t\tSet<Clas> classSet3 = new HashSet();\n\t\tclassSet3.add(clas2);\n\t\tclassSet3.add(clas3);\n\t\tclassSet3.add(clas1);\n\t\t\n\t\t//Create Teacher Entity\n\t\tTeacher teacher1 = new Teacher(0,\n\t\t\t\t\"Satish\",\"Java\",classSet1);\n\t\tTeacher teacher2 = new Teacher(0,\n\t\t\t\t\"Krishna\",\"Adv Java\",classSet2);\n\t\tTeacher teacher3 = new Teacher(0,\n\t\t\t\t\"Masthanvali\",\"DB2\",classSet3);\n\t\t\n\t\t//Store Teacher\n\t\tentitymanager.persist(teacher1);\n\t\tentitymanager.persist(teacher2);\n\t\tentitymanager.persist(teacher3);\n\t\t\n\t\tentitymanager.getTransaction( ).commit( );\n\t\tentitymanager.close( );\n\t\temfactory.close( );\n\t}\n}" }, { "code": null, "e": 92528, "s": 92366, "text": "In this example project, three tables are created. Pass the following query in MySQL interface and the result of teacher_clas table will be displayed as follows:" }, { "code": null, "e": 92555, "s": 92528, "text": "Select * form teacher_clas" }, { "code": null, "e": 92740, "s": 92555, "text": "In the above table teacher_tid is the foreign key from teacher table, and classet_cid is the foreign key from class table. Therefore different teachers are allotted to different class." }, { "code": null, "e": 92846, "s": 92740, "text": "Pass the following query in MySQL interface and the result of teacher table will be displayed as follows:" }, { "code": null, "e": 92868, "s": 92846, "text": "Select * from teacher" }, { "code": null, "e": 92971, "s": 92868, "text": "Pass the following query in MySQL interface and the result of clas table will be displayed as follows:" }, { "code": null, "e": 92990, "s": 92971, "text": "Select * from clas" }, { "code": null, "e": 93384, "s": 92990, "text": "Criteria is a predefined API that is used to define queries for entities. It is an alternative way of defining a JPQL query. These queries are type-safe, portable, and easy to modify by changing the syntax. Similar to JPQL, it follows an abstract schema (easy to edit schema) and embedded objects. The metadata API is mingled with criteria API to model persistent entity for criteria queries. " }, { "code": null, "e": 93581, "s": 93384, "text": "The major advantage of Criteria API is that errors can be detected earlier during the compile time. String-based JPQL queries and JPA criteria based queries are same in performance and efficiency." }, { "code": null, "e": 93705, "s": 93581, "text": "The criteria is included into all versions of JPA therefore each step of criteria is notified in the specifications of JPA." }, { "code": null, "e": 93783, "s": 93705, "text": "In JPA 2.0, the criteria query API, standardization of queries are developed." }, { "code": null, "e": 93861, "s": 93783, "text": "In JPA 2.1, Criteria update and delete (bulk update and delete) are included." }, { "code": null, "e": 94093, "s": 93861, "text": "The Criteria and the JPQL are closely related and are allowed to design using similar operators in their queries. It follows javax.persistence.criteria package to design a query. The query structure means the syntax criteria query." }, { "code": null, "e": 94191, "s": 94093, "text": "The following simple criteria query returns all instances of the entity class in the data source." }, { "code": null, "e": 94472, "s": 94191, "text": "EntityManager em = ...;\nCriteriaBuilder cb = em.getCriteriaBuilder();\nCriteriaQuery<Entity class> cq = cb.createQuery(Entity.class);\nRoot<Entity> from = cq.from(Entity.class);\ncq.select(Entity);\nTypedQuery<Entity> q = em.createQuery(cq);\nList<Entity> allitems = q.getResultList();" }, { "code": null, "e": 94533, "s": 94472, "text": "The query demonstrates the basic steps to create a criteria." }, { "code": null, "e": 94600, "s": 94533, "text": "EntityManager instance is used to create a CriteriaBuilder object." }, { "code": null, "e": 94667, "s": 94600, "text": "EntityManager instance is used to create a CriteriaBuilder object." }, { "code": null, "e": 94803, "s": 94667, "text": "CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query." }, { "code": null, "e": 94939, "s": 94803, "text": "CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query." }, { "code": null, "e": 94998, "s": 94939, "text": "CriteriaQuery.form method is called to set the query root." }, { "code": null, "e": 95057, "s": 94998, "text": "CriteriaQuery.form method is called to set the query root." }, { "code": null, "e": 95117, "s": 95057, "text": "CriteriaQuery.select is called to set the result list type." }, { "code": null, "e": 95177, "s": 95117, "text": "CriteriaQuery.select is called to set the result list type." }, { "code": null, "e": 95286, "s": 95177, "text": "TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result." }, { "code": null, "e": 95395, "s": 95286, "text": "TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result." }, { "code": null, "e": 95541, "s": 95395, "text": "getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List." }, { "code": null, "e": 95687, "s": 95541, "text": "getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List." }, { "code": null, "e": 95804, "s": 95687, "text": "Let us consider the example of employee database. Let us assume the jpadb.employee table contains following records:" }, { "code": null, "e": 96078, "s": 95804, "text": "Eid\t Ename Salary\tDeg\n401\t Gopal\t 40000\tTechnical Manager\n402\t Manisha\t 40000\tProof reader\n403\t Masthanvali 35000\tTechnical Writer\n404 Satish\t 30000\tTechnical writer\n405\t Krishna\t 30000\tTechnical Writer\n406\t Kiran\t 35000\tProof reader" }, { "code": null, "e": 96203, "s": 96078, "text": "Create a JPA Project in the eclipse IDE named JPA_Eclipselink_Criteria. All the modules of this project are discussed below:" }, { "code": null, "e": 96277, "s": 96203, "text": "Create a package named com.tutorialspoint.eclipselink.entity under ‘src’\n" }, { "code": null, "e": 96380, "s": 96277, "text": "Create a class named Employee.java under given package. The class Employee entity is shown as follows:" }, { "code": null, "e": 97548, "s": 96380, "text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class Employee \n{\n\t@Id\n\t@GeneratedValue(strategy= GenerationType.AUTO) \t\n\tprivate int eid;\n\tprivate String ename;\n\tprivate double salary;\n\tprivate String deg;\n\tpublic Employee(int eid, String ename, double salary, String deg) \n\t{\n\t\tsuper( );\n\t\tthis.eid = eid;\n\t\tthis.ename = ename;\n\t\tthis.salary = salary;\n\t\tthis.deg = deg;\n\t}\n\t\n\tpublic Employee( ) \n\t{\n\t\tsuper();\n\t}\n\t\n\tpublic int getEid( ) \n\t{\n\t\treturn eid;\n\t}\n\tpublic void setEid(int eid) \n\t{\n\t\tthis.eid = eid;\n\t}\n\t\n\tpublic String getEname( ) \n\t{\n\t\treturn ename;\n\t}\n\tpublic void setEname(String ename) \n\t{\n\t\tthis.ename = ename;\n\t}\n\t\n\tpublic double getSalary( ) \n\t{\n\t\treturn salary;\n\t}\n\tpublic void setSalary(double salary) \n\t{\n\t\tthis.salary = salary;\n\t}\n\t\n\tpublic String getDeg( ) \n\t{\n\t\treturn deg;\n\t}\n\tpublic void setDeg(String deg) \n\t{\n\t\tthis.deg = deg;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Employee [eid=\" + eid + \", ename=\" + ename + \", salary=\"\n\t\t\t\t+ salary + \", deg=\" + deg + \"]\";\n\t}\n}" }, { "code": null, "e": 97584, "s": 97548, "text": "Persistence.xml file is as follows:" }, { "code": null, "e": 98636, "s": 97584, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\t<persistence-unit name=\"Eclipselink_JPA\" \n transaction-type=\"RESOURCE_LOCAL\">\n\t<class>com.tutorialspoint.eclipselink.entity.Employee</class>\n\t\t<properties>\n\t\t\t<property name=\"javax.persistence.jdbc.url\" \n\t\t\t value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.password\" \n\t\t\t value=\"root\"/>\n\t\t\t<property name=\"javax.persistence.jdbc.driver\" \n\t\t\t value=\"com.mysql.jdbc.Driver\"/>\n\t\t\t<property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n\t\t\t<property name=\"eclipselink.ddl-generation\" \n\t\t\t value=\"create-tables\"/>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>" }, { "code": null, "e": 98923, "s": 98636, "text": "This module contains the service classes, which implements the Criteria query part using the MetaData API initialization. Create a package named ‘com.tutorialspoint.eclipselink.service’. The class named CriteriaAPI.java is created under given package. The DAO class is shown as follows:" }, { "code": null, "e": 100787, "s": 98923, "text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Root;\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class CriteriaApi \n{\n\tpublic static void main(String[] args) \n\t{\n\t\tEntityManagerFactory emfactory = Persistence.\n\t\t\t\tcreateEntityManagerFactory( \"Eclipselink_JPA\" );\n\t\tEntityManager entitymanager = emfactory.\n\t\t\t\tcreateEntityManager( );\n\t\tCriteriaBuilder criteriaBuilder = entitymanager\n\t\t\t\t.getCriteriaBuilder();\n\t\tCriteriaQuery<Object> criteriaQuery = criteriaBuilder\n\t\t\t\t.createQuery();\n\t\tRoot<Employee> from = criteriaQuery.from(Employee.class);\n\t\t\n\t\t//select all records\n System.out.println(“Select all records”);\n\t\tCriteriaQuery<Object> select =criteriaQuery.select(from);\n\t\tTypedQuery<Object> typedQuery = entitymanager\n\t\t\t\t.createQuery(select);\n\t\tList<Object> resultlist= typedQuery.getResultList();\n\t\t\n\t\tfor(Object o:resultlist)\n\t\t{\n\t\t\tEmployee e=(Employee)o;\n\t\t\tSystem.out.println(\"EID : \"+e.getEid()\n\t\t\t\t\t+\" Ename : \"+e.getEname());\n\t\t}\n\t\t\n\t\t//Ordering the records \n System.out.println(“Select all records by follow ordering”);\n\t\tCriteriaQuery<Object> select1 = criteriaQuery.select(from);\n select1.orderBy(criteriaBuilder.asc(from.get(\"ename\")));\n TypedQuery<Object> typedQuery1 = entitymanager\n \t\t.createQuery(select);\n List<Object> resultlist1= typedQuery1.getResultList();\n\t\t\n\t\tfor(Object o:resultlist1)\n\t\t{\n\t\t\tEmployee e=(Employee)o;\n\t\t\tSystem.out.println(\"EID : \"+e.getEid()\n\t\t\t\t\t+\" Ename : \"+e.getEname());\n\t\t}\n\t\t\n\t\tentitymanager.close( );\n\t\temfactory.close( );\n\t}\n}" }, { "code": null, "e": 100906, "s": 100787, "text": "After compiling and executing the above program you will get the following output in the console panel of Eclipse IDE." }, { "code": null, "e": 101273, "s": 100906, "text": "Select All records\nEID : 401 Ename : Gopal\nEID : 402 Ename : Manisha\nEID : 403 Ename : Masthanvali\nEID : 404 Ename : Satish\nEID : 405 Ename : Krishna\nEID : 406 Ename : Kiran\nSelect All records by follow Ordering\nEID : 401 Ename : Gopal\nEID : 406 Ename : Kiran\nEID : 405 Ename : Krishna\nEID : 402 Ename : Manisha\nEID : 403 Ename : Masthanvali\nEID : 404 Ename : Satish" }, { "code": null, "e": 101280, "s": 101273, "text": " Print" }, { "code": null, "e": 101291, "s": 101280, "text": " Add Notes" } ]
Difference Between Atomic, Volatile and Synchronized in Java - GeeksforGeeks
17 Nov, 2021 Synchronized is the modifier applicable only for methods and blocks but not for the variables and for classes. There may be a chance of data inconsistency problem to overcome this problem we should go for a synchronized keyword when multiple threads are trying to operate simultaneously on the same java object. If a method or block declares as synchronized then at a time only one thread at a time is allowed to execute that method or block on the given object so that the data inconsistence problem will be resolved. The main advantage of synchronized keywords is we can resolve data inconsistence problems but the main disadvantage of this keyword is it increases the waiting time of the thread and creates performance problems. Hence, It is not recommended using, the synchronized keyword when there is no specific requirement. Every object in java has a unique lock. The lock concept will come into the picture when we are using a synchronized keyword. The remaining threads are not allowed to execute any synchronized method simultaneously on the same object when a thread executing a synchronized method on the given object. But remaining threads are allowed to execute the non-synchronized method simultaneously. Volatile Modifier: If a value of a variable keeps on changing by multiple threads then there may be a chance of a data inconsistency problem. It is a modifier applicable only for variables, and we can’t apply it anywhere else. We can solve this problem by using a volatile modifier. If a variable is declared as volatile as for every thread JVM will create a separate local copy. Every modification performed by the thread will take place in the local copy so that there is no effect on the remaining threads. Overcoming the data inconsistency problem is the advantage and the volatile keyword is creating and maintaining a separate copy for every thread increases the complexity of the programming and creates performance problem is a disadvantage. Hence, if there are no specific requirements it is never recommended to use volatile keywords. Atomic Modifier: If a value of a variable keeps on changing by multiple threads then there may be a chance of a data inconsistency problem. We can solve this problem by using an atomic variable. Data inconsistency problem can be solved when objects of these classes represent the atomic variable of int, long, boolean, and object reference respectively. Example: In the below example every thread increments the count variable 5 times. So after the execution of two threads, the finish count value should be 10. Java // import required packagesimport java.io.*;import java.util.*; // creating a thread by extending a thread classclass myThread extends Thread { // declaring a count variable private int count; public void run() { // calculating the count for (int i = 1; i <= 5; i++) { try { Thread.sleep(i * 100); count++; } catch (InterruptedException e) { // throwing an exception System.out.println(e); } } } // returning the count value public int getCount() { return this.count; }}// driver classpublic class GFG { // main method public static void main(String[] args) throws InterruptedException { // creating an thread object myThread t = new myThread(); Thread t1 = new Thread(t, "t1"); // starting thread t1 t1.start(); Thread t2 = new Thread(t, "t2"); // starting thread t2 t2.start(); // calling join method on thread t1 t1.join(); // calling join method on thread t1 t2.join(); // displaying the count System.out.println("count=" + t.getCount()); }} count=10 If we run the above program, we will notice that the count value varies between 6,7,8.9 The reason is that count++ is not an atomic operation. So by the time one thread read itâ€TMs value and increment it by one, another thread has read the older value leading to the wrong result. To solve this issue, we will have to make sure that increment operation on count is atomic. Below program will always output count value as 8 because AtomicInteger method incrementAndGet() atomically increments the current value by one. Java // import required packagesimport java.io.*;import java.util.*;import java.util.concurrent.atomic.AtomicInteger; // creating a thread by extending a thread classclass myThread extends Thread { // declaring an atomic variable private AtomicInteger count = new AtomicInteger(); public void run() { // calculating the count for (int i = 1; i <= 5; i++) { try { // putting thread on sleep Thread.sleep(i * 100); // calling incrementAndGet() method // on count variable count.incrementAndGet(); } catch (InterruptedException e) { // throwing exception System.out.println(e); } } } // returning the count value public AtomicInteger getCount() { return count; }}// driver classpublic class GFG { // main method public static void main(String[] args) throws InterruptedException { // creating an thread object myThread t = new myThread(); Thread t1 = new Thread(t, "t1"); // starting thread t1 t1.start(); Thread t2 = new Thread(t, "t2"); // starting thread t2 t2.start(); // calling join method on thread t1 t1.join(); // calling join method on thread t1 t2.join(); // displaying the count System.out.println("count=" + t.getCount()); }} count=10 akshaysingh98088 varshagumber28 Java-keyword Picked Difference Between Java Java 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python 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": 24858, "s": 24830, "text": "\n17 Nov, 2021" }, { "code": null, "e": 25817, "s": 24858, "text": "Synchronized is the modifier applicable only for methods and blocks but not for the variables and for classes. There may be a chance of data inconsistency problem to overcome this problem we should go for a synchronized keyword when multiple threads are trying to operate simultaneously on the same java object. If a method or block declares as synchronized then at a time only one thread at a time is allowed to execute that method or block on the given object so that the data inconsistence problem will be resolved. The main advantage of synchronized keywords is we can resolve data inconsistence problems but the main disadvantage of this keyword is it increases the waiting time of the thread and creates performance problems. Hence, It is not recommended using, the synchronized keyword when there is no specific requirement. Every object in java has a unique lock. The lock concept will come into the picture when we are using a synchronized keyword. " }, { "code": null, "e": 26080, "s": 25817, "text": "The remaining threads are not allowed to execute any synchronized method simultaneously on the same object when a thread executing a synchronized method on the given object. But remaining threads are allowed to execute the non-synchronized method simultaneously." }, { "code": null, "e": 26099, "s": 26080, "text": "Volatile Modifier:" }, { "code": null, "e": 26925, "s": 26099, "text": "If a value of a variable keeps on changing by multiple threads then there may be a chance of a data inconsistency problem. It is a modifier applicable only for variables, and we can’t apply it anywhere else. We can solve this problem by using a volatile modifier. If a variable is declared as volatile as for every thread JVM will create a separate local copy. Every modification performed by the thread will take place in the local copy so that there is no effect on the remaining threads. Overcoming the data inconsistency problem is the advantage and the volatile keyword is creating and maintaining a separate copy for every thread increases the complexity of the programming and creates performance problem is a disadvantage. Hence, if there are no specific requirements it is never recommended to use volatile keywords." }, { "code": null, "e": 26944, "s": 26925, "text": "Atomic Modifier: " }, { "code": null, "e": 27281, "s": 26944, "text": "If a value of a variable keeps on changing by multiple threads then there may be a chance of a data inconsistency problem. We can solve this problem by using an atomic variable. Data inconsistency problem can be solved when objects of these classes represent the atomic variable of int, long, boolean, and object reference respectively." }, { "code": null, "e": 27290, "s": 27281, "text": "Example:" }, { "code": null, "e": 27439, "s": 27290, "text": "In the below example every thread increments the count variable 5 times. So after the execution of two threads, the finish count value should be 10." }, { "code": null, "e": 27444, "s": 27439, "text": "Java" }, { "code": "// import required packagesimport java.io.*;import java.util.*; // creating a thread by extending a thread classclass myThread extends Thread { // declaring a count variable private int count; public void run() { // calculating the count for (int i = 1; i <= 5; i++) { try { Thread.sleep(i * 100); count++; } catch (InterruptedException e) { // throwing an exception System.out.println(e); } } } // returning the count value public int getCount() { return this.count; }}// driver classpublic class GFG { // main method public static void main(String[] args) throws InterruptedException { // creating an thread object myThread t = new myThread(); Thread t1 = new Thread(t, \"t1\"); // starting thread t1 t1.start(); Thread t2 = new Thread(t, \"t2\"); // starting thread t2 t2.start(); // calling join method on thread t1 t1.join(); // calling join method on thread t1 t2.join(); // displaying the count System.out.println(\"count=\" + t.getCount()); }}", "e": 28704, "s": 27444, "text": null }, { "code": null, "e": 28716, "s": 28707, "text": "count=10" }, { "code": null, "e": 29091, "s": 28716, "text": "If we run the above program, we will notice that the count value varies between 6,7,8.9 The reason is that count++ is not an atomic operation. So by the time one thread read itâ€TMs value and increment it by one, another thread has read the older value leading to the wrong result. To solve this issue, we will have to make sure that increment operation on count is atomic." }, { "code": null, "e": 29237, "s": 29091, "text": "Below program will always output count value as 8 because AtomicInteger method incrementAndGet() atomically increments the current value by one. " }, { "code": null, "e": 29242, "s": 29237, "text": "Java" }, { "code": "// import required packagesimport java.io.*;import java.util.*;import java.util.concurrent.atomic.AtomicInteger; // creating a thread by extending a thread classclass myThread extends Thread { // declaring an atomic variable private AtomicInteger count = new AtomicInteger(); public void run() { // calculating the count for (int i = 1; i <= 5; i++) { try { // putting thread on sleep Thread.sleep(i * 100); // calling incrementAndGet() method // on count variable count.incrementAndGet(); } catch (InterruptedException e) { // throwing exception System.out.println(e); } } } // returning the count value public AtomicInteger getCount() { return count; }}// driver classpublic class GFG { // main method public static void main(String[] args) throws InterruptedException { // creating an thread object myThread t = new myThread(); Thread t1 = new Thread(t, \"t1\"); // starting thread t1 t1.start(); Thread t2 = new Thread(t, \"t2\"); // starting thread t2 t2.start(); // calling join method on thread t1 t1.join(); // calling join method on thread t1 t2.join(); // displaying the count System.out.println(\"count=\" + t.getCount()); }}", "e": 30783, "s": 29242, "text": null }, { "code": null, "e": 30795, "s": 30786, "text": "count=10" }, { "code": null, "e": 30814, "s": 30797, "text": "akshaysingh98088" }, { "code": null, "e": 30829, "s": 30814, "text": "varshagumber28" }, { "code": null, "e": 30842, "s": 30829, "text": "Java-keyword" }, { "code": null, "e": 30849, "s": 30842, "text": "Picked" }, { "code": null, "e": 30868, "s": 30849, "text": "Difference Between" }, { "code": null, "e": 30873, "s": 30868, "text": "Java" }, { "code": null, "e": 30878, "s": 30873, "text": "Java" }, { "code": null, "e": 30976, "s": 30878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31037, "s": 30976, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31105, "s": 31037, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 31163, "s": 31105, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 31218, "s": 31163, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 31292, "s": 31218, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 31307, "s": 31292, "text": "Arrays in Java" }, { "code": null, "e": 31351, "s": 31307, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31373, "s": 31351, "text": "For-each loop in Java" }, { "code": null, "e": 31409, "s": 31373, "text": "Arrays.sort() in Java with examples" } ]
Generate all combinations of supplied words in JavaScript
We are required to write a JavaScript function that takes in an array of strings. The function should then generate and return all possible combinations of the strings of the array. The code for this will be − const arr = ['a', 'b', 'c', 'd']; const permutations = (len, val, existing) => { if(len==0){ res.push(val); return; } for(let i=0; i<arr.length; i++){ // so that we do not repeat the item, using an array here makes it O(1) operation if(!existing[i]){ existing[i] = true; permutations(len−1, val+arr[i], existing); existing[i] = false; } } } let res = []; const buildPermuations = (arr = []) => { for(let i=0; i < arr.length; i++){ permutations(arr.length−i, "", []); } }; buildPermuations(arr); console.log(res); And the output in the console will be − [ 'abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'a', 'b', 'c', 'd' ]
[ { "code": null, "e": 1244, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of strings. The function should then generate and return all possible combinations of the strings of the array." }, { "code": null, "e": 1272, "s": 1244, "text": "The code for this will be −" }, { "code": null, "e": 1872, "s": 1272, "text": "const arr = ['a', 'b', 'c', 'd'];\nconst permutations = (len, val, existing) => {\n if(len==0){\n res.push(val);\n return;\n }\n for(let i=0; i<arr.length; i++){\n // so that we do not repeat the item, using an array here makes it\n O(1) operation\n if(!existing[i]){\n existing[i] = true;\n permutations(len−1, val+arr[i], existing);\n existing[i] = false;\n }\n }\n}\nlet res = [];\nconst buildPermuations = (arr = []) => {\n for(let i=0; i < arr.length; i++){\n permutations(arr.length−i, \"\", []);\n }\n};\nbuildPermuations(arr);\nconsole.log(res);" }, { "code": null, "e": 1912, "s": 1872, "text": "And the output in the console will be −" }, { "code": null, "e": 2400, "s": 1912, "text": "[\n 'abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb',\n 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca',\n 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba',\n 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba',\n 'abc', 'abd', 'acb', 'acd', 'adb', 'adc',\n 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc',\n 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb',\n 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb',\n 'ab', 'ac', 'ad', 'ba', 'bc', 'bd',\n 'ca', 'cb', 'cd', 'da', 'db', 'dc',\n 'a', 'b', 'c', 'd'\n]" } ]
Check if input is a number or letter in JavaScript?
To check if the input is a number or letter, use the isNaN() function from JavaScript. It returns true if the value is NaN i.e. Not a Number. Following is the code − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <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> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min. css" integrity="sha384- BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <form name="checkingInput" action="" onsubmit="return checkInputIsNumber()"> Enter the value: <input type="text" name="txtValue"> <br> <input type="submit" value="check"> <script> function checkInputIsNumber(){ var value=document.forms["checkingInput"]["txtValue"].value; if (isNaN(value)){ alert("Please Provide the input as a number"); return false; } } </script> </body> </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 − If you provide any value except the number, you will get an alert message. This will produce the following output − Here, I am entering the value 100. The screenshot is as follows − After clicking the check button, you will get the value as query string like − ?txtValue=yourValue. This will produce the following output −
[ { "code": null, "e": 1228, "s": 1062, "text": "To check if the input is a number or letter, use the isNaN() function from JavaScript. It returns\ntrue if the value is NaN i.e. Not a Number. Following is the code −" }, { "code": null, "e": 1239, "s": 1228, "text": " Live Demo" }, { "code": null, "e": 2358, "s": 1239, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//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<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.\ncss\" integrity=\"sha384- BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\"\ncrossorigin=\"anonymous\">\n</head>\n<body>\n<form name=\"checkingInput\" action=\"\" onsubmit=\"return\ncheckInputIsNumber()\">\nEnter the value: <input type=\"text\" name=\"txtValue\">\n<br>\n<input type=\"submit\" value=\"check\">\n<script>\n function checkInputIsNumber(){\n var value=document.forms[\"checkingInput\"][\"txtValue\"].value;\n if (isNaN(value)){\n alert(\"Please Provide the input as a number\");\n return false;\n }\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2520, "s": 2358, "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": 2561, "s": 2520, "text": "This will produce the following output −" }, { "code": null, "e": 2677, "s": 2561, "text": "If you provide any value except the number, you will get an alert message. This will produce the\nfollowing output −" }, { "code": null, "e": 2743, "s": 2677, "text": "Here, I am entering the value 100. The screenshot is as follows −" }, { "code": null, "e": 2822, "s": 2743, "text": "After clicking the check button, you will get the value as query string like −" }, { "code": null, "e": 2843, "s": 2822, "text": "?txtValue=yourValue." }, { "code": null, "e": 2884, "s": 2843, "text": "This will produce the following output −" } ]
k-th smallest absolute difference of two elements in an array - GeeksforGeeks
05 Jan, 2022 We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] – a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) the smallest absolute difference among all these pairs.Examples: Input : a[] = {1, 2, 3, 4} k = 3 Output : 1 The possible absolute differences are : {1, 2, 3, 1, 2, 1}. The 3rd smallest value among these is 1. Input : n = 2 a[] = {10, 10} k = 1 Output : 0 Naive Method is to find all the n*(n-1)/2 possible absolute differences in O(n^2) and store them in an array. Then sort this array and print the k-th minimum value from this array. This will take time O(n^2 + n^2 * log(n^2)) = O(n^2 + 2*n^2*log(n)).The naive method won’t be efficient for large values of n, say n = 10^5.An Efficient Solution is based on Binary Search. 1) Sort the given array a[]. 2) We can easily find the least possible absolute difference in O(n) after sorting. The largest possible difference will be a[n-1] - a[0] after sorting the array. Let low = minimum_difference and high = maximum_difference. 3) while low < high: 4) mid = (low + high)/2 5) if ((number of pairs with absolute difference <= mid) < k): 6) low = mid + 1 7) else: 8) high = mid 9) return low We need a function that will tell us the number of pairs with a difference <= mid efficiently. Since our array is sorted, this part can be done like this: 1) result = 0 2) for i = 0 to n-1: 3) result = result + (upper_bound(a+i, a+n, a[i] + mid) - (a+i+1)) 4) return result Here upper_bound is a variant of binary search which returns a pointer to the first element from a[i] to a[n-1] which is greater than a[i] + mid. Let the pointer returned be j. Then a[i] + mid < a[j]. Thus, subtracting (a+i+1) from this will give us the number of values whose difference with a[i] is <= mid. We sum this up for all indices from 0 to n-1 and get the answer for the current mid. C++ Java Python3 C# Javascript // C++ program to find k-th absolute difference// between two elements#include<bits/stdc++.h>using namespace std; // returns number of pairs with absolute difference// less than or equal to mid.int countPairs(int *a, int n, int mid){ int res = 0; for (int i = 0; i < n; ++i) // Upper bound returns pointer to position // of next higher number than a[i]+mid in // a[i..n-1]. We subtract (a + i + 1) from // this position to count res += upper_bound(a+i, a+n, a[i] + mid) - (a + i + 1); return res;} // Returns k-th absolute differenceint kthDiff(int a[], int n, int k){ // Sort array sort(a, a+n); // Minimum absolute difference int low = a[1] - a[0]; for (int i = 1; i <= n-2; ++i) low = min(low, a[i+1] - a[i]); // Maximum absolute difference int high = a[n-1] - a[0]; // Do binary search for k-th absolute difference while (low < high) { int mid = (low+high)>>1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low;} // Driver codeint main(){ int k = 3; int a[] = {1, 2, 3, 4}; int n = sizeof(a)/sizeof(a[0]); cout << kthDiff(a, n, k); return 0;} // Java program to find k-th absolute difference// between two elementsimport java.util.Scanner;import java.util.Arrays; class GFG{ // returns number of pairs with absolute // difference less than or equal to mid static int countPairs(int[] a, int n, int mid) { int res = 0, value; for(int i = 0; i < n; i++) { // Upper bound returns pointer to position // of next higher number than a[i]+mid in // a[i..n-1]. We subtract (ub + i + 1) from // this position to count if(a[i]+mid>a[n-1]) res+=(n-(i+1)); else { int ub = upperbound(a, n, a[i]+mid); res += (ub- (i+1)); } } return res; } // returns the upper bound static int upperbound(int a[], int n, int value) { int low = 0; int high = n; while(low < high) { final int mid = (low + high)/2; if(value >= a[mid]) low = mid + 1; else high = mid; } return low; } // Returns k-th absolute difference static int kthDiff(int a[], int n, int k) { // Sort array Arrays.sort(a); // Minimum absolute difference int low = a[1] - a[0]; for (int i = 1; i <= n-2; ++i) low = Math.min(low, a[i+1] - a[i]); // Maximum absolute difference int high = a[n-1] - a[0]; // Do binary search for k-th absolute difference while (low < high) { int mid = (low + high) >> 1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low; } // Driver function to check the above functions public static void main(String args[]) { Scanner s = new Scanner(System.in); int k = 3; int a[] = {1,2,3,4}; int n = a.length; System.out.println(kthDiff(a, n, k)); } }// This code is contributed by nishkarsh146 # Python3 program to find # k-th absolute difference # between two elements from bisect import bisect as upper_bound # returns number of pairs with # absolute difference less than # or equal to mid. def countPairs(a, n, mid): res = 0 for i in range(n): # Upper bound returns pointer to position # of next higher number than a[i]+mid in # a[i..n-1]. We subtract (a + i + 1) from # this position to count res += upper_bound(a, a[i] + mid) return res # Returns k-th absolute difference def kthDiff(a, n, k): # Sort array a = sorted(a) # Minimum absolute difference low = a[1] - a[0] for i in range(1, n - 1): low = min(low, a[i + 1] - a[i]) # Maximum absolute difference high = a[n - 1] - a[0] # Do binary search for k-th absolute difference while (low < high): mid = (low + high) >> 1 if (countPairs(a, n, mid) < k): low = mid + 1 else: high = mid return low # Driver code k = 3a = [1, 2, 3, 4] n = len(a) print(kthDiff(a, n, k)) # This code is contributed by Mohit Kumar // C# program to find k-th // absolute difference// between two elementsusing System;class GFG{ // returns number of pairs // with absolute difference // less than or equal to mid static int countPairs(int[] a, int n, int mid){ int res = 0; for(int i = 0; i < n; i++) { // Upper bound returns pointer // to position of next higher // number than a[i]+mid in // a[i..n-1]. We subtract // (ub + i + 1) from // this position to count int ub = upperbound(a, n, a[i] + mid); res += (ub - (i)); } return res;} // returns the upper boundstatic int upperbound(int []a, int n, int value){ int low = 0; int high = n; while(low < high) { int mid = (low + high)/2; if(value >= a[mid]) low = mid + 1; else high = mid; } return low;} // Returns k-th absolute // differencestatic int kthDiff(int []a, int n, int k){ // Sort array Array.Sort(a); // Minimum absolute // difference int low = a[1] - a[0]; for (int i = 1; i <= n - 2; ++i) low = Math.Min(low, a[i + 1] - a[i]); // Maximum absolute // difference int high = a[n - 1] - a[0]; // Do binary search for // k-th absolute difference while (low < high) { int mid = (low + high) >> 1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low;} // Driver codepublic static void Main(String []args){ int k = 3; int []a = {1, 2, 3, 4}; int n = a.Length; Console.WriteLine(kthDiff(a, n, k));}} // This code is contributed by gauravrajput1 <script> // JavaScript program to find k-th// absolute difference// between two elements // returns number of pairs// with absolute difference// less than or equal to midfunction countPairs(a, n, mid) { let res = 0; for (let i = 0; i < n; i++) { // Upper bound returns pointer // to position of next higher // number than a[i]+mid in // a[i..n-1]. We subtract // (ub + i + 1) from // this position to count let ub = upperbound(a, n, a[i] + mid); res += (ub - (i)); } return res;} // returns the upper boundfunction upperbound(a, n, value) { let low = 0; let high = n; while (low < high) { let mid = (low + high) / 2; if (value >= a[mid]) low = mid + 1; else high = mid; } return low;} // Returns k-th absolute// differencefunction kthDiff(a, n, k) { // Sort array a.sort((a, b) => a - b); // Minimum absolute // difference let low = a[1] - a[0]; for (let i = 1; i <= n - 2; ++i) low = Math.min(low, a[i + 1] - a[i]); // Maximum absolute // difference let high = a[n - 1] - a[0]; // Do binary search for // k-th absolute difference while (low < high) { let mid = (low + high) >> 1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low;} // Driver code let k = 3;let a = [1, 2, 3, 4];let n = a.length;document.write(kthDiff(a, n, k)); // This code is contributed by gfgking </script> Output: 1 Suppose, maximum element in the array is , and minimum element is minimum element in the array is . Then time taken for the binary_search will be , and time taken for the upper_bound function will be . So, the time complexity of the algorithm is . Sorting takes . After that the main binary search over low and high takes time because each call to the function countPairs takes time . So the Overall time complexity would be YouTubeGeeksforGeeks500K subscribersk-th smallest absolute difference of two elements in an array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ZXpYPeRE66E" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p This article is contributed by Hemang Sarkar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mohit kumar 29 nishkarsh146 GauravRajput1 gfgking sankcan55 executionover Binary Search Order-Statistics Arrays Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Stack Data Structure (Introduction and Program) Arrays in C/C++ Multidimensional Arrays in Java Python | Using 2D arrays/lists the right way Queue | Set 1 (Introduction and Array Implementation) Largest Sum Contiguous Subarray Linear Search Program for array rotation Program to find largest element in an array
[ { "code": null, "e": 40883, "s": 40855, "text": "\n05 Jan, 2022" }, { "code": null, "e": 41174, "s": 40883, "text": "We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] – a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) the smallest absolute difference among all these pairs.Examples: " }, { "code": null, "e": 41392, "s": 41174, "text": "Input : a[] = {1, 2, 3, 4}\n k = 3\nOutput : 1\nThe possible absolute differences are :\n{1, 2, 3, 1, 2, 1}.\nThe 3rd smallest value among these is 1.\n\nInput : n = 2\n a[] = {10, 10}\n k = 1\nOutput : 0" }, { "code": null, "e": 41764, "s": 41392, "text": "Naive Method is to find all the n*(n-1)/2 possible absolute differences in O(n^2) and store them in an array. Then sort this array and print the k-th minimum value from this array. This will take time O(n^2 + n^2 * log(n^2)) = O(n^2 + 2*n^2*log(n)).The naive method won’t be efficient for large values of n, say n = 10^5.An Efficient Solution is based on Binary Search. " }, { "code": null, "e": 42248, "s": 41764, "text": "1) Sort the given array a[].\n2) We can easily find the least possible absolute\n difference in O(n) after sorting. The largest\n possible difference will be a[n-1] - a[0] after\n sorting the array. Let low = minimum_difference\n and high = maximum_difference.\n3) while low < high:\n4) mid = (low + high)/2\n5) if ((number of pairs with absolute difference\n <= mid) < k):\n6) low = mid + 1\n7) else:\n8) high = mid\n9) return low" }, { "code": null, "e": 42404, "s": 42248, "text": "We need a function that will tell us the number of pairs with a difference <= mid efficiently. Since our array is sorted, this part can be done like this: " }, { "code": null, "e": 42527, "s": 42404, "text": "1) result = 0\n2) for i = 0 to n-1:\n3) result = result + (upper_bound(a+i, a+n, a[i] + mid) - (a+i+1))\n4) return result" }, { "code": null, "e": 42922, "s": 42527, "text": "Here upper_bound is a variant of binary search which returns a pointer to the first element from a[i] to a[n-1] which is greater than a[i] + mid. Let the pointer returned be j. Then a[i] + mid < a[j]. Thus, subtracting (a+i+1) from this will give us the number of values whose difference with a[i] is <= mid. We sum this up for all indices from 0 to n-1 and get the answer for the current mid. " }, { "code": null, "e": 42926, "s": 42922, "text": "C++" }, { "code": null, "e": 42931, "s": 42926, "text": "Java" }, { "code": null, "e": 42939, "s": 42931, "text": "Python3" }, { "code": null, "e": 42942, "s": 42939, "text": "C#" }, { "code": null, "e": 42953, "s": 42942, "text": "Javascript" }, { "code": "// C++ program to find k-th absolute difference// between two elements#include<bits/stdc++.h>using namespace std; // returns number of pairs with absolute difference// less than or equal to mid.int countPairs(int *a, int n, int mid){ int res = 0; for (int i = 0; i < n; ++i) // Upper bound returns pointer to position // of next higher number than a[i]+mid in // a[i..n-1]. We subtract (a + i + 1) from // this position to count res += upper_bound(a+i, a+n, a[i] + mid) - (a + i + 1); return res;} // Returns k-th absolute differenceint kthDiff(int a[], int n, int k){ // Sort array sort(a, a+n); // Minimum absolute difference int low = a[1] - a[0]; for (int i = 1; i <= n-2; ++i) low = min(low, a[i+1] - a[i]); // Maximum absolute difference int high = a[n-1] - a[0]; // Do binary search for k-th absolute difference while (low < high) { int mid = (low+high)>>1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low;} // Driver codeint main(){ int k = 3; int a[] = {1, 2, 3, 4}; int n = sizeof(a)/sizeof(a[0]); cout << kthDiff(a, n, k); return 0;}", "e": 44219, "s": 42953, "text": null }, { "code": "// Java program to find k-th absolute difference// between two elementsimport java.util.Scanner;import java.util.Arrays; class GFG{ // returns number of pairs with absolute // difference less than or equal to mid static int countPairs(int[] a, int n, int mid) { int res = 0, value; for(int i = 0; i < n; i++) { // Upper bound returns pointer to position // of next higher number than a[i]+mid in // a[i..n-1]. We subtract (ub + i + 1) from // this position to count if(a[i]+mid>a[n-1]) res+=(n-(i+1)); else { int ub = upperbound(a, n, a[i]+mid); res += (ub- (i+1)); } } return res; } // returns the upper bound static int upperbound(int a[], int n, int value) { int low = 0; int high = n; while(low < high) { final int mid = (low + high)/2; if(value >= a[mid]) low = mid + 1; else high = mid; } return low; } // Returns k-th absolute difference static int kthDiff(int a[], int n, int k) { // Sort array Arrays.sort(a); // Minimum absolute difference int low = a[1] - a[0]; for (int i = 1; i <= n-2; ++i) low = Math.min(low, a[i+1] - a[i]); // Maximum absolute difference int high = a[n-1] - a[0]; // Do binary search for k-th absolute difference while (low < high) { int mid = (low + high) >> 1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low; } // Driver function to check the above functions public static void main(String args[]) { Scanner s = new Scanner(System.in); int k = 3; int a[] = {1,2,3,4}; int n = a.length; System.out.println(kthDiff(a, n, k)); } }// This code is contributed by nishkarsh146", "e": 46279, "s": 44219, "text": null }, { "code": "# Python3 program to find # k-th absolute difference # between two elements from bisect import bisect as upper_bound # returns number of pairs with # absolute difference less than # or equal to mid. def countPairs(a, n, mid): res = 0 for i in range(n): # Upper bound returns pointer to position # of next higher number than a[i]+mid in # a[i..n-1]. We subtract (a + i + 1) from # this position to count res += upper_bound(a, a[i] + mid) return res # Returns k-th absolute difference def kthDiff(a, n, k): # Sort array a = sorted(a) # Minimum absolute difference low = a[1] - a[0] for i in range(1, n - 1): low = min(low, a[i + 1] - a[i]) # Maximum absolute difference high = a[n - 1] - a[0] # Do binary search for k-th absolute difference while (low < high): mid = (low + high) >> 1 if (countPairs(a, n, mid) < k): low = mid + 1 else: high = mid return low # Driver code k = 3a = [1, 2, 3, 4] n = len(a) print(kthDiff(a, n, k)) # This code is contributed by Mohit Kumar ", "e": 47419, "s": 46279, "text": null }, { "code": "// C# program to find k-th // absolute difference// between two elementsusing System;class GFG{ // returns number of pairs // with absolute difference // less than or equal to mid static int countPairs(int[] a, int n, int mid){ int res = 0; for(int i = 0; i < n; i++) { // Upper bound returns pointer // to position of next higher // number than a[i]+mid in // a[i..n-1]. We subtract // (ub + i + 1) from // this position to count int ub = upperbound(a, n, a[i] + mid); res += (ub - (i)); } return res;} // returns the upper boundstatic int upperbound(int []a, int n, int value){ int low = 0; int high = n; while(low < high) { int mid = (low + high)/2; if(value >= a[mid]) low = mid + 1; else high = mid; } return low;} // Returns k-th absolute // differencestatic int kthDiff(int []a, int n, int k){ // Sort array Array.Sort(a); // Minimum absolute // difference int low = a[1] - a[0]; for (int i = 1; i <= n - 2; ++i) low = Math.Min(low, a[i + 1] - a[i]); // Maximum absolute // difference int high = a[n - 1] - a[0]; // Do binary search for // k-th absolute difference while (low < high) { int mid = (low + high) >> 1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low;} // Driver codepublic static void Main(String []args){ int k = 3; int []a = {1, 2, 3, 4}; int n = a.Length; Console.WriteLine(kthDiff(a, n, k));}} // This code is contributed by gauravrajput1", "e": 49079, "s": 47419, "text": null }, { "code": "<script> // JavaScript program to find k-th// absolute difference// between two elements // returns number of pairs// with absolute difference// less than or equal to midfunction countPairs(a, n, mid) { let res = 0; for (let i = 0; i < n; i++) { // Upper bound returns pointer // to position of next higher // number than a[i]+mid in // a[i..n-1]. We subtract // (ub + i + 1) from // this position to count let ub = upperbound(a, n, a[i] + mid); res += (ub - (i)); } return res;} // returns the upper boundfunction upperbound(a, n, value) { let low = 0; let high = n; while (low < high) { let mid = (low + high) / 2; if (value >= a[mid]) low = mid + 1; else high = mid; } return low;} // Returns k-th absolute// differencefunction kthDiff(a, n, k) { // Sort array a.sort((a, b) => a - b); // Minimum absolute // difference let low = a[1] - a[0]; for (let i = 1; i <= n - 2; ++i) low = Math.min(low, a[i + 1] - a[i]); // Maximum absolute // difference let high = a[n - 1] - a[0]; // Do binary search for // k-th absolute difference while (low < high) { let mid = (low + high) >> 1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low;} // Driver code let k = 3;let a = [1, 2, 3, 4];let n = a.length;document.write(kthDiff(a, n, k)); // This code is contributed by gfgking </script>", "e": 50648, "s": 49079, "text": null }, { "code": null, "e": 50658, "s": 50648, "text": "Output: " }, { "code": null, "e": 50660, "s": 50658, "text": "1" }, { "code": null, "e": 50760, "s": 50660, "text": "Suppose, maximum element in the array is , and minimum element is minimum element in the array is ." }, { "code": null, "e": 50863, "s": 50760, "text": "Then time taken for the binary_search will be , and time taken for the upper_bound function will be . " }, { "code": null, "e": 51048, "s": 50863, "text": "So, the time complexity of the algorithm is . Sorting takes . After that the main binary search over low and high takes time because each call to the function countPairs takes time . " }, { "code": null, "e": 51090, "s": 51048, "text": "So the Overall time complexity would be " }, { "code": null, "e": 51950, "s": 51090, "text": "YouTubeGeeksforGeeks500K subscribersk-th smallest absolute difference of two elements in an array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ZXpYPeRE66E\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 51992, "s": 51950, "text": "?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p " }, { "code": null, "e": 52414, "s": 51992, "text": "This article is contributed by Hemang Sarkar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 52429, "s": 52414, "text": "mohit kumar 29" }, { "code": null, "e": 52442, "s": 52429, "text": "nishkarsh146" }, { "code": null, "e": 52456, "s": 52442, "text": "GauravRajput1" }, { "code": null, "e": 52464, "s": 52456, "text": "gfgking" }, { "code": null, "e": 52474, "s": 52464, "text": "sankcan55" }, { "code": null, "e": 52488, "s": 52474, "text": "executionover" }, { "code": null, "e": 52502, "s": 52488, "text": "Binary Search" }, { "code": null, "e": 52519, "s": 52502, "text": "Order-Statistics" }, { "code": null, "e": 52526, "s": 52519, "text": "Arrays" }, { "code": null, "e": 52533, "s": 52526, "text": "Arrays" }, { "code": null, "e": 52547, "s": 52533, "text": "Binary Search" }, { "code": null, "e": 52645, "s": 52547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52654, "s": 52645, "text": "Comments" }, { "code": null, "e": 52667, "s": 52654, "text": "Old Comments" }, { "code": null, "e": 52682, "s": 52667, "text": "Arrays in Java" }, { "code": null, "e": 52730, "s": 52682, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 52746, "s": 52730, "text": "Arrays in C/C++" }, { "code": null, "e": 52778, "s": 52746, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 52823, "s": 52778, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 52877, "s": 52823, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 52909, "s": 52877, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 52923, "s": 52909, "text": "Linear Search" }, { "code": null, "e": 52950, "s": 52923, "text": "Program for array rotation" } ]
12 Amazing Pandas & NumPy Functions | by Kunal Dhariwal | Towards Data Science
We all know that Pandas and NumPy are amazing, and they play a crucial role in our day to day analysis. Without Pandas and NumPy, we would be left deserted in this huge world of data analytics and science. Today, I am going to share 12 amazing Pandas and NumPy functions that will make your life and analysis much easier than before. In the end, you can find a Jupyter Notebook for the code used in this article. Let’s start with NumPy: NumPy is the fundamental package for scientific computing with Python. It contains among other things: a powerful N-dimensional array object sophisticated (broadcasting) functions tools for integrating C/C++ and Fortran code useful linear algebra, Fourier transform, and random number capabilities Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases. argpartition() argpartition() NumPy has this amazing function which can find N largest values index. The output will be the N largest values index, and then we can sort the values if needed. x = np.array([12, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 0])index_val = np.argpartition(x, -4)[-4:]index_valarray([1, 8, 2, 0], dtype=int64)np.sort(x[index_val])array([10, 12, 12, 16]) 2. allclose() Allclose() is used for matching two arrays and getting the output in terms of a boolean value. It will return False if items in two arrays are not equal within a tolerance. It is a great way to check if two arrays are similar, which can actually be difficult to implement manually. array1 = np.array([0.12,0.17,0.24,0.29])array2 = np.array([0.13,0.19,0.26,0.31])# with a tolerance of 0.1, it should return False:np.allclose(array1,array2,0.1)False# with a tolerance of 0.2, it should return True:np.allclose(array1,array2,0.2)True 3. clip() Clip() is used to keep values in an array within an interval. Sometimes, we need to keep the values within an upper and lower limit. For the mentioned purpose, we can make use of NumPy’s clip(). Given an interval, values outside the interval are clipped to the interval edges. x = np.array([3, 17, 14, 23, 2, 2, 6, 8, 1, 2, 16, 0])np.clip(x,2,5)array([3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 5, 2]) 4. extract() Extract() as the name goes, is used to extract specific elements from an array based on a certain condition. With extract(), we can also use conditions like and and or. # Random integersarray = np.random.randint(20, size=12)arrayarray([ 0, 1, 8, 19, 16, 18, 10, 11, 2, 13, 14, 3])# Divide by 2 and check if remainder is 1cond = np.mod(array, 2)==1condarray([False, True, False, True, False, False, False, True, False, True, False, True])# Use extract to get the valuesnp.extract(cond, array)array([ 1, 19, 11, 13, 3])# Apply condition on extract directlynp.extract(((array < 3) | (array > 15)), array)array([ 0, 1, 19, 16, 18, 2]) 5. where() Where() is used to return elements from an array that satisfy a certain condition. It returns the index position of values that fall in a certain condition. This is almost similar to the where condition that we use in SQL, I’ll demonstrate that in the examples below. y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greater than 5, returns index positionnp.where(y>5)array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that match the condition, # second will replace the values that does notnp.where(y>5, "Hit", "Miss")array(['Miss', 'Miss', 'Hit', 'Hit', 'Miss', 'Hit', 'Miss', 'Hit', 'Hit'],dtype='<U4') 6. percentile() Percentile() is used to compute the nth percentile of the array elements along the specified axis. a = np.array([1,5,6,8,1,7,3,6,9])print("50th Percentile of a, axis = 0 : ", np.percentile(a, 50, axis =0))50th Percentile of a, axis = 0 : 6.0b = np.array([[10, 7, 4], [3, 2, 1]])print("30th Percentile of b, axis = 0 : ", np.percentile(b, 30, axis =0))30th Percentile of b, axis = 0 : [5.1 3.5 1.9] Let me know if you’ve used them earlier and how far did it help you. Let’s move on to the amazing Pandas. Pandas: pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with structured (tabular, multidimensional, potentially heterogeneous) and time-series data both easy and intuitive. pandas is well suited for many different kinds of data: Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet Ordered and unordered (not necessarily fixed-frequency) time-series data. Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels Any other form of observational/statistical data sets. The data actually need not be labeled at all to be placed into a pandas data structure. Here are just a few of the things that pandas does well: Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional objects Automatic and explicit data alignment: objects can be explicitly aligned to a set of labels, or the user can simply ignore the labels and let Series, DataFrame, etc. automatically align the data for you in computations Powerful, flexible group by functionality to perform split-apply-combine operations on data sets, for both aggregating and transforming data Make it easy to convert ragged, differently-indexed data in other Python and NumPy data structures into DataFrame objects Intelligent label-based slicing, fancy indexing, and subsetting of large data sets Intuitive merging and joining data sets Flexible reshaping and pivoting of data sets Hierarchical labeling of axes (possible to have multiple labels per tick) Robust IO tools for loading data from flat files (CSV and delimited), Excel files, databases, and saving/loading data from the ultrafast HDF5 format Time series-specific functionality: date range generation and frequency conversion, moving window statistics, date shifting and lagging. read_csv(nrows=n) read_csv(nrows=n) You might already be aware of the use of read_csv function. But, most of us still make a mistake of reading the entire .csv file even when it is not required. Let’s consider a situation where we are unaware of the columns and the data present in a .csv file of 10gb, reading whole .csv file here would not be a smart decision because it would be the unnecessary use of our memory and would take a lot of time. We can just import a few rows from the .csv file and then proceed further as per our need. import ioimport requests# I am using this online data set just to make things easier for you guysurl = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/AirPassengers.csv"s = requests.get(url).content# read only first 10 rowsdf = pd.read_csv(io.StringIO(s.decode('utf-8')),nrows=10 , index_col=0) 2. map() The map() function is used to map values of Series according to input correspondence. Used for substituting each value in a Series with another value, that may be derived from a function, a dict or a Series. # create a dataframedframe = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['India', 'USA', 'China', 'Russia'])#compute a formatted string from each floating point value in framechangefn = lambda x: '%.2f' % x# Make changes element-wisedframe['d'].map(changefn) 3. apply() The apply() allows the users to pass a function and apply it on every single value of the Pandas series. # max minus mix lambda fnfn = lambda x: x.max() - x.min()# Apply this on dframe that we've just created abovedframe.apply(fn) 4. isin() The isin() is used to filter data frames. isin() helps in selecting rows with having a particular(or Multiple) value in a particular column. It is the most useful function I’ve come across. # Using the dataframe we created for read_csvfilter1 = df["value"].isin([112]) filter2 = df["time"].isin([1949.000000])df [filter1 & filter2] 5. copy() The copy() is used to create a copy of a Pandas object. When you assign a data frame to another data frame, its value changes when you make changes in the other one. To prevent the mentioned issue, we can make use of copy(). # creating sample series data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issue that we facedata1= data# Change a valuedata1[0]='USA'# Also changes value in old dataframedata# To prevent that, we use# creating copy of series new = data.copy()# assigning new values new[1]='Changed value'# printing data print(new) print(data) 6. select_dtypes() The select_dtypes() function returns a subset of the data frame's columns based on the column dtypes. The parameters of this function can be set to include all the columns having some specific data type or it could be set to exclude all those columns which has some specific data types. # We'll use the same dataframe that we used for read_csvframex = df.select_dtypes(include="float64")# Returns only time column Bonus: pivot_table() The most amazing and useful function of pandas is pivot_table. If you hesitate to use groupby and want to extend its functionalities then you can very well use the pivot_table. If you’re aware of how pivot table works in excel, then it’s might be a piece of cake for you. Levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. # Create a sample dataframeschool = pd.DataFrame({'A': ['Jay', 'Usher', 'Nicky', 'Romero', 'Will'], 'B': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'], 'C': [26, 22, 20, 23, 24]})# Lets create a pivot table to segregate students based on age and coursetable = pd.pivot_table(school, values ='A', index =['B', 'C'], columns =['B'], aggfunc = np.sum, fill_value="Not Available") table Do let me know down below in the comments if you guys have come across or used any other amazing functions. I would love to know more about them. Jupyter Notebook (Code used) : https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions LinkedIn: https://bit.ly/2u4YPoF I hope that this has helped you to enhance your knowledge base :) Follow me for more! Thanks for your read and valuable time!
[ { "code": null, "e": 584, "s": 171, "text": "We all know that Pandas and NumPy are amazing, and they play a crucial role in our day to day analysis. Without Pandas and NumPy, we would be left deserted in this huge world of data analytics and science. Today, I am going to share 12 amazing Pandas and NumPy functions that will make your life and analysis much easier than before. In the end, you can find a Jupyter Notebook for the code used in this article." }, { "code": null, "e": 608, "s": 584, "text": "Let’s start with NumPy:" }, { "code": null, "e": 711, "s": 608, "text": "NumPy is the fundamental package for scientific computing with Python. It contains among other things:" }, { "code": null, "e": 749, "s": 711, "text": "a powerful N-dimensional array object" }, { "code": null, "e": 788, "s": 749, "text": "sophisticated (broadcasting) functions" }, { "code": null, "e": 833, "s": 788, "text": "tools for integrating C/C++ and Fortran code" }, { "code": null, "e": 906, "s": 833, "text": "useful linear algebra, Fourier transform, and random number capabilities" }, { "code": null, "e": 1153, "s": 906, "text": "Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases." }, { "code": null, "e": 1168, "s": 1153, "text": "argpartition()" }, { "code": null, "e": 1183, "s": 1168, "text": "argpartition()" }, { "code": null, "e": 1344, "s": 1183, "text": "NumPy has this amazing function which can find N largest values index. The output will be the N largest values index, and then we can sort the values if needed." }, { "code": null, "e": 1523, "s": 1344, "text": "x = np.array([12, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 0])index_val = np.argpartition(x, -4)[-4:]index_valarray([1, 8, 2, 0], dtype=int64)np.sort(x[index_val])array([10, 12, 12, 16])" }, { "code": null, "e": 1537, "s": 1523, "text": "2. allclose()" }, { "code": null, "e": 1819, "s": 1537, "text": "Allclose() is used for matching two arrays and getting the output in terms of a boolean value. It will return False if items in two arrays are not equal within a tolerance. It is a great way to check if two arrays are similar, which can actually be difficult to implement manually." }, { "code": null, "e": 2068, "s": 1819, "text": "array1 = np.array([0.12,0.17,0.24,0.29])array2 = np.array([0.13,0.19,0.26,0.31])# with a tolerance of 0.1, it should return False:np.allclose(array1,array2,0.1)False# with a tolerance of 0.2, it should return True:np.allclose(array1,array2,0.2)True" }, { "code": null, "e": 2078, "s": 2068, "text": "3. clip()" }, { "code": null, "e": 2355, "s": 2078, "text": "Clip() is used to keep values in an array within an interval. Sometimes, we need to keep the values within an upper and lower limit. For the mentioned purpose, we can make use of NumPy’s clip(). Given an interval, values outside the interval are clipped to the interval edges." }, { "code": null, "e": 2467, "s": 2355, "text": "x = np.array([3, 17, 14, 23, 2, 2, 6, 8, 1, 2, 16, 0])np.clip(x,2,5)array([3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 5, 2])" }, { "code": null, "e": 2480, "s": 2467, "text": "4. extract()" }, { "code": null, "e": 2649, "s": 2480, "text": "Extract() as the name goes, is used to extract specific elements from an array based on a certain condition. With extract(), we can also use conditions like and and or." }, { "code": null, "e": 3123, "s": 2649, "text": "# Random integersarray = np.random.randint(20, size=12)arrayarray([ 0, 1, 8, 19, 16, 18, 10, 11, 2, 13, 14, 3])# Divide by 2 and check if remainder is 1cond = np.mod(array, 2)==1condarray([False, True, False, True, False, False, False, True, False, True, False, True])# Use extract to get the valuesnp.extract(cond, array)array([ 1, 19, 11, 13, 3])# Apply condition on extract directlynp.extract(((array < 3) | (array > 15)), array)array([ 0, 1, 19, 16, 18, 2])" }, { "code": null, "e": 3134, "s": 3123, "text": "5. where()" }, { "code": null, "e": 3402, "s": 3134, "text": "Where() is used to return elements from an array that satisfy a certain condition. It returns the index position of values that fall in a certain condition. This is almost similar to the where condition that we use in SQL, I’ll demonstrate that in the examples below." }, { "code": null, "e": 3755, "s": 3402, "text": "y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greater than 5, returns index positionnp.where(y>5)array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that match the condition, # second will replace the values that does notnp.where(y>5, \"Hit\", \"Miss\")array(['Miss', 'Miss', 'Hit', 'Hit', 'Miss', 'Hit', 'Miss', 'Hit', 'Hit'],dtype='<U4')" }, { "code": null, "e": 3771, "s": 3755, "text": "6. percentile()" }, { "code": null, "e": 3870, "s": 3771, "text": "Percentile() is used to compute the nth percentile of the array elements along the specified axis." }, { "code": null, "e": 4185, "s": 3870, "text": "a = np.array([1,5,6,8,1,7,3,6,9])print(\"50th Percentile of a, axis = 0 : \", np.percentile(a, 50, axis =0))50th Percentile of a, axis = 0 : 6.0b = np.array([[10, 7, 4], [3, 2, 1]])print(\"30th Percentile of b, axis = 0 : \", np.percentile(b, 30, axis =0))30th Percentile of b, axis = 0 : [5.1 3.5 1.9]" }, { "code": null, "e": 4291, "s": 4185, "text": "Let me know if you’ve used them earlier and how far did it help you. Let’s move on to the amazing Pandas." }, { "code": null, "e": 4299, "s": 4291, "text": "Pandas:" }, { "code": null, "e": 4525, "s": 4299, "text": "pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with structured (tabular, multidimensional, potentially heterogeneous) and time-series data both easy and intuitive." }, { "code": null, "e": 4581, "s": 4525, "text": "pandas is well suited for many different kinds of data:" }, { "code": null, "e": 4670, "s": 4581, "text": "Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet" }, { "code": null, "e": 4744, "s": 4670, "text": "Ordered and unordered (not necessarily fixed-frequency) time-series data." }, { "code": null, "e": 4832, "s": 4744, "text": "Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels" }, { "code": null, "e": 4975, "s": 4832, "text": "Any other form of observational/statistical data sets. The data actually need not be labeled at all to be placed into a pandas data structure." }, { "code": null, "e": 5032, "s": 4975, "text": "Here are just a few of the things that pandas does well:" }, { "code": null, "e": 5136, "s": 5032, "text": "Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data" }, { "code": null, "e": 5235, "s": 5136, "text": "Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional objects" }, { "code": null, "e": 5454, "s": 5235, "text": "Automatic and explicit data alignment: objects can be explicitly aligned to a set of labels, or the user can simply ignore the labels and let Series, DataFrame, etc. automatically align the data for you in computations" }, { "code": null, "e": 5595, "s": 5454, "text": "Powerful, flexible group by functionality to perform split-apply-combine operations on data sets, for both aggregating and transforming data" }, { "code": null, "e": 5717, "s": 5595, "text": "Make it easy to convert ragged, differently-indexed data in other Python and NumPy data structures into DataFrame objects" }, { "code": null, "e": 5800, "s": 5717, "text": "Intelligent label-based slicing, fancy indexing, and subsetting of large data sets" }, { "code": null, "e": 5840, "s": 5800, "text": "Intuitive merging and joining data sets" }, { "code": null, "e": 5885, "s": 5840, "text": "Flexible reshaping and pivoting of data sets" }, { "code": null, "e": 5959, "s": 5885, "text": "Hierarchical labeling of axes (possible to have multiple labels per tick)" }, { "code": null, "e": 6108, "s": 5959, "text": "Robust IO tools for loading data from flat files (CSV and delimited), Excel files, databases, and saving/loading data from the ultrafast HDF5 format" }, { "code": null, "e": 6245, "s": 6108, "text": "Time series-specific functionality: date range generation and frequency conversion, moving window statistics, date shifting and lagging." }, { "code": null, "e": 6263, "s": 6245, "text": "read_csv(nrows=n)" }, { "code": null, "e": 6281, "s": 6263, "text": "read_csv(nrows=n)" }, { "code": null, "e": 6782, "s": 6281, "text": "You might already be aware of the use of read_csv function. But, most of us still make a mistake of reading the entire .csv file even when it is not required. Let’s consider a situation where we are unaware of the columns and the data present in a .csv file of 10gb, reading whole .csv file here would not be a smart decision because it would be the unnecessary use of our memory and would take a lot of time. We can just import a few rows from the .csv file and then proceed further as per our need." }, { "code": null, "e": 7102, "s": 6782, "text": "import ioimport requests# I am using this online data set just to make things easier for you guysurl = \"https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/AirPassengers.csv\"s = requests.get(url).content# read only first 10 rowsdf = pd.read_csv(io.StringIO(s.decode('utf-8')),nrows=10 , index_col=0)" }, { "code": null, "e": 7111, "s": 7102, "text": "2. map()" }, { "code": null, "e": 7319, "s": 7111, "text": "The map() function is used to map values of Series according to input correspondence. Used for substituting each value in a Series with another value, that may be derived from a function, a dict or a Series." }, { "code": null, "e": 7598, "s": 7319, "text": "# create a dataframedframe = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['India', 'USA', 'China', 'Russia'])#compute a formatted string from each floating point value in framechangefn = lambda x: '%.2f' % x# Make changes element-wisedframe['d'].map(changefn)" }, { "code": null, "e": 7609, "s": 7598, "text": "3. apply()" }, { "code": null, "e": 7714, "s": 7609, "text": "The apply() allows the users to pass a function and apply it on every single value of the Pandas series." }, { "code": null, "e": 7840, "s": 7714, "text": "# max minus mix lambda fnfn = lambda x: x.max() - x.min()# Apply this on dframe that we've just created abovedframe.apply(fn)" }, { "code": null, "e": 7850, "s": 7840, "text": "4. isin()" }, { "code": null, "e": 8040, "s": 7850, "text": "The isin() is used to filter data frames. isin() helps in selecting rows with having a particular(or Multiple) value in a particular column. It is the most useful function I’ve come across." }, { "code": null, "e": 8182, "s": 8040, "text": "# Using the dataframe we created for read_csvfilter1 = df[\"value\"].isin([112]) filter2 = df[\"time\"].isin([1949.000000])df [filter1 & filter2]" }, { "code": null, "e": 8192, "s": 8182, "text": "5. copy()" }, { "code": null, "e": 8417, "s": 8192, "text": "The copy() is used to create a copy of a Pandas object. When you assign a data frame to another data frame, its value changes when you make changes in the other one. To prevent the mentioned issue, we can make use of copy()." }, { "code": null, "e": 8766, "s": 8417, "text": "# creating sample series data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issue that we facedata1= data# Change a valuedata1[0]='USA'# Also changes value in old dataframedata# To prevent that, we use# creating copy of series new = data.copy()# assigning new values new[1]='Changed value'# printing data print(new) print(data)" }, { "code": null, "e": 8785, "s": 8766, "text": "6. select_dtypes()" }, { "code": null, "e": 9072, "s": 8785, "text": "The select_dtypes() function returns a subset of the data frame's columns based on the column dtypes. The parameters of this function can be set to include all the columns having some specific data type or it could be set to exclude all those columns which has some specific data types." }, { "code": null, "e": 9200, "s": 9072, "text": "# We'll use the same dataframe that we used for read_csvframex = df.select_dtypes(include=\"float64\")# Returns only time column" }, { "code": null, "e": 9207, "s": 9200, "text": "Bonus:" }, { "code": null, "e": 9221, "s": 9207, "text": "pivot_table()" }, { "code": null, "e": 9629, "s": 9221, "text": "The most amazing and useful function of pandas is pivot_table. If you hesitate to use groupby and want to extend its functionalities then you can very well use the pivot_table. If you’re aware of how pivot table works in excel, then it’s might be a piece of cake for you. Levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame." }, { "code": null, "e": 10064, "s": 9629, "text": "# Create a sample dataframeschool = pd.DataFrame({'A': ['Jay', 'Usher', 'Nicky', 'Romero', 'Will'], 'B': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'], 'C': [26, 22, 20, 23, 24]})# Lets create a pivot table to segregate students based on age and coursetable = pd.pivot_table(school, values ='A', index =['B', 'C'], columns =['B'], aggfunc = np.sum, fill_value=\"Not Available\") table" }, { "code": null, "e": 10210, "s": 10064, "text": "Do let me know down below in the comments if you guys have come across or used any other amazing functions. I would love to know more about them." }, { "code": null, "e": 10315, "s": 10210, "text": "Jupyter Notebook (Code used) : https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions" }, { "code": null, "e": 10348, "s": 10315, "text": "LinkedIn: https://bit.ly/2u4YPoF" }, { "code": null, "e": 10414, "s": 10348, "text": "I hope that this has helped you to enhance your knowledge base :)" }, { "code": null, "e": 10434, "s": 10414, "text": "Follow me for more!" } ]
Find maximum depth of nested parenthesis in a string - GeeksforGeeks
25 Mar, 2022 We are given a string having parenthesis like below “( ((X)) (((Y))) )” We need to find the maximum depth of balanced parenthesis, like 4 in the above example. Since ‘Y’ is surrounded by 4 balanced parentheses. If parenthesis is unbalanced then return -1. Examples : Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)"; Output : 4 Input : S = "( p((q)) ((s)t) )"; Output : 3 Input : S = ""; Output : 0 Input : S = "b) (c) ()"; Output : -1 Input : S = "(b) ((c) ()" Output : -1 Method 1 (Uses Stack) A simple solution is to use a stack that keeps track of current open brackets. 1) Create a stack. 2) Traverse the string, do following for every character a) If current character is ‘(’ push it to the stack . b) If character is ‘)’, pop an element. c) Maintain maximum count during the traversal. Below is the code implementation of the algorithm. C++ Java // A C++ program to find the maximum depth of nested// parenthesis in a given expression#include <bits/stdc++.h>using namespace std; int maxDepth(string& s){ int count = 0; stack<int> st; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') st.push(i); // pushing the bracket in the stack else if (s[i] == ')') { if (count < st.size()) count = st.size(); /*keeping track of the parenthesis and storing it before removing it when it gets balanced*/ st.pop(); } } return count;} // Driver programint main(){ string s = "( ((X)) (((Y))) )"; cout << maxDepth(s); // This code is contributed by rakeshsahni return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static int maxDepth(String s) { int count=0; Stack<Integer> st = new Stack<>(); for(int i=0;i<s.length();i++) { if(s.charAt(i) == '(') st.push(i);//pushing the bracket in the stack else if(s.charAt(i) == ')') { if(count < st.size()) count = st.size(); /*keeping track of the parenthesis and storing it before removing it when it gets balanced*/ st.pop(); } } return count;} public static void main (String[] args) { System.out.println(maxDepth("( ((X)) (((Y))) )")); }} 4 Time Complexity : O(n) Auxiliary Space : O(n) Method 2 ( O(1) auxiliary space ) This can also be done without using stack. 1) Take two variables max and current_max, initialize both of them as 0. 2) Traverse the string, do following for every character a) If current character is ‘(’, increment current_max and update max value if required. b) If character is ‘)’. Check if current_max is positive or not (this condition ensure that parenthesis are balanced). If positive that means we previously had a ‘(’ character so decrement current_max without worry. If not positive then the parenthesis are not balanced. Thus return -1. 3) If current_max is not 0, then return -1 to ensure that the parenthesis are balanced. Else return max Below is the implementation of the above algorithm. C++ Java Python3 C# PHP Javascript // A C++ program to find the maximum depth of nested// parenthesis in a given expression#include <iostream>using namespace std; // function takes a string and returns the// maximum depth nested parenthesisint maxDepth(string S){ int current_max = 0; // current count int max = 0; // overall maximum count int n = S.length(); // Traverse the input string for (int i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // update max if required if (current_max > max) max = current_max; } else if (S[i] == ')') { if (current_max > 0) current_max--; else return -1; } } // finally check for unbalanced string if (current_max != 0) return -1; return max;} // Driver programint main(){ string s = "( ((X)) (((Y))) )"; cout << maxDepth(s); return 0;} //Java program to find the maximum depth of nested// parenthesis in a given expression class GFG {// function takes a string and returns the// maximum depth nested parenthesis static int maxDepth(String S) { int current_max = 0; // current count int max = 0; // overall maximum count int n = S.length(); // Traverse the input string for (int i = 0; i < n; i++) { if (S.charAt(i) == '(') { current_max++; // update max if required if (current_max > max) { max = current_max; } } else if (S.charAt(i) == ')') { if (current_max > 0) { current_max--; } else { return -1; } } } // finally check for unbalanced string if (current_max != 0) { return -1; } return max; } // Driver program public static void main(String[] args) { String s = "( ((X)) (((Y))) )"; System.out.println(maxDepth(s)); }} # A Python program to find the maximum depth of nested# parenthesis in a given expression # function takes a string and returns the# maximum depth nested parenthesisdef maxDepth(S): current_max = 0 max = 0 n = len(S) # Traverse the input string for i in range(n): if S[i] == '(': current_max += 1 if current_max > max: max = current_max else if S[i] == ')': if current_max > 0: current_max -= 1 else: return -1 # finally check for unbalanced string if current_max != 0: return -1 return max # Driver programs = "( ((X)) (((Y))) )"print (maxDepth(s)) # This code is contributed by BHAVYA JAIN // C# program to find the// maximum depth of nested// parenthesis in a given expressionusing System;class GFG { // function takes a string// and returns the maximum// depth nested parenthesis static int maxDepth(string S){ // current count int current_max = 0; // overall maximum count int max = 0; int n = S.Length; // Traverse the input string for (int i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // update max if required if (current_max > max) { max = current_max; } } else if (S[i] == ')') { if (current_max > 0) { current_max--; } else { return -1; } } } // finally check for unbalanced string if (current_max != 0) { return -1; } return max;} // Driver programpublic static void Main(){ string s = "(((X)) (((Y))))"; Console.Write(maxDepth(s));}} // This code is contributed by Chitranayal <?php// A PHP program to find the// maximum depth of nested// parenthesis in a given// expression // function takes a string // and returns the maximum// depth nested parenthesisfunction maxDepth($S){ // current count $current_max = 0; // overall maximum count $max = 0; $n = strlen($S); // Traverse the input string for ($i = 0; $i < $n; $i++) { if ($S[$i] == '(') { $current_max++; // update max if required if ($current_max> $max) $max = $current_max; } else if ($S[$i] == ')') { if ($current_max>0) $current_max--; else return -1; } } // finally check for // unbalanced string if ($current_max != 0) return -1; return $max;} // Driver Code$s = "( ((X)) (((Y))) )";echo maxDepth($s); // This code is contributed by mits?> <script> // Javascript program to find the// maximum depth of nested parenthesis// in a given expression // Function takes a string and returns the// maximum depth nested parenthesisfunction maxDepth(S){ // Current count let current_max = 0; // Overall maximum count let max = 0; let n = S.length; // Traverse the input string for(let i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // Update max if required if (current_max > max) { max = current_max; } } else if (S[i] == ')') { if (current_max > 0) { current_max--; } else { return -1; } } } // Finally check for unbalanced string if (current_max != 0) { return -1; } return max;} // Driver codelet s = "( ((X)) (((Y))) )"; document.write(maxDepth(s)); // This code is contributed by avanitrachhadiya2155 </script> 4 Time Complexity: O(n) Auxiliary Space: O(1) YouTubeGeeksforGeeks502K subscribersFind maximum depth of nested parenthesis in a string | GeeksforGeeksWatch 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:000:00 / 5:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IOQi3aJFIaM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySF7Lap-wi5qlaD8OEBx9RMV This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar princiraj1992 AvirupDutta ukasp avanitrachhadiya2155 amartyaghoshgfg surinderdawra388 ritiksahu9312 rakeshsahni Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Inorder Tree Traversal without Recursion Implement a stack using singly linked list Implement Stack using Queues Merge Overlapping Intervals Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25124, "s": 25096, "text": "\n25 Mar, 2022" }, { "code": null, "e": 25386, "s": 25124, "text": "We are given a string having parenthesis like below “( ((X)) (((Y))) )” We need to find the maximum depth of balanced parenthesis, like 4 in the above example. Since ‘Y’ is surrounded by 4 balanced parentheses. If parenthesis is unbalanced then return -1. " }, { "code": null, "e": 25398, "s": 25386, "text": "Examples : " }, { "code": null, "e": 25611, "s": 25398, "text": "Input : S = \"( a(b) (c) (d(e(f)g)h) I (j(k)l)m)\";\nOutput : 4\n\nInput : S = \"( p((q)) ((s)t) )\";\nOutput : 3\n\nInput : S = \"\";\nOutput : 0\n\nInput : S = \"b) (c) ()\";\nOutput : -1 \n\nInput : S = \"(b) ((c) ()\"\nOutput : -1 " }, { "code": null, "e": 25713, "s": 25611, "text": "Method 1 (Uses Stack) A simple solution is to use a stack that keeps track of current open brackets. " }, { "code": null, "e": 25948, "s": 25713, "text": "1) Create a stack. \n2) Traverse the string, do following for every character\n a) If current character is ‘(’ push it to the stack .\n b) If character is ‘)’, pop an element.\n c) Maintain maximum count during the traversal. " }, { "code": null, "e": 25999, "s": 25948, "text": "Below is the code implementation of the algorithm." }, { "code": null, "e": 26003, "s": 25999, "text": "C++" }, { "code": null, "e": 26008, "s": 26003, "text": "Java" }, { "code": "// A C++ program to find the maximum depth of nested// parenthesis in a given expression#include <bits/stdc++.h>using namespace std; int maxDepth(string& s){ int count = 0; stack<int> st; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') st.push(i); // pushing the bracket in the stack else if (s[i] == ')') { if (count < st.size()) count = st.size(); /*keeping track of the parenthesis and storing it before removing it when it gets balanced*/ st.pop(); } } return count;} // Driver programint main(){ string s = \"( ((X)) (((Y))) )\"; cout << maxDepth(s); // This code is contributed by rakeshsahni return 0;}", "e": 26743, "s": 26008, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static int maxDepth(String s) { int count=0; Stack<Integer> st = new Stack<>(); for(int i=0;i<s.length();i++) { if(s.charAt(i) == '(') st.push(i);//pushing the bracket in the stack else if(s.charAt(i) == ')') { if(count < st.size()) count = st.size(); /*keeping track of the parenthesis and storing it before removing it when it gets balanced*/ st.pop(); } } return count;} public static void main (String[] args) { System.out.println(maxDepth(\"( ((X)) (((Y))) )\")); }}", "e": 27524, "s": 26743, "text": null }, { "code": null, "e": 27526, "s": 27524, "text": "4" }, { "code": null, "e": 27572, "s": 27526, "text": "Time Complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 27651, "s": 27572, "text": "Method 2 ( O(1) auxiliary space ) This can also be done without using stack. " }, { "code": null, "e": 28319, "s": 27651, "text": "1) Take two variables max and current_max, initialize both of them as 0.\n2) Traverse the string, do following for every character\n a) If current character is ‘(’, increment current_max and \n update max value if required.\n b) If character is ‘)’. Check if current_max is positive or\n not (this condition ensure that parenthesis are balanced). \n If positive that means we previously had a ‘(’ character \n so decrement current_max without worry. \n If not positive then the parenthesis are not balanced. \n Thus return -1. \n3) If current_max is not 0, then return -1 to ensure that the parenthesis\n are balanced. Else return max" }, { "code": null, "e": 28371, "s": 28319, "text": "Below is the implementation of the above algorithm." }, { "code": null, "e": 28375, "s": 28371, "text": "C++" }, { "code": null, "e": 28380, "s": 28375, "text": "Java" }, { "code": null, "e": 28388, "s": 28380, "text": "Python3" }, { "code": null, "e": 28391, "s": 28388, "text": "C#" }, { "code": null, "e": 28395, "s": 28391, "text": "PHP" }, { "code": null, "e": 28406, "s": 28395, "text": "Javascript" }, { "code": "// A C++ program to find the maximum depth of nested// parenthesis in a given expression#include <iostream>using namespace std; // function takes a string and returns the// maximum depth nested parenthesisint maxDepth(string S){ int current_max = 0; // current count int max = 0; // overall maximum count int n = S.length(); // Traverse the input string for (int i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // update max if required if (current_max > max) max = current_max; } else if (S[i] == ')') { if (current_max > 0) current_max--; else return -1; } } // finally check for unbalanced string if (current_max != 0) return -1; return max;} // Driver programint main(){ string s = \"( ((X)) (((Y))) )\"; cout << maxDepth(s); return 0;}", "e": 29344, "s": 28406, "text": null }, { "code": "//Java program to find the maximum depth of nested// parenthesis in a given expression class GFG {// function takes a string and returns the// maximum depth nested parenthesis static int maxDepth(String S) { int current_max = 0; // current count int max = 0; // overall maximum count int n = S.length(); // Traverse the input string for (int i = 0; i < n; i++) { if (S.charAt(i) == '(') { current_max++; // update max if required if (current_max > max) { max = current_max; } } else if (S.charAt(i) == ')') { if (current_max > 0) { current_max--; } else { return -1; } } } // finally check for unbalanced string if (current_max != 0) { return -1; } return max; } // Driver program public static void main(String[] args) { String s = \"( ((X)) (((Y))) )\"; System.out.println(maxDepth(s)); }}", "e": 30441, "s": 29344, "text": null }, { "code": "# A Python program to find the maximum depth of nested# parenthesis in a given expression # function takes a string and returns the# maximum depth nested parenthesisdef maxDepth(S): current_max = 0 max = 0 n = len(S) # Traverse the input string for i in range(n): if S[i] == '(': current_max += 1 if current_max > max: max = current_max else if S[i] == ')': if current_max > 0: current_max -= 1 else: return -1 # finally check for unbalanced string if current_max != 0: return -1 return max # Driver programs = \"( ((X)) (((Y))) )\"print (maxDepth(s)) # This code is contributed by BHAVYA JAIN", "e": 31171, "s": 30441, "text": null }, { "code": "// C# program to find the// maximum depth of nested// parenthesis in a given expressionusing System;class GFG { // function takes a string// and returns the maximum// depth nested parenthesis static int maxDepth(string S){ // current count int current_max = 0; // overall maximum count int max = 0; int n = S.Length; // Traverse the input string for (int i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // update max if required if (current_max > max) { max = current_max; } } else if (S[i] == ')') { if (current_max > 0) { current_max--; } else { return -1; } } } // finally check for unbalanced string if (current_max != 0) { return -1; } return max;} // Driver programpublic static void Main(){ string s = \"(((X)) (((Y))))\"; Console.Write(maxDepth(s));}} // This code is contributed by Chitranayal", "e": 32104, "s": 31171, "text": null }, { "code": "<?php// A PHP program to find the// maximum depth of nested// parenthesis in a given// expression // function takes a string // and returns the maximum// depth nested parenthesisfunction maxDepth($S){ // current count $current_max = 0; // overall maximum count $max = 0; $n = strlen($S); // Traverse the input string for ($i = 0; $i < $n; $i++) { if ($S[$i] == '(') { $current_max++; // update max if required if ($current_max> $max) $max = $current_max; } else if ($S[$i] == ')') { if ($current_max>0) $current_max--; else return -1; } } // finally check for // unbalanced string if ($current_max != 0) return -1; return $max;} // Driver Code$s = \"( ((X)) (((Y))) )\";echo maxDepth($s); // This code is contributed by mits?>", "e": 33035, "s": 32104, "text": null }, { "code": "<script> // Javascript program to find the// maximum depth of nested parenthesis// in a given expression // Function takes a string and returns the// maximum depth nested parenthesisfunction maxDepth(S){ // Current count let current_max = 0; // Overall maximum count let max = 0; let n = S.length; // Traverse the input string for(let i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // Update max if required if (current_max > max) { max = current_max; } } else if (S[i] == ')') { if (current_max > 0) { current_max--; } else { return -1; } } } // Finally check for unbalanced string if (current_max != 0) { return -1; } return max;} // Driver codelet s = \"( ((X)) (((Y))) )\"; document.write(maxDepth(s)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 34100, "s": 33035, "text": null }, { "code": null, "e": 34102, "s": 34100, "text": "4" }, { "code": null, "e": 34147, "s": 34102, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 34998, "s": 34147, "text": "YouTubeGeeksforGeeks502K subscribersFind maximum depth of nested parenthesis in a string | GeeksforGeeksWatch 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:000:00 / 5:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IOQi3aJFIaM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 35040, "s": 34998, "text": "?list=PLqM7alHXFySF7Lap-wi5qlaD8OEBx9RMV " }, { "code": null, "e": 35211, "s": 35040, "text": "This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35226, "s": 35213, "text": "Mithun Kumar" }, { "code": null, "e": 35240, "s": 35226, "text": "princiraj1992" }, { "code": null, "e": 35252, "s": 35240, "text": "AvirupDutta" }, { "code": null, "e": 35258, "s": 35252, "text": "ukasp" }, { "code": null, "e": 35279, "s": 35258, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35295, "s": 35279, "text": "amartyaghoshgfg" }, { "code": null, "e": 35312, "s": 35295, "text": "surinderdawra388" }, { "code": null, "e": 35326, "s": 35312, "text": "ritiksahu9312" }, { "code": null, "e": 35338, "s": 35326, "text": "rakeshsahni" }, { "code": null, "e": 35344, "s": 35338, "text": "Stack" }, { "code": null, "e": 35352, "s": 35344, "text": "Strings" }, { "code": null, "e": 35360, "s": 35352, "text": "Strings" }, { "code": null, "e": 35366, "s": 35360, "text": "Stack" }, { "code": null, "e": 35464, "s": 35366, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35491, "s": 35464, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 35532, "s": 35491, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 35575, "s": 35532, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 35604, "s": 35575, "text": "Implement Stack using Queues" }, { "code": null, "e": 35632, "s": 35604, "text": "Merge Overlapping Intervals" }, { "code": null, "e": 35657, "s": 35632, "text": "Reverse a string in Java" }, { "code": null, "e": 35703, "s": 35657, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35737, "s": 35703, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35797, "s": 35737, "text": "Write a program to print all permutations of a given string" } ]
File getAbsolutePath() method in Java with Examples - GeeksforGeeks
30 Jan, 2019 The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object.If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using an IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete). The function getAbsolutePath() will return the absolute (complete) path from the root directories. If the file object is created with an absolute path then getPath() and getAbsolutePath() will give the same results. Function Signature: public String getAbsolutePath() Function Syntax: file.getAbsolutePath() Parameters: This function does not accept any parameters. Return value: This function returns a String value which is the absolute Path of the given File object. Exception: This method throws Security Exception if the required property value cannot be accessed. Below programs will illustrate the use of getAbsolutePath() method: Example 1: A file named “program.txt” is in the present working directory. // Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("program.txt"); // Get the absolute path of file f String absolute = f.getAbsolutePath(); // Display the file path of the file object // and also the file path of absolute file System.out.println("Original path: " + f.getPath()); System.out.println("Absolute path: " + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }} Output: Original Path: program.txt Absolute Path: C:\Users\pc\eclipse-workspace1\arnab\program.txt Example 2: A directory named “program” is in the present working directory. // Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String try-catch { // try catch block to handle exceptions try { // Create a file object File f = new File("program"); // Get the absolute path of file f String absolute = f.getAbsolutePath(); // Display the file path of the file object // and also the file path of absolute file System.out.println("Original path: " + f.getPath()); System.out.println("Absolute path: " + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }} Output: Original Path: program Absolute Path: C:\Users\pc\eclipse-workspace1\arnab\program Example 3: A file named “f:\program.txt” in the “f:\” directory. // Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String args[]) { // try catch block to handle exceptions try { // Create a file object File f = new File("f:\\program.txt"); // get the absolute path // of file f String absolute = f.getAbsolutePath(); // display the file path of the file object // and also the file path of absolute file System.out.println("Original path: " + f.getPath()); System.out.println("Absolute path: " + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }} Output: Original file path: f:\program.txt Absolute file path: f:\program.txt The programs might not run in an online IDE . please use an offline IDE and set the path of the file Java-File Class Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Singleton Class in Java Set in Java LinkedList in Java Collections in Java Overriding in Java Multithreading in Java Queue Interface In Java Different ways of Reading a text file in Java Initializing a List in Java
[ { "code": null, "e": 24935, "s": 24907, "text": "\n30 Jan, 2019" }, { "code": null, "e": 25165, "s": 24935, "text": "The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object.If the pathname of the file object is absolute then it simply returns the path of the current file object." }, { "code": null, "e": 25740, "s": 25165, "text": "For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using an IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete). The function getAbsolutePath() will return the absolute (complete) path from the root directories. If the file object is created with an absolute path then getPath() and getAbsolutePath() will give the same results." }, { "code": null, "e": 25760, "s": 25740, "text": "Function Signature:" }, { "code": null, "e": 25792, "s": 25760, "text": "public String getAbsolutePath()" }, { "code": null, "e": 25809, "s": 25792, "text": "Function Syntax:" }, { "code": null, "e": 25832, "s": 25809, "text": "file.getAbsolutePath()" }, { "code": null, "e": 25890, "s": 25832, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 25994, "s": 25890, "text": "Return value: This function returns a String value which is the absolute Path of the given File object." }, { "code": null, "e": 26094, "s": 25994, "text": "Exception: This method throws Security Exception if the required property value cannot be accessed." }, { "code": null, "e": 26162, "s": 26094, "text": "Below programs will illustrate the use of getAbsolutePath() method:" }, { "code": null, "e": 26237, "s": 26162, "text": "Example 1: A file named “program.txt” is in the present working directory." }, { "code": "// Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"program.txt\"); // Get the absolute path of file f String absolute = f.getAbsolutePath(); // Display the file path of the file object // and also the file path of absolute file System.out.println(\"Original path: \" + f.getPath()); System.out.println(\"Absolute path: \" + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }}", "e": 27039, "s": 26237, "text": null }, { "code": null, "e": 27047, "s": 27039, "text": "Output:" }, { "code": null, "e": 27139, "s": 27047, "text": "Original Path: program.txt\nAbsolute Path: C:\\Users\\pc\\eclipse-workspace1\\arnab\\program.txt\n" }, { "code": null, "e": 27215, "s": 27139, "text": "Example 2: A directory named “program” is in the present working directory." }, { "code": "// Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String try-catch { // try catch block to handle exceptions try { // Create a file object File f = new File(\"program\"); // Get the absolute path of file f String absolute = f.getAbsolutePath(); // Display the file path of the file object // and also the file path of absolute file System.out.println(\"Original path: \" + f.getPath()); System.out.println(\"Absolute path: \" + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }}", "e": 28012, "s": 27215, "text": null }, { "code": null, "e": 28020, "s": 28012, "text": "Output:" }, { "code": null, "e": 28104, "s": 28020, "text": "Original Path: program\nAbsolute Path: C:\\Users\\pc\\eclipse-workspace1\\arnab\\program\n" }, { "code": null, "e": 28169, "s": 28104, "text": "Example 3: A file named “f:\\program.txt” in the “f:\\” directory." }, { "code": "// Java program to demonstrate the// use of getAbsolutePath() function import java.io.*; public class solution { public static void main(String args[]) { // try catch block to handle exceptions try { // Create a file object File f = new File(\"f:\\\\program.txt\"); // get the absolute path // of file f String absolute = f.getAbsolutePath(); // display the file path of the file object // and also the file path of absolute file System.out.println(\"Original path: \" + f.getPath()); System.out.println(\"Absolute path: \" + absolute); } catch (Exception e) { System.err.println(e.getMessage()); } }}", "e": 28989, "s": 28169, "text": null }, { "code": null, "e": 28997, "s": 28989, "text": "Output:" }, { "code": null, "e": 29068, "s": 28997, "text": "Original file path: f:\\program.txt\nAbsolute file path: f:\\program.txt\n" }, { "code": null, "e": 29169, "s": 29068, "text": "The programs might not run in an online IDE . please use an offline IDE and set the path of the file" }, { "code": null, "e": 29185, "s": 29169, "text": "Java-File Class" }, { "code": null, "e": 29200, "s": 29185, "text": "Java-Functions" }, { "code": null, "e": 29216, "s": 29200, "text": "Java-IO package" }, { "code": null, "e": 29221, "s": 29216, "text": "Java" }, { "code": null, "e": 29226, "s": 29221, "text": "Java" }, { "code": null, "e": 29324, "s": 29226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29343, "s": 29324, "text": "Interfaces in Java" }, { "code": null, "e": 29367, "s": 29343, "text": "Singleton Class in Java" }, { "code": null, "e": 29379, "s": 29367, "text": "Set in Java" }, { "code": null, "e": 29398, "s": 29379, "text": "LinkedList in Java" }, { "code": null, "e": 29418, "s": 29398, "text": "Collections in Java" }, { "code": null, "e": 29437, "s": 29418, "text": "Overriding in Java" }, { "code": null, "e": 29460, "s": 29437, "text": "Multithreading in Java" }, { "code": null, "e": 29484, "s": 29460, "text": "Queue Interface In Java" }, { "code": null, "e": 29530, "s": 29484, "text": "Different ways of Reading a text file in Java" } ]
DTD - Entities
Entities are used to define shortcuts to special characters within the XML documents. Entities can be primarily of four types − Built-in entities Built-in entities Character entities Character entities General entities General entities Parameter entities Parameter entities In general, entities can be declared internally or externally. Let us understand each of these and their syntax as follows − If an entity is declared within a DTD it is called as internal entity. Syntax Following is the syntax for internal entity declaration − <!ENTITY entity_name "entity_value"> In the above syntax − entity_name is the name of entity followed by its value within the double quotes or single quote. entity_name is the name of entity followed by its value within the double quotes or single quote. entity_value holds the value for the entity name. entity_value holds the value for the entity name. The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name. The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name. Example Following is a simple example for internal entity declaration − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <!DOCTYPE address [ <!ELEMENT address (#PCDATA)> <!ENTITY name "Tanmay patil"> <!ENTITY company "TutorialsPoint"> <!ENTITY phone_no "(011) 123-4567"> ]> <address> &name; &company; &phone_no; </address> In the above example, the respective entity names name, company and phone_no are replaced by their values in the XML document. The entity values are de-referenced by adding prefix & to the entity name. Save this file as sample.xml and open it in any browser, you will notice that the entity values for name, company, phone_no are replaced respectively. If an entity is declared outside a DTD it is called as external entity. You can refer to an external Entity by either using system identifiers or public identifiers. Syntax Following is the syntax for External Entity declaration − <!ENTITY name SYSTEM "URI/URL"> In the above syntax − name is the name of entity. name is the name of entity. SYSTEM is the keyword. SYSTEM is the keyword. URI/URL is the address of the external source enclosed within the double or single quotes. URI/URL is the address of the external source enclosed within the double or single quotes. Types You can refer to an external DTD by either using − System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations. As you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows − System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations. As you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows − <!DOCTYPE name SYSTEM "address.dtd" [...]> Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below − As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs. Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below − As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs. <!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN"> Example Let us understand the external entity with the following example − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <!DOCTYPE address SYSTEM "address.dtd"> <address> <name> Tanmay Patil </name> <company> TutorialsPoint </company> <phone> (011) 123-4567 </phone> </address> Below is the content of the DTD file address.dtd − <!ELEMENT address (name, company, phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> All XML parsers must support built-in entities. In general, you can use these entity references anywhere. You can also use normal text within the XML document, such as in element contents and attribute values. There are five built-in entities that play their role in well-formed XML, they are − ampersand: &amp; ampersand: &amp; Single quote: &apos; Single quote: &apos; Greater than: &gt; Greater than: &gt; Less than: &lt; Less than: &lt; Double quote: " Double quote: " Following example demonstrates the built-in entity declaration − <?xml version = "1.0"?> <note> <description>I'm a technical writer & programmer</description> <note> As you can see here the &amp; character is replaced by & whenever the processor encounters this. Character Entities are used to name some of the entities which are symbolic representation of information i.e characters that are difficult or impossible to type can be substituted by Character Entities. Following example demonstrates the character entity declaration − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <!DOCTYPE author[ <!ELEMENT author (#PCDATA)> <!ENTITY writer "Tanmay patil"> <!ENTITY copyright "&#169;"> ]> <author>&writer;&copyright;</author> You will notice here we have used &#169; as value for copyright character. Save this file as sample.xml and open it in your browser and you will see that copyright is replaced by the character ©. General entities must be declared within the DTD before they can be used within an XML document. Instead of representing only a single character, general entities can represent characters, paragraphs, and even entire documents. To declare a general entity, use a declaration of this general form in your DTD − <!ENTITY ename "text"> Following example demonstrates the general entity declaration − <?xml version = "1.0"?> <!DOCTYPE note [ <!ENTITY source-text "tutorialspoint"> ]> <note> &source-text; </note> Whenever an XML parser encounters a reference to source-text entity, it will supply the replacement text to the application at the point of the reference. The purpose of a parameter entity is to enable you to create reusable sections of replacement text. Following is the syntax for parameter entity declaration − <!ENTITY % ename "entity_value"> entity_value is any character that is not an '&', '%' or ' " '. entity_value is any character that is not an '&', '%' or ' " '. Following example demonstrates the parameter entity declaration. Suppose you have element declarations as below − <!ELEMENT residence (name, street, pincode, city, phone)> <!ELEMENT apartment (name, street, pincode, city, phone)> <!ELEMENT office (name, street, pincode, city, phone)> <!ELEMENT shop (name, street, pincode, city, phone)> Now suppose you want to add additional eleement country, then then you need to add it to all four declarations. Hence we can go for a parameter entity reference. Now using parameter entity reference the above example will be − <!ENTITY % area "name, street, pincode, city"> <!ENTITY % contact "phone"> Parameter entities are dereferenced in the same way as a general entity reference, only with a percent sign instead of an ampersand − <!ELEMENT residence (%area;, %contact;)> <!ELEMENT apartment (%area;, %contact;)> <!ELEMENT office (%area;, %contact;)> <!ELEMENT shop (%area;, %contact;)> When the parser reads these declarations, it substitutes the entity's replacement text for the entity reference. Print Add Notes Bookmark this page
[ { "code": null, "e": 1794, "s": 1666, "text": "Entities are used to define shortcuts to special characters within the XML documents. Entities can be primarily of four types −" }, { "code": null, "e": 1812, "s": 1794, "text": "Built-in entities" }, { "code": null, "e": 1830, "s": 1812, "text": "Built-in entities" }, { "code": null, "e": 1849, "s": 1830, "text": "Character entities" }, { "code": null, "e": 1868, "s": 1849, "text": "Character entities" }, { "code": null, "e": 1885, "s": 1868, "text": "General entities" }, { "code": null, "e": 1902, "s": 1885, "text": "General entities" }, { "code": null, "e": 1921, "s": 1902, "text": "Parameter entities" }, { "code": null, "e": 1940, "s": 1921, "text": "Parameter entities" }, { "code": null, "e": 2065, "s": 1940, "text": "In general, entities can be declared internally or externally. Let us understand each of these and their syntax as follows −" }, { "code": null, "e": 2136, "s": 2065, "text": "If an entity is declared within a DTD it is called as internal entity." }, { "code": null, "e": 2143, "s": 2136, "text": "Syntax" }, { "code": null, "e": 2201, "s": 2143, "text": "Following is the syntax for internal entity declaration −" }, { "code": null, "e": 2238, "s": 2201, "text": "<!ENTITY entity_name \"entity_value\">" }, { "code": null, "e": 2260, "s": 2238, "text": "In the above syntax −" }, { "code": null, "e": 2358, "s": 2260, "text": "entity_name is the name of entity followed by its value within the double quotes or single quote." }, { "code": null, "e": 2456, "s": 2358, "text": "entity_name is the name of entity followed by its value within the double quotes or single quote." }, { "code": null, "e": 2506, "s": 2456, "text": "entity_value holds the value for the entity name." }, { "code": null, "e": 2556, "s": 2506, "text": "entity_value holds the value for the entity name." }, { "code": null, "e": 2672, "s": 2556, "text": "The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name." }, { "code": null, "e": 2788, "s": 2672, "text": "The entity value of the Internal Entity is de-referenced by adding prefix & to the entity name i.e. &entity_name." }, { "code": null, "e": 2796, "s": 2788, "text": "Example" }, { "code": null, "e": 2860, "s": 2796, "text": "Following is a simple example for internal entity declaration −" }, { "code": null, "e": 3147, "s": 2860, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?>\n\n<!DOCTYPE address [\n <!ELEMENT address (#PCDATA)>\n <!ENTITY name \"Tanmay patil\">\n <!ENTITY company \"TutorialsPoint\">\n <!ENTITY phone_no \"(011) 123-4567\">\n]>\n\n<address>\n &name;\n &company;\n &phone_no;\n</address>" }, { "code": null, "e": 3352, "s": 3147, "text": "In the above example, the respective entity names name, company and phone_no are replaced by their values in the XML document. The entity values are de-referenced by adding prefix & to the entity name." }, { "code": null, "e": 3503, "s": 3352, "text": "Save this file as sample.xml and open it in any browser, you will notice that the entity values for name, company, phone_no are replaced respectively." }, { "code": null, "e": 3669, "s": 3503, "text": "If an entity is declared outside a DTD it is called as external entity. You can refer to an external Entity by either using system identifiers or public identifiers." }, { "code": null, "e": 3676, "s": 3669, "text": "Syntax" }, { "code": null, "e": 3734, "s": 3676, "text": "Following is the syntax for External Entity declaration −" }, { "code": null, "e": 3766, "s": 3734, "text": "<!ENTITY name SYSTEM \"URI/URL\">" }, { "code": null, "e": 3788, "s": 3766, "text": "In the above syntax −" }, { "code": null, "e": 3816, "s": 3788, "text": "name is the name of entity." }, { "code": null, "e": 3844, "s": 3816, "text": "name is the name of entity." }, { "code": null, "e": 3867, "s": 3844, "text": "SYSTEM is the keyword." }, { "code": null, "e": 3890, "s": 3867, "text": "SYSTEM is the keyword." }, { "code": null, "e": 3981, "s": 3890, "text": "URI/URL is the address of the external source enclosed within the double or single quotes." }, { "code": null, "e": 4072, "s": 3981, "text": "URI/URL is the address of the external source enclosed within the double or single quotes." }, { "code": null, "e": 4078, "s": 4072, "text": "Types" }, { "code": null, "e": 4129, "s": 4078, "text": "You can refer to an external DTD by either using −" }, { "code": null, "e": 4379, "s": 4129, "text": "System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations.\nAs you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows −\n" }, { "code": null, "e": 4506, "s": 4379, "text": "System Identifiers − A system identifier enables you to specify the location of an external file containing DTD declarations." }, { "code": null, "e": 4628, "s": 4506, "text": "As you can see it contains keyword SYSTEM and a URI reference pointing to the document's location. Syntax is as follows −" }, { "code": null, "e": 4671, "s": 4628, "text": "<!DOCTYPE name SYSTEM \"address.dtd\" [...]>" }, { "code": null, "e": 5052, "s": 4671, "text": "Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below −\nAs you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs.\n" }, { "code": null, "e": 5164, "s": 5052, "text": "Public Identifiers − Public identifiers provide a mechanism to locate DTD resources and are written as below −" }, { "code": null, "e": 5432, "s": 5164, "text": "As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format; however, a commonly used format is called Formal Public Identifiers, or FPIs." }, { "code": null, "e": 5499, "s": 5432, "text": "<!DOCTYPE name PUBLIC \"-//Beginning XML//DTD Address Example//EN\">" }, { "code": null, "e": 5507, "s": 5499, "text": "Example" }, { "code": null, "e": 5574, "s": 5507, "text": "Let us understand the external entity with the following example −" }, { "code": null, "e": 5838, "s": 5574, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?>\n<!DOCTYPE address SYSTEM \"address.dtd\">\n\n<address>\n <name>\n Tanmay Patil\n </name>\n \n <company>\n TutorialsPoint\n </company>\n \n <phone>\n (011) 123-4567\n </phone>\n</address>" }, { "code": null, "e": 5889, "s": 5838, "text": "Below is the content of the DTD file address.dtd −" }, { "code": null, "e": 6013, "s": 5889, "text": "<!ELEMENT address (name, company, phone)>\n<!ELEMENT name (#PCDATA)>\n<!ELEMENT company (#PCDATA)>\n<!ELEMENT phone (#PCDATA)>" }, { "code": null, "e": 6223, "s": 6013, "text": "All XML parsers must support built-in entities. In general, you can use these entity references anywhere. You can also use normal text within the XML document, such as in element contents and attribute values." }, { "code": null, "e": 6308, "s": 6223, "text": "There are five built-in entities that play their role in well-formed XML, they are −" }, { "code": null, "e": 6325, "s": 6308, "text": "ampersand: &amp;" }, { "code": null, "e": 6342, "s": 6325, "text": "ampersand: &amp;" }, { "code": null, "e": 6363, "s": 6342, "text": "Single quote: &apos;" }, { "code": null, "e": 6384, "s": 6363, "text": "Single quote: &apos;" }, { "code": null, "e": 6403, "s": 6384, "text": "Greater than: &gt;" }, { "code": null, "e": 6422, "s": 6403, "text": "Greater than: &gt;" }, { "code": null, "e": 6438, "s": 6422, "text": "Less than: &lt;" }, { "code": null, "e": 6454, "s": 6438, "text": "Less than: &lt;" }, { "code": null, "e": 6470, "s": 6454, "text": "Double quote: \"" }, { "code": null, "e": 6486, "s": 6470, "text": "Double quote: \"" }, { "code": null, "e": 6551, "s": 6486, "text": "Following example demonstrates the built-in entity declaration −" }, { "code": null, "e": 6656, "s": 6551, "text": "<?xml version = \"1.0\"?>\n\n<note>\n <description>I'm a technical writer & programmer</description>\n<note>" }, { "code": null, "e": 6753, "s": 6656, "text": "As you can see here the &amp; character is replaced by & whenever the processor encounters this." }, { "code": null, "e": 6957, "s": 6753, "text": "Character Entities are used to name some of the entities which are symbolic representation of information i.e characters that are difficult or impossible to type can be substituted by Character Entities." }, { "code": null, "e": 7023, "s": 6957, "text": "Following example demonstrates the character entity declaration −" }, { "code": null, "e": 7241, "s": 7023, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?>\n<!DOCTYPE author[\n <!ELEMENT author (#PCDATA)>\n <!ENTITY writer \"Tanmay patil\">\n <!ENTITY copyright \"&#169;\">\n]>\n<author>&writer;&copyright;</author>" }, { "code": null, "e": 7437, "s": 7241, "text": "You will notice here we have used &#169; as value for copyright character. Save this file as sample.xml and open it in your browser and you will see that copyright is replaced by the character ©." }, { "code": null, "e": 7665, "s": 7437, "text": "General entities must be declared within the DTD before they can be used within an XML document. Instead of representing only a single character, general entities can represent characters, paragraphs, and even entire documents." }, { "code": null, "e": 7747, "s": 7665, "text": "To declare a general entity, use a declaration of this general form in your DTD −" }, { "code": null, "e": 7770, "s": 7747, "text": "<!ENTITY ename \"text\">" }, { "code": null, "e": 7834, "s": 7770, "text": "Following example demonstrates the general entity declaration −" }, { "code": null, "e": 7954, "s": 7834, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE note [\n <!ENTITY source-text \"tutorialspoint\">\n]>\n\n<note>\n &source-text;\n</note>" }, { "code": null, "e": 8109, "s": 7954, "text": "Whenever an XML parser encounters a reference to source-text entity, it will supply the replacement text to the application at the point of the reference." }, { "code": null, "e": 8209, "s": 8109, "text": "The purpose of a parameter entity is to enable you to create reusable sections of replacement text." }, { "code": null, "e": 8268, "s": 8209, "text": "Following is the syntax for parameter entity declaration −" }, { "code": null, "e": 8301, "s": 8268, "text": "<!ENTITY % ename \"entity_value\">" }, { "code": null, "e": 8365, "s": 8301, "text": "entity_value is any character that is not an '&', '%' or ' \" '." }, { "code": null, "e": 8429, "s": 8365, "text": "entity_value is any character that is not an '&', '%' or ' \" '." }, { "code": null, "e": 8543, "s": 8429, "text": "Following example demonstrates the parameter entity declaration. Suppose you have element declarations as below −" }, { "code": null, "e": 8767, "s": 8543, "text": "<!ELEMENT residence (name, street, pincode, city, phone)>\n<!ELEMENT apartment (name, street, pincode, city, phone)>\n<!ELEMENT office (name, street, pincode, city, phone)>\n<!ELEMENT shop (name, street, pincode, city, phone)>" }, { "code": null, "e": 8996, "s": 8767, "text": "Now suppose you want to add additional eleement country, then then you need to add it to all four declarations. Hence we can go for a parameter entity reference. Now using parameter entity reference the above example will be −" }, { "code": null, "e": 9071, "s": 8996, "text": "<!ENTITY % area \"name, street, pincode, city\">\n<!ENTITY % contact \"phone\">" }, { "code": null, "e": 9205, "s": 9071, "text": "Parameter entities are dereferenced in the same way as a general entity reference, only with a percent sign instead of an ampersand −" }, { "code": null, "e": 9361, "s": 9205, "text": "<!ELEMENT residence (%area;, %contact;)>\n<!ELEMENT apartment (%area;, %contact;)>\n<!ELEMENT office (%area;, %contact;)>\n<!ELEMENT shop (%area;, %contact;)>" }, { "code": null, "e": 9474, "s": 9361, "text": "When the parser reads these declarations, it substitutes the entity's replacement text for the entity reference." }, { "code": null, "e": 9481, "s": 9474, "text": " Print" }, { "code": null, "e": 9492, "s": 9481, "text": " Add Notes" } ]
Reverse a sublist of a linked list | Practice | GeeksforGeeks
Given a linked list and positions m and n. Reverse the linked list from position m to n. Example 1: Input : N = 10 Linked List = 1->7->5->3->9->8->10 ->2->2->5->NULL m = 1, n = 8 Output : 2 10 8 9 3 5 7 1 2 5 Explanation : The nodes from position 1 to 8 are reversed, resulting in 2 10 8 9 3 5 7 1 2 5. Example 2: Input: N = 6 Linked List = 1->2->3->4->5->6->NULL m = 2, n = 4 Output: 1 4 3 2 5 6 Explanation: Nodes from position 2 to 4 are reversed resulting in 1 4 3 2 5 6. 0 nareshshiva93171 day ago Can someone please tell me what is the problem in this code? Node* reverseBetween(Node* head, int m, int n) { if(head == NULL || m == n || head->next == NULL){ return head; } //m and n is given Node* ptr = head; Node* newll = new Node(-1); Node* newlhead = NULL; int cnt = 1; while(ptr!=NULL){ if(cnt == m){ while(cnt<=n){ if(newlhead == NULL){ newlhead = ptr; } newll->next = ptr; newll = newll->next; ptr = ptr->next; cnt++; } break; } cnt++; ptr = ptr->next; } newll->next = NULL; Node* curr = newlhead; Node* prev = NULL; Node* nxt = NULL; while(curr!=NULL){ nxt = curr->next; curr->next = prev; prev = curr; curr = nxt; } curr = prev; //reversed int start = 1; Node* n1 = new Node(-1); Node* n1h = NULL; Node* n2 = new Node(-1); Node* n2h = NULL; int c1 = 0; int c2 = 0; while(head!=NULL){ if(start<m){ if(n1h == NULL){ n1h = head; } c1 = c1 + 1; n1->next = head; n1 = n1->next; } else if(start>n){ if(n2h == NULL){ n2h = head; } c2 = c2 + 1; n2->next = head; n2 = n2->next; } start = start + 1; head = head->next; } if(c1 == 0 && c2 > 0){ newlhead->next = n2h; n2->next = NULL; return curr; } if(c1 >0 && c2 > 0){ n1->next = curr; newlhead->next = n2h; n2->next = NULL; return n1h; } if(c1 > 0 && c2 == 0){ n1->next = curr; newlhead->next = NULL; return n1h; } if(c1 == 0 && c2 == 0){ newlhead->next = NULL; return curr; } //code here } 0 hokage4u2 days ago // If it helps public static Node reverseBetween(Node head, int m, int n) { //code here int count = 1; Node leftTail = null; Node rightHead = null; Node current = head; while(count < n) { if(count == m-1) leftTail = current; current = current.next; count++; } rightHead = current.next; current.next = null; Node revHead = leftTail == null ? reverse(head):reverse(leftTail.next); Node temp = revHead; while(temp.next != null) temp = temp.next; temp.next = rightHead; Node newHead = leftTail == null ? revHead : head; if(leftTail != null) leftTail.next = revHead; return newHead; } private static Node reverse(Node head) { if(head == null || head.next == null) return head; Node newHead = reverse(head.next); Node tail = head.next; tail.next = head; head.next = null; return newHead; } 0 shakshamkaushik12 days ago Time -→1.77 public static Node reverseBetween(Node head, int m, int n) { Node rev = new Node(0); Node rev1 = rev; Node temp = head; int count = 1; while (temp!=null){ if(count>=m && count<=n){ rev.next = new Node(temp.data); rev = rev.next; } count++; temp = temp.next; } Node curr = rev1.next; Node prev = null; while(curr!=null){ Node t = curr.next; curr.next = prev; prev = curr; curr = t; } Node tn = head; int count1 = 1; while(prev!=null && tn!=null){ if(count1>=m && count1<=n){ tn.data = prev.data; prev = prev.next; } tn = tn.next; count1++; } return head; } 0 vishalsavade1 week ago //This code is contributed by Vishal Savade //Easy to understand C++ in 0.2/1.31 //Any update or optimization write it into comment Node *reverse(Node *root){ Node *curr = root, *prev = NULL, *succ; while(curr!=NULL){ succ = curr->next; curr->next = prev; prev = curr; curr = succ; } return prev; } Node* reverseBetween(Node* head, int m, int n) { //code here if(m == n) return head; int cnt = 0; Node *h1 = head, *p1 = head; //Finding first index while(cnt+1 != m){ p1 = h1; h1 = h1->next; cnt++; } Node *h2 = h1; cnt = 0; //Finding second index while(cnt != abs(n-m)){ h2 = h2->next; cnt++; } //Store right part of the list Node *right_part = h2->next; h2->next = NULL; //Reverse the sublist Node *reversed = reverse(h1); if(m == 1) head = reversed; else{ p1->next = reversed; } //Attach the right part to end of the list back Node *t = reversed; while(t->next!=NULL) t = t->next; t->next = right_part; return head; } +2 shubhamkhavare2 weeks ago Very Easy Java Code: Node rev = new Node(0); Node rev1 = rev; Node temp = head; int count = 1; while(temp != null) { if(count >= m && count <= n) { rev.next = new Node(temp.data); rev = rev.next; } count++; temp = temp.next; } Node curr = rev1.next; Node prev = null; while(curr != null) { Node temp1 = curr.next; curr.next = prev; prev = curr; curr = temp1; } Node tempNode = head; int count1 = 1; while(prev != null && tempNode != null) { if(count1 >= m && count1 <= n) { tempNode.data = prev.data; prev = prev.next; } tempNode = tempNode.next; count1++; } return head; +1 lakshta192 months ago Node* reverseBetween(Node* head, int m, int n) { Node*p=head,*q=head, *b,*f; if(m==1){ while(n-1){ q=q->next; f=q; n--; } f=q->next; q->next=NULL; Node *r=NULL, *t=NULL, *s=p; while(p){ r=t; t=p; p=p->next; t->next=r; } s->next=f; head=q; return head; } else { while(m-1){ b=p; p=p->next; m--; } while(n-1){ q=q->next; f=q; n--; } f=q->next; b->next=NULL; q->next=NULL; Node *r=NULL, *t=NULL, *s=p; while(p){ r=t; t=p; p=p->next; t->next=r; } b->next=t; s->next=f; return head; }} 0 hanumanmanyam8372 months ago public static Node reverseBetween(Node head, int m, int n) { if(head == null || m == n) return head; int count=0; Node curr=head; Node prevFirst=null; while(curr!=null) { count++; if(count==m) { Node first=curr; Node prev=null; while(first!=null && count<=n) { Node temp=first.next; first.next=prev; prev=first; first=temp; count++; } if(m==1) { head=prev; } else { prevFirst.next=prev; } curr.next=first; break; } prevFirst=curr; curr=curr.next; } return head; } +1 ciph3rcodes2 months ago #JAVA EASY SOLUTION class Solution{ public static Node reverseBetween(Node head, int m, int n) { Node temp=head; Node t=head; int c=0; ArrayList<Integer> arrli=new ArrayList<>(); while(t!=null){ arrli.add(t.data); t=t.next; c++; } ArrayList<Integer> arrli1= new ArrayList<>(); for(int i=m-1;i<n;i++){ arrli1.add(arrli.get(i)); } int k=0; Collections.reverse(arrli1); for(int i=0;i<c;i++){ if(i+1>=m && i+1<=n){ int a=arrli1.get(k); k++; temp.data=a; temp=temp.next; } else{ int b=arrli.get(i); temp.data=b; temp=temp.next; } } return head; }} 0 mridulbhaskarabc2 months ago class Solution: def reverseBetween(self, head, m, n): #code here node_ = head node_temp = head count = n-m+1 list_ = [0]*count for i in range(m-1): node_ = node_.next node_temp = node_temp.next for i in range(count): list_[count-i-1] = node_.data node_ = node_.next for i in range(count): node_temp.data = list_[i] node_temp = node_temp.next return head #Contributed By: Mridul Bhaskar 0 chessnoobdj2 months ago C++ Node* reverseBetween(Node* head, int m, int n) { Node *ptr = head, *prev = head, *tmp1 = NULL, *tmp2 = head; while(ptr){ if(m == 1){ while(ptr && n>0){ Node *tmp = ptr->next; ptr->next = prev; prev = ptr; ptr = tmp; n -= 1; } if(tmp1 == NULL){ tmp1 = prev; head = prev; } else tmp1->next = prev; tmp2->next = ptr; break; } m -= 1; n -= 1; tmp1 = ptr; tmp2 = ptr->next; ptr = ptr->next; } return head; } 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": 327, "s": 238, "text": "Given a linked list and positions m and n. Reverse the linked list from position m to n." }, { "code": null, "e": 338, "s": 327, "text": "Example 1:" }, { "code": null, "e": 568, "s": 338, "text": "Input :\nN = 10\nLinked List = 1->7->5->3->9->8->10\n ->2->2->5->NULL\nm = 1, n = 8\nOutput : 2 10 8 9 3 5 7 1 2 5 \nExplanation :\nThe nodes from position 1 to 8 \nare reversed, resulting in \n2 10 8 9 3 5 7 1 2 5.\n\n" }, { "code": null, "e": 579, "s": 568, "text": "Example 2:" }, { "code": null, "e": 742, "s": 579, "text": "Input:\nN = 6\nLinked List = 1->2->3->4->5->6->NULL\nm = 2, n = 4\nOutput: 1 4 3 2 5 6\nExplanation:\nNodes from position 2 to 4 \nare reversed resulting in\n1 4 3 2 5 6." }, { "code": null, "e": 744, "s": 742, "text": "0" }, { "code": null, "e": 769, "s": 744, "text": "nareshshiva93171 day ago" }, { "code": null, "e": 830, "s": 769, "text": "Can someone please tell me what is the problem in this code?" }, { "code": null, "e": 2945, "s": 830, "text": "Node* reverseBetween(Node* head, int m, int n) { if(head == NULL || m == n || head->next == NULL){ return head; } //m and n is given Node* ptr = head; Node* newll = new Node(-1); Node* newlhead = NULL; int cnt = 1; while(ptr!=NULL){ if(cnt == m){ while(cnt<=n){ if(newlhead == NULL){ newlhead = ptr; } newll->next = ptr; newll = newll->next; ptr = ptr->next; cnt++; } break; } cnt++; ptr = ptr->next; } newll->next = NULL; Node* curr = newlhead; Node* prev = NULL; Node* nxt = NULL; while(curr!=NULL){ nxt = curr->next; curr->next = prev; prev = curr; curr = nxt; } curr = prev; //reversed int start = 1; Node* n1 = new Node(-1); Node* n1h = NULL; Node* n2 = new Node(-1); Node* n2h = NULL; int c1 = 0; int c2 = 0; while(head!=NULL){ if(start<m){ if(n1h == NULL){ n1h = head; } c1 = c1 + 1; n1->next = head; n1 = n1->next; } else if(start>n){ if(n2h == NULL){ n2h = head; } c2 = c2 + 1; n2->next = head; n2 = n2->next; } start = start + 1; head = head->next; } if(c1 == 0 && c2 > 0){ newlhead->next = n2h; n2->next = NULL; return curr; } if(c1 >0 && c2 > 0){ n1->next = curr; newlhead->next = n2h; n2->next = NULL; return n1h; } if(c1 > 0 && c2 == 0){ n1->next = curr; newlhead->next = NULL; return n1h; } if(c1 == 0 && c2 == 0){ newlhead->next = NULL; return curr; } //code here }" }, { "code": null, "e": 2949, "s": 2947, "text": "0" }, { "code": null, "e": 2968, "s": 2949, "text": "hokage4u2 days ago" }, { "code": null, "e": 4177, "s": 2968, "text": "// If it helps\n\npublic static Node reverseBetween(Node head, int m, int n)\n {\n //code here\n int count = 1;\n \n Node leftTail = null;\n Node rightHead = null;\n \n Node current = head;\n \n while(count < n)\n {\n if(count == m-1)\n leftTail = current;\n \n current = current.next;\n count++;\n }\n \n rightHead = current.next;\n current.next = null;\n \n Node revHead = leftTail == null ? reverse(head):reverse(leftTail.next);\n \n \n Node temp = revHead;\n while(temp.next != null)\n temp = temp.next;\n \n temp.next = rightHead;\n \n Node newHead = leftTail == null ? revHead : head;\n \n if(leftTail != null)\n leftTail.next = revHead;\n \n return newHead;\n \n }\n private static Node reverse(Node head)\n {\n if(head == null || head.next == null)\n return head;\n \n Node newHead = reverse(head.next);\n \n Node tail = head.next;\n tail.next = head;\n head.next = null;\n \n return newHead;\n }" }, { "code": null, "e": 4179, "s": 4177, "text": "0" }, { "code": null, "e": 4206, "s": 4179, "text": "shakshamkaushik12 days ago" }, { "code": null, "e": 4220, "s": 4208, "text": "Time -→1.77" }, { "code": null, "e": 5083, "s": 4220, "text": " public static Node reverseBetween(Node head, int m, int n) { Node rev = new Node(0); Node rev1 = rev; Node temp = head; int count = 1; while (temp!=null){ if(count>=m && count<=n){ rev.next = new Node(temp.data); rev = rev.next; } count++; temp = temp.next; } Node curr = rev1.next; Node prev = null; while(curr!=null){ Node t = curr.next; curr.next = prev; prev = curr; curr = t; } Node tn = head; int count1 = 1; while(prev!=null && tn!=null){ if(count1>=m && count1<=n){ tn.data = prev.data; prev = prev.next; } tn = tn.next; count1++; } return head; } " }, { "code": null, "e": 5085, "s": 5083, "text": "0" }, { "code": null, "e": 5108, "s": 5085, "text": "vishalsavade1 week ago" }, { "code": null, "e": 6456, "s": 5108, "text": "//This code is contributed by Vishal Savade\n//Easy to understand C++ in 0.2/1.31\n//Any update or optimization write it into comment\nNode *reverse(Node *root){\n Node *curr = root, *prev = NULL, *succ;\n while(curr!=NULL){\n succ = curr->next;\n curr->next = prev;\n \n prev = curr;\n curr = succ;\n }\n return prev;\n }\n Node* reverseBetween(Node* head, int m, int n)\n {\n //code here\n if(m == n) return head;\n int cnt = 0;\n Node *h1 = head, *p1 = head;\n \n //Finding first index \n while(cnt+1 != m){\n p1 = h1;\n h1 = h1->next;\n cnt++;\n }\n \n Node *h2 = h1;\n cnt = 0;\n //Finding second index \n while(cnt != abs(n-m)){\n h2 = h2->next;\n cnt++;\n }\n //Store right part of the list\n Node *right_part = h2->next;\n h2->next = NULL;\n \n //Reverse the sublist\n Node *reversed = reverse(h1);\n \n if(m == 1) head = reversed;\n else{\n p1->next = reversed;\n }\n //Attach the right part to end of the list back\n Node *t = reversed;\n while(t->next!=NULL) t = t->next;\n t->next = right_part;\n \n return head;\n }" }, { "code": null, "e": 6459, "s": 6456, "text": "+2" }, { "code": null, "e": 6485, "s": 6459, "text": "shubhamkhavare2 weeks ago" }, { "code": null, "e": 6506, "s": 6485, "text": "Very Easy Java Code:" }, { "code": null, "e": 7361, "s": 6506, "text": " Node rev = new Node(0); Node rev1 = rev; Node temp = head; int count = 1; while(temp != null) { if(count >= m && count <= n) { rev.next = new Node(temp.data); rev = rev.next; } count++; temp = temp.next; } Node curr = rev1.next; Node prev = null; while(curr != null) { Node temp1 = curr.next; curr.next = prev; prev = curr; curr = temp1; } Node tempNode = head; int count1 = 1; while(prev != null && tempNode != null) { if(count1 >= m && count1 <= n) { tempNode.data = prev.data; prev = prev.next; } tempNode = tempNode.next; count1++; } return head;" }, { "code": null, "e": 7364, "s": 7361, "text": "+1" }, { "code": null, "e": 7386, "s": 7364, "text": "lakshta192 months ago" }, { "code": null, "e": 8200, "s": 7386, "text": " Node* reverseBetween(Node* head, int m, int n) { Node*p=head,*q=head, *b,*f; if(m==1){ while(n-1){ q=q->next; f=q; n--; } f=q->next; q->next=NULL; Node *r=NULL, *t=NULL, *s=p; while(p){ r=t; t=p; p=p->next; t->next=r; } s->next=f; head=q; return head; } else { while(m-1){ b=p; p=p->next; m--; } while(n-1){ q=q->next; f=q; n--; } f=q->next; b->next=NULL; q->next=NULL; Node *r=NULL, *t=NULL, *s=p; while(p){ r=t; t=p; p=p->next; t->next=r; } b->next=t; s->next=f; return head; }}" }, { "code": null, "e": 8202, "s": 8200, "text": "0" }, { "code": null, "e": 8231, "s": 8202, "text": "hanumanmanyam8372 months ago" }, { "code": null, "e": 9196, "s": 8231, "text": "public static Node reverseBetween(Node head, int m, int n)\n {\n if(head == null || m == n) return head;\n int count=0;\n Node curr=head;\n Node prevFirst=null;\n while(curr!=null)\n {\n count++;\n if(count==m)\n {\n Node first=curr;\n Node prev=null;\n while(first!=null && count<=n)\n {\n Node temp=first.next;\n first.next=prev;\n prev=first;\n first=temp;\n count++;\n }\n if(m==1)\n {\n head=prev;\n }\n else\n {\n prevFirst.next=prev;\n }\n curr.next=first;\n break;\n }\n prevFirst=curr;\n curr=curr.next;\n }\n return head;\n \n }" }, { "code": null, "e": 9199, "s": 9196, "text": "+1" }, { "code": null, "e": 9223, "s": 9199, "text": "ciph3rcodes2 months ago" }, { "code": null, "e": 9244, "s": 9223, "text": "#JAVA EASY SOLUTION " }, { "code": null, "e": 10013, "s": 9246, "text": "class Solution{ public static Node reverseBetween(Node head, int m, int n) { Node temp=head; Node t=head; int c=0; ArrayList<Integer> arrli=new ArrayList<>(); while(t!=null){ arrli.add(t.data); t=t.next; c++; } ArrayList<Integer> arrli1= new ArrayList<>(); for(int i=m-1;i<n;i++){ arrli1.add(arrli.get(i)); } int k=0; Collections.reverse(arrli1); for(int i=0;i<c;i++){ if(i+1>=m && i+1<=n){ int a=arrli1.get(k); k++; temp.data=a; temp=temp.next; } else{ int b=arrli.get(i); temp.data=b; temp=temp.next; } } return head; }}" }, { "code": null, "e": 10015, "s": 10013, "text": "0" }, { "code": null, "e": 10044, "s": 10015, "text": "mridulbhaskarabc2 months ago" }, { "code": null, "e": 10580, "s": 10046, "text": "class Solution:\n def reverseBetween(self, head, m, n):\n #code here\n node_ = head\n node_temp = head\n count = n-m+1\n list_ = [0]*count\n for i in range(m-1):\n node_ = node_.next\n node_temp = node_temp.next\n for i in range(count):\n list_[count-i-1] = node_.data\n node_ = node_.next\n for i in range(count):\n node_temp.data = list_[i]\n node_temp = node_temp.next\n return head\n#Contributed By: Mridul Bhaskar" }, { "code": null, "e": 10586, "s": 10584, "text": "0" }, { "code": null, "e": 10610, "s": 10586, "text": "chessnoobdj2 months ago" }, { "code": null, "e": 10614, "s": 10610, "text": "C++" }, { "code": null, "e": 11413, "s": 10614, "text": "Node* reverseBetween(Node* head, int m, int n)\n {\n Node *ptr = head, *prev = head, *tmp1 = NULL, *tmp2 = head;\n while(ptr){\n if(m == 1){\n while(ptr && n>0){\n Node *tmp = ptr->next;\n ptr->next = prev;\n prev = ptr;\n ptr = tmp;\n n -= 1;\n }\n if(tmp1 == NULL){\n tmp1 = prev;\n head = prev;\n }\n else\n tmp1->next = prev;\n tmp2->next = ptr;\n break;\n }\n m -= 1;\n n -= 1;\n tmp1 = ptr;\n tmp2 = ptr->next;\n ptr = ptr->next;\n }\n return head;\n }" }, { "code": null, "e": 11559, "s": 11413, "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": 11595, "s": 11559, "text": " Login to access your submissions. " }, { "code": null, "e": 11605, "s": 11595, "text": "\nProblem\n" }, { "code": null, "e": 11615, "s": 11605, "text": "\nContest\n" }, { "code": null, "e": 11678, "s": 11615, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11826, "s": 11678, "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": 12034, "s": 11826, "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": 12140, "s": 12034, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
WSDL - <definition> Element
The <definitions> element must be the root element of all WSDL documents. It defines the name of the web service. Here is the piece of code from the last chapter that uses the definitions element. <definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> ................................................ </definitions> From the above example, we can conclude that definitions − is a container of all the other elements. is a container of all the other elements. specifies that this document is called HelloService. specifies that this document is called HelloService. specifies a targetNamespace attribute. The targetNamespace is a convention of XML Schema that enables the WSDL document to refer to itself. In this example, we have specified a targetNamespace of http://www.examples.com/wsdl/HelloService.wsdl specifies a targetNamespace attribute. The targetNamespace is a convention of XML Schema that enables the WSDL document to refer to itself. In this example, we have specified a targetNamespace of http://www.examples.com/wsdl/HelloService.wsdl specifies a default namespace: xmlns=http://schemas.xmlsoap.org/wsdl/. All elements without a namespace prefix, such as message or portType, are therefore assumed to be a part of the default WSDL namespace. specifies a default namespace: xmlns=http://schemas.xmlsoap.org/wsdl/. All elements without a namespace prefix, such as message or portType, are therefore assumed to be a part of the default WSDL namespace. specifies numerous namespaces that are used throughout the remainder of the document. specifies numerous namespaces that are used throughout the remainder of the document. NOTE − The namespace specification does not require the document to be present at the given location. The important point is that you specify a value that is unique, different from all other namespaces that are defined. Print Add Notes Bookmark this page
[ { "code": null, "e": 1918, "s": 1804, "text": "The <definitions> element must be the root element of all WSDL documents. It defines the name of the web service." }, { "code": null, "e": 2001, "s": 1918, "text": "Here is the piece of code from the last chapter that uses the definitions element." }, { "code": null, "e": 2378, "s": 2001, "text": "<definitions name=\"HelloService\"\n targetNamespace=\"http://www.examples.com/wsdl/HelloService.wsdl\"\n xmlns=\"http://schemas.xmlsoap.org/wsdl/\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns=\"http://www.examples.com/wsdl/HelloService.wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n ................................................\n</definitions>" }, { "code": null, "e": 2437, "s": 2378, "text": "From the above example, we can conclude that definitions −" }, { "code": null, "e": 2479, "s": 2437, "text": "is a container of all the other elements." }, { "code": null, "e": 2521, "s": 2479, "text": "is a container of all the other elements." }, { "code": null, "e": 2574, "s": 2521, "text": "specifies that this document is called HelloService." }, { "code": null, "e": 2627, "s": 2574, "text": "specifies that this document is called HelloService." }, { "code": null, "e": 2870, "s": 2627, "text": "specifies a targetNamespace attribute. The targetNamespace is a convention of XML Schema that enables the WSDL document to refer to itself. In this example, we have specified a targetNamespace of http://www.examples.com/wsdl/HelloService.wsdl" }, { "code": null, "e": 3113, "s": 2870, "text": "specifies a targetNamespace attribute. The targetNamespace is a convention of XML Schema that enables the WSDL document to refer to itself. In this example, we have specified a targetNamespace of http://www.examples.com/wsdl/HelloService.wsdl" }, { "code": null, "e": 3320, "s": 3113, "text": "specifies a default namespace: xmlns=http://schemas.xmlsoap.org/wsdl/. All elements without a namespace prefix, such as message or portType, are therefore assumed to be a part of the default WSDL namespace." }, { "code": null, "e": 3527, "s": 3320, "text": "specifies a default namespace: xmlns=http://schemas.xmlsoap.org/wsdl/. All elements without a namespace prefix, such as message or portType, are therefore assumed to be a part of the default WSDL namespace." }, { "code": null, "e": 3613, "s": 3527, "text": "specifies numerous namespaces that are used throughout the remainder of the document." }, { "code": null, "e": 3699, "s": 3613, "text": "specifies numerous namespaces that are used throughout the remainder of the document." }, { "code": null, "e": 3919, "s": 3699, "text": "NOTE − The namespace specification does not require the document to be present at the given location. The important point is that you specify a value that is unique, different from all other namespaces that are defined." }, { "code": null, "e": 3926, "s": 3919, "text": " Print" }, { "code": null, "e": 3937, "s": 3926, "text": " Add Notes" } ]
Assignment Operators in Python - GeeksforGeeks
29 Aug, 2020 Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, bitwise computations. The value the operator operates on is known as Operand. Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables. Description = += -= *= /= %= //= **= &= |= ^= >>= <<= Now Let’s see each Assignment Operator one by one. 1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand. Syntax: x = y + z Example: Python3 # Assigning values using # Assignment Operator a = 3b = 5 c = a + b # Outputprint(c) Output: 8 2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand. Syntax: x += y Example: Python3 a = 3b = 5 # a = a + ba += b # Outputprint(a) Output: 8 3) Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to the left operand. Syntax: x -= y Example – Python3 a = 3b = 5 # a = a - ba -= b # Outputprint(a) Output: -2 4) Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to the left operand. Syntax: x *= y Example: Python3 a = 3b = 5 # a = a * ba *= b # Outputprint(a) Output: 15 5) Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the left operand. Syntax: x /= y Example: Python3 a = 3b = 5 # a = a / ba /= b # Outputprint(a) Output: 0.6 6) Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the result to the left operand. Syntax: x %= y Example: Python3 a = 3b = 5 # a = a % ba %= b # Outputprint(a) Output: 3 7) Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the result(floor) to the left operand. Syntax: x //= y Example: Python a = 3b = 5 # a = a // ba //= b # Outputprint(a) Output: 0 8) Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand. Syntax: x **= y Example: Python a = 3b = 5 # a = a ** ba **= b # Outputprint(a) Output: 243 9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the left operand. Syntax: x &= y Example: Python3 a = 3b = 5 # a = a & ba &= b # Outputprint(a) Output: 1 10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands and then assigning result to the left operand. Syntax: x |= y Example: Python3 a = 3b = 5 # a = a | ba |= b # Outputprint(a) Output: 7 11) Bitwise XOR and Assign: This operator is used to perform Bitwise XOR on the operands and then assigning result to the left operand. Syntax: x ^= y Example: Python3 a = 3b = 5 # a = a ^ ba ^= b # Outputprint(a) Output: 6 12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on the operands and then assigning result to the left operand. Syntax: x >>= y Example: Python3 a = 3b = 5 # a = a >> ba >>= b # Outputprint(a) Output: 0 13) Bitwise Left Shift and Assign: This operator is used to perform Bitwise left shift on the operands and then assigning result to the left operand. Syntax: x <<= y Example: Python3 a = 3b = 5 # a = a << ba <<= b # Outputprint(a) Output: 96 Python-Operators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24063, "s": 24035, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24273, "s": 24063, "text": "Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, bitwise computations. The value the operator operates on is known as Operand." }, { "code": null, "e": 24394, "s": 24273, "text": "Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables. " }, { "code": null, "e": 24406, "s": 24394, "text": "Description" }, { "code": null, "e": 24408, "s": 24406, "text": "=" }, { "code": null, "e": 24411, "s": 24408, "text": "+=" }, { "code": null, "e": 24414, "s": 24411, "text": "-=" }, { "code": null, "e": 24417, "s": 24414, "text": "*=" }, { "code": null, "e": 24420, "s": 24417, "text": "/=" }, { "code": null, "e": 24423, "s": 24420, "text": "%=" }, { "code": null, "e": 24427, "s": 24423, "text": "//=" }, { "code": null, "e": 24431, "s": 24427, "text": "**=" }, { "code": null, "e": 24434, "s": 24431, "text": "&=" }, { "code": null, "e": 24437, "s": 24434, "text": "|=" }, { "code": null, "e": 24440, "s": 24437, "text": "^=" }, { "code": null, "e": 24444, "s": 24440, "text": ">>=" }, { "code": null, "e": 24448, "s": 24444, "text": "<<=" }, { "code": null, "e": 24499, "s": 24448, "text": "Now Let’s see each Assignment Operator one by one." }, { "code": null, "e": 24614, "s": 24499, "text": "1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand." }, { "code": null, "e": 24622, "s": 24614, "text": "Syntax:" }, { "code": null, "e": 24633, "s": 24622, "text": "x = y + z\n" }, { "code": null, "e": 24642, "s": 24633, "text": "Example:" }, { "code": null, "e": 24650, "s": 24642, "text": "Python3" }, { "code": "# Assigning values using # Assignment Operator a = 3b = 5 c = a + b # Outputprint(c)", "e": 24738, "s": 24650, "text": null }, { "code": null, "e": 24746, "s": 24738, "text": "Output:" }, { "code": null, "e": 24749, "s": 24746, "text": "8\n" }, { "code": null, "e": 24898, "s": 24749, "text": "2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand." }, { "code": null, "e": 24907, "s": 24898, "text": "Syntax: " }, { "code": null, "e": 24915, "s": 24907, "text": "x += y\n" }, { "code": null, "e": 24924, "s": 24915, "text": "Example:" }, { "code": null, "e": 24932, "s": 24924, "text": "Python3" }, { "code": "a = 3b = 5 # a = a + ba += b # Outputprint(a)", "e": 24980, "s": 24932, "text": null }, { "code": null, "e": 24988, "s": 24980, "text": "Output:" }, { "code": null, "e": 24991, "s": 24988, "text": "8\n" }, { "code": null, "e": 25140, "s": 24991, "text": "3) Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to the left operand." }, { "code": null, "e": 25148, "s": 25140, "text": "Syntax:" }, { "code": null, "e": 25155, "s": 25148, "text": "x -= y" }, { "code": null, "e": 25165, "s": 25155, "text": "Example –" }, { "code": null, "e": 25173, "s": 25165, "text": "Python3" }, { "code": "a = 3b = 5 # a = a - ba -= b # Outputprint(a)", "e": 25221, "s": 25173, "text": null }, { "code": null, "e": 25229, "s": 25221, "text": "Output:" }, { "code": null, "e": 25233, "s": 25229, "text": "-2\n" }, { "code": null, "e": 25383, "s": 25233, "text": " 4) Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to the left operand." }, { "code": null, "e": 25391, "s": 25383, "text": "Syntax:" }, { "code": null, "e": 25399, "s": 25391, "text": "x *= y\n" }, { "code": null, "e": 25408, "s": 25399, "text": "Example:" }, { "code": null, "e": 25416, "s": 25408, "text": "Python3" }, { "code": "a = 3b = 5 # a = a * ba *= b # Outputprint(a)", "e": 25464, "s": 25416, "text": null }, { "code": null, "e": 25472, "s": 25464, "text": "Output:" }, { "code": null, "e": 25476, "s": 25472, "text": "15\n" }, { "code": null, "e": 25622, "s": 25476, "text": " 5) Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the left operand." }, { "code": null, "e": 25631, "s": 25622, "text": "Syntax: " }, { "code": null, "e": 25639, "s": 25631, "text": "x /= y\n" }, { "code": null, "e": 25648, "s": 25639, "text": "Example:" }, { "code": null, "e": 25656, "s": 25648, "text": "Python3" }, { "code": "a = 3b = 5 # a = a / ba /= b # Outputprint(a)", "e": 25704, "s": 25656, "text": null }, { "code": null, "e": 25712, "s": 25704, "text": "Output:" }, { "code": null, "e": 25717, "s": 25712, "text": "0.6\n" }, { "code": null, "e": 25872, "s": 25717, "text": " 6) Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the result to the left operand." }, { "code": null, "e": 25880, "s": 25872, "text": "Syntax:" }, { "code": null, "e": 25888, "s": 25880, "text": "x %= y\n" }, { "code": null, "e": 25897, "s": 25888, "text": "Example:" }, { "code": null, "e": 25905, "s": 25897, "text": "Python3" }, { "code": "a = 3b = 5 # a = a % ba %= b # Outputprint(a)", "e": 25953, "s": 25905, "text": null }, { "code": null, "e": 25961, "s": 25953, "text": "Output:" }, { "code": null, "e": 25964, "s": 25961, "text": "3\n" }, { "code": null, "e": 26124, "s": 25964, "text": "7) Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the result(floor) to the left operand." }, { "code": null, "e": 26132, "s": 26124, "text": "Syntax:" }, { "code": null, "e": 26141, "s": 26132, "text": "x //= y\n" }, { "code": null, "e": 26150, "s": 26141, "text": "Example:" }, { "code": null, "e": 26157, "s": 26150, "text": "Python" }, { "code": "a = 3b = 5 # a = a // ba //= b # Outputprint(a)", "e": 26207, "s": 26157, "text": null }, { "code": null, "e": 26215, "s": 26207, "text": "Output:" }, { "code": null, "e": 26218, "s": 26215, "text": "0\n" }, { "code": null, "e": 26376, "s": 26218, "text": " 8) Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand." }, { "code": null, "e": 26384, "s": 26376, "text": "Syntax:" }, { "code": null, "e": 26393, "s": 26384, "text": "x **= y\n" }, { "code": null, "e": 26402, "s": 26393, "text": "Example:" }, { "code": null, "e": 26409, "s": 26402, "text": "Python" }, { "code": "a = 3b = 5 # a = a ** ba **= b # Outputprint(a)", "e": 26459, "s": 26409, "text": null }, { "code": null, "e": 26467, "s": 26459, "text": "Output:" }, { "code": null, "e": 26472, "s": 26467, "text": "243\n" }, { "code": null, "e": 26612, "s": 26472, "text": "9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the left operand." }, { "code": null, "e": 26620, "s": 26612, "text": "Syntax:" }, { "code": null, "e": 26628, "s": 26620, "text": "x &= y\n" }, { "code": null, "e": 26637, "s": 26628, "text": "Example:" }, { "code": null, "e": 26645, "s": 26637, "text": "Python3" }, { "code": "a = 3b = 5 # a = a & ba &= b # Outputprint(a)", "e": 26693, "s": 26645, "text": null }, { "code": null, "e": 26701, "s": 26693, "text": "Output:" }, { "code": null, "e": 26704, "s": 26701, "text": "1\n" }, { "code": null, "e": 26838, "s": 26704, "text": "10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands and then assigning result to the left operand." }, { "code": null, "e": 26846, "s": 26838, "text": "Syntax:" }, { "code": null, "e": 26854, "s": 26846, "text": "x |= y\n" }, { "code": null, "e": 26863, "s": 26854, "text": "Example:" }, { "code": null, "e": 26871, "s": 26863, "text": "Python3" }, { "code": "a = 3b = 5 # a = a | ba |= b # Outputprint(a)", "e": 26919, "s": 26871, "text": null }, { "code": null, "e": 26927, "s": 26919, "text": "Output:" }, { "code": null, "e": 26930, "s": 26927, "text": "7\n" }, { "code": null, "e": 27066, "s": 26930, "text": "11) Bitwise XOR and Assign: This operator is used to perform Bitwise XOR on the operands and then assigning result to the left operand." }, { "code": null, "e": 27074, "s": 27066, "text": "Syntax:" }, { "code": null, "e": 27082, "s": 27074, "text": "x ^= y\n" }, { "code": null, "e": 27091, "s": 27082, "text": "Example:" }, { "code": null, "e": 27099, "s": 27091, "text": "Python3" }, { "code": "a = 3b = 5 # a = a ^ ba ^= b # Outputprint(a)", "e": 27147, "s": 27099, "text": null }, { "code": null, "e": 27155, "s": 27147, "text": "Output:" }, { "code": null, "e": 27158, "s": 27155, "text": "6\n" }, { "code": null, "e": 27310, "s": 27158, "text": "12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on the operands and then assigning result to the left operand." }, { "code": null, "e": 27318, "s": 27310, "text": "Syntax:" }, { "code": null, "e": 27327, "s": 27318, "text": "x >>= y\n" }, { "code": null, "e": 27336, "s": 27327, "text": "Example:" }, { "code": null, "e": 27344, "s": 27336, "text": "Python3" }, { "code": "a = 3b = 5 # a = a >> ba >>= b # Outputprint(a)", "e": 27394, "s": 27344, "text": null }, { "code": null, "e": 27402, "s": 27394, "text": "Output:" }, { "code": null, "e": 27405, "s": 27402, "text": "0\n" }, { "code": null, "e": 27556, "s": 27405, "text": " 13) Bitwise Left Shift and Assign: This operator is used to perform Bitwise left shift on the operands and then assigning result to the left operand." }, { "code": null, "e": 27564, "s": 27556, "text": "Syntax:" }, { "code": null, "e": 27573, "s": 27564, "text": "x <<= y\n" }, { "code": null, "e": 27582, "s": 27573, "text": "Example:" }, { "code": null, "e": 27590, "s": 27582, "text": "Python3" }, { "code": "a = 3b = 5 # a = a << ba <<= b # Outputprint(a)", "e": 27640, "s": 27590, "text": null }, { "code": null, "e": 27648, "s": 27640, "text": "Output:" }, { "code": null, "e": 27652, "s": 27648, "text": "96\n" }, { "code": null, "e": 27669, "s": 27652, "text": "Python-Operators" }, { "code": null, "e": 27676, "s": 27669, "text": "Python" }, { "code": null, "e": 27774, "s": 27676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27783, "s": 27774, "text": "Comments" }, { "code": null, "e": 27796, "s": 27783, "text": "Old Comments" }, { "code": null, "e": 27814, "s": 27796, "text": "Python Dictionary" }, { "code": null, "e": 27846, "s": 27814, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27881, "s": 27846, "text": "Read a file line by line in Python" }, { "code": null, "e": 27903, "s": 27881, "text": "Enumerate() in Python" }, { "code": null, "e": 27933, "s": 27903, "text": "Iterate over a list in Python" }, { "code": null, "e": 27975, "s": 27933, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28012, "s": 27975, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28038, "s": 28012, "text": "Python String | replace()" }, { "code": null, "e": 28082, "s": 28038, "text": "Reading and Writing to text files in Python" } ]
Sum the common elements | Practice | GeeksforGeeks
You are given two arrays of size n1 and n2. Your task is to find all the elements that are common to both the arrays and sum them print them in the order as they appear in the second array. If there are no common elements the output would be 0. Note: The arrays may contain duplicate elements. However, you need to sum only unique elements that are common to both arrays. Input Format: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two three lines of input. The first line contains n1 and n2 separated by a space. The second line contains elements of arr1. The third line contains elements of arr2. Output Format: For each testcase, in a new line, print the common sum. Your Task: Since this is a function problem, you don't need to take any input. Just complete the provided function commonSum that takes two arrays as input. Constraints: 1 <= T <= 100 1 <= n1,n2 <= 1000 1 <= arr1i,arr2i <= 109 Example: Input: 1 5 6 1 2 3 4 5 2 3 4 5 6 7 Output: 14 0 ankitparashxr3 months ago java int sum = 0; Set<Integer> s = new HashSet<>(); for(int val:arr1) { s.add(val); } for(int val:arr2) { if(s.contains(val)) { sum+=val; s.remove(val); } } return sum; 0 ankitparashxr3 months ago java int sum = 0; HashMap<Integer,Integer> hm = new HashMap<>(); for(int val:arr1) { if(hm.containsKey(val)) { hm.put(val,hm.get(val)+1); } else { hm.put(val,1); } } for(int val:arr2) { if(hm.containsKey(val) && hm.get(val)>0) { sum+=val; hm.remove(val); } } return (long)sum; 0 padmaraju0843 months ago def get_common(set1,set2): comm=set1 & set2 le=len(comm) if le==0: return "0" else: sum_1=sum(comm) return sum_1 def get_sets(m,n): set1=set() for value1 in range(m): a=int(input()) set1.add(a) set2=set() for value2 in range(n): b=int(input()) set2.add(b) out=get_common(set1,set2) return out t=int(input())for i in range(t): m,n=input().split(" ") m,n=int(m),int(n) out=get_sets(m,n) print(out) +1 devreujjval774 months ago //Java Solution with 0.6 TimeTaken using a HashSet class Geeks { public static long commonSum(int arr1[], int arr2[]) { //Your code here int sum = 0; Set<Integer> set = new HashSet<>(); //Using foreach loop on an array to add all- //its unique elements to the HashSet for(int i: arr1){ set.add(i); } //Looping through second array and //checking for the element in the HashSet for(int i: arr2){ if(set.contains(i)){ //adding the values on match and removing //the element from Hashset to avoid duplicates sum+=i; set.remove(i); } } return sum; } } 0 badgujarsachin836 months ago public static long commonSum(int arr1[], int arr2[]) { //Your code here int sum=0; HashSet<Integer> h=new HashSet<>(); for(int it:arr1){ h.add(it); } for(int it:arr2){ if(h.contains(it)){ h.remove(it); sum+=it; } } return sum; } 0 siddhartha agarwal8 months ago siddhartha agarwal //Java use only one hashSet class Geeks{ public static long commonSum(int arr1[], int arr2[]) { HashSet<integer> h= new HashSet<>(); for(int i:arr1) h.add(i); int sum=0; for(int i:arr2) if(h.contains(i)) { h.remove(i); sum+=i; } return sum; //Your code here }} 0 Navin Ranjan1 year ago Navin Ranjan java easy solutionHashSet<integer> hs1=new HashSet<>(); HashSet<integer> hs2=new HashSet<>(); for(int x:arr1) hs1.add(x); for(int x:arr2) hs2.add(x); long sum=0; for(int x:hs2) if(!hs1.add(x)) sum+=x; return sum; 0 Harsh2 years ago Harsh public static long commonSum(int arr1[], int arr2[]) { Set<integer> set1 = new HashSet<>(); Set<integer> set2 = new HashSet<>(); for(int i=0;i<arr1.length;i++) set1.add(arr1[i]);="" for(int="" i="0;i&lt;arr2.length;i++)" set2.add(arr2[i]);="" set2.retainall(set1);="" int="" sum="0;" for(int="" x="" :="" set2)="" sum+="x;" return="" sum;="" }=""> 0 Anant Krishan Joshi2 years ago Anant Krishan Joshi class Geeks{ public static long commonSum(int arr1[], int arr2[]) { //Your code here Set<integer> a = new HashSet<integer>(arr1.length); Set<integer> b = new HashSet<integer>(arr2.length); for(int i=0;i<arr1.length;i++) a.add(arr1[i]);="" for(int="" i="0;i&lt;arr2.length;i++)" b.add(arr2[i]);="" integer="" sum="0;" set<integer=""> s = new HashSet<integer>(a); s.retainAll(b); Iterator<integer> it = s.iterator(); while(it.hasNext()) { Integer setElement = it.next(); sum+=setElement; } return sum; } 0 Devarshi Singh3 years ago Devarshi Singh class Geeks{ public static long commonSum(int arr1[], int arr2[]) { long sum=0; Set<integer> a1 = new HashSet<integer>(); Set<integer> a2 = new HashSet<integer>(); for(int i=0;i<arr1.length;i++) a1.add(new="" integer(arr1[i]));="" for(int="" j="0;j&lt;arr2.length;j++)" a2.add(new="" integer(arr2[j]));="" a1.retainall(a2);="" can't="" use="" iterator="" here="" for(integer="" a:="" a1)="" {="" sum+="a;//Unboxing" and="" type="" conversion="" }="" return="" sum;="" }="" }=""> 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": 471, "s": 226, "text": "You are given two arrays of size n1 and n2. Your task is to find all the elements that are common to both the arrays and sum them print them in the order as they appear in the second array. If there are no common elements the output would be 0." }, { "code": null, "e": 598, "s": 471, "text": "Note: The arrays may contain duplicate elements. However, you need to sum only unique elements that are common to both arrays." }, { "code": null, "e": 891, "s": 598, "text": "Input Format:\nThe first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two three lines of input. The first line contains n1 and n2 separated by a space. The second line contains elements of arr1. The third line contains elements of arr2." }, { "code": null, "e": 962, "s": 891, "text": "Output Format:\nFor each testcase, in a new line, print the common sum." }, { "code": null, "e": 1119, "s": 962, "text": "Your Task:\nSince this is a function problem, you don't need to take any input. Just complete the provided function commonSum that takes two arrays as input." }, { "code": null, "e": 1189, "s": 1119, "text": "Constraints:\n1 <= T <= 100\n1 <= n1,n2 <= 1000\n1 <= arr1i,arr2i <= 109" }, { "code": null, "e": 1244, "s": 1189, "text": "Example:\nInput:\n1\n5 6\n1 2 3 4 5\n2 3 4 5 6 7\nOutput:\n14" }, { "code": null, "e": 1246, "s": 1244, "text": "0" }, { "code": null, "e": 1272, "s": 1246, "text": "ankitparashxr3 months ago" }, { "code": null, "e": 1277, "s": 1272, "text": "java" }, { "code": null, "e": 1523, "s": 1277, "text": "int sum = 0; Set<Integer> s = new HashSet<>(); for(int val:arr1) { s.add(val); } for(int val:arr2) { if(s.contains(val)) { sum+=val; s.remove(val); } } return sum;" }, { "code": null, "e": 1525, "s": 1523, "text": "0" }, { "code": null, "e": 1551, "s": 1525, "text": "ankitparashxr3 months ago" }, { "code": null, "e": 1556, "s": 1551, "text": "java" }, { "code": null, "e": 1985, "s": 1556, "text": "int sum = 0; HashMap<Integer,Integer> hm = new HashMap<>(); for(int val:arr1) { if(hm.containsKey(val)) { hm.put(val,hm.get(val)+1); } else { hm.put(val,1); } } for(int val:arr2) { if(hm.containsKey(val) && hm.get(val)>0) { sum+=val; hm.remove(val); } } return (long)sum;" }, { "code": null, "e": 1987, "s": 1985, "text": "0" }, { "code": null, "e": 2012, "s": 1987, "text": "padmaraju0843 months ago" }, { "code": null, "e": 2388, "s": 2012, "text": "def get_common(set1,set2): comm=set1 & set2 le=len(comm) if le==0: return \"0\" else: sum_1=sum(comm) return sum_1 def get_sets(m,n): set1=set() for value1 in range(m): a=int(input()) set1.add(a) set2=set() for value2 in range(n): b=int(input()) set2.add(b) out=get_common(set1,set2) return out" }, { "code": null, "e": 2502, "s": 2390, "text": "t=int(input())for i in range(t): m,n=input().split(\" \") m,n=int(m),int(n) out=get_sets(m,n) print(out) " }, { "code": null, "e": 2505, "s": 2502, "text": "+1" }, { "code": null, "e": 2531, "s": 2505, "text": "devreujjval774 months ago" }, { "code": null, "e": 2582, "s": 2531, "text": "//Java Solution with 0.6 TimeTaken using a HashSet" }, { "code": null, "e": 3286, "s": 2584, "text": "class Geeks\n{\n public static long commonSum(int arr1[], int arr2[])\n {\n //Your code here\n int sum = 0;\n Set<Integer> set = new HashSet<>();\n \n //Using foreach loop on an array to add all-\n //its unique elements to the HashSet\n for(int i: arr1){\n set.add(i);\n }\n \n //Looping through second array and\n //checking for the element in the HashSet\n for(int i: arr2){\n if(set.contains(i)){\n //adding the values on match and removing\n //the element from Hashset to avoid duplicates\n sum+=i;\n set.remove(i);\n }\n }\n return sum;\n }\n}" }, { "code": null, "e": 3290, "s": 3288, "text": "0" }, { "code": null, "e": 3319, "s": 3290, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 3687, "s": 3319, "text": " public static long commonSum(int arr1[], int arr2[])\n {\n //Your code here\n int sum=0;\n HashSet<Integer> h=new HashSet<>();\n for(int it:arr1){\n h.add(it);\n }\n for(int it:arr2){\n if(h.contains(it)){\n h.remove(it);\n sum+=it;\n }\n }\n return sum;\n }" }, { "code": null, "e": 3689, "s": 3687, "text": "0" }, { "code": null, "e": 3720, "s": 3689, "text": "siddhartha agarwal8 months ago" }, { "code": null, "e": 3739, "s": 3720, "text": "siddhartha agarwal" }, { "code": null, "e": 3767, "s": 3739, "text": "//Java use only one hashSet" }, { "code": null, "e": 4135, "s": 3767, "text": "class Geeks{ public static long commonSum(int arr1[], int arr2[]) { HashSet<integer> h= new HashSet<>(); for(int i:arr1) h.add(i); int sum=0; for(int i:arr2) if(h.contains(i)) { h.remove(i); sum+=i; } return sum; //Your code here }}" }, { "code": null, "e": 4137, "s": 4135, "text": "0" }, { "code": null, "e": 4160, "s": 4137, "text": "Navin Ranjan1 year ago" }, { "code": null, "e": 4173, "s": 4160, "text": "Navin Ranjan" }, { "code": null, "e": 4477, "s": 4173, "text": "java easy solutionHashSet<integer> hs1=new HashSet<>(); HashSet<integer> hs2=new HashSet<>(); for(int x:arr1) hs1.add(x); for(int x:arr2) hs2.add(x); long sum=0; for(int x:hs2) if(!hs1.add(x)) sum+=x; return sum;" }, { "code": null, "e": 4479, "s": 4477, "text": "0" }, { "code": null, "e": 4496, "s": 4479, "text": "Harsh2 years ago" }, { "code": null, "e": 4502, "s": 4496, "text": "Harsh" }, { "code": null, "e": 4871, "s": 4502, "text": "public static long commonSum(int arr1[], int arr2[]) { Set<integer> set1 = new HashSet<>(); Set<integer> set2 = new HashSet<>(); for(int i=0;i<arr1.length;i++) set1.add(arr1[i]);=\"\" for(int=\"\" i=\"0;i&lt;arr2.length;i++)\" set2.add(arr2[i]);=\"\" set2.retainall(set1);=\"\" int=\"\" sum=\"0;\" for(int=\"\" x=\"\" :=\"\" set2)=\"\" sum+=\"x;\" return=\"\" sum;=\"\" }=\"\">" }, { "code": null, "e": 4873, "s": 4871, "text": "0" }, { "code": null, "e": 4904, "s": 4873, "text": "Anant Krishan Joshi2 years ago" }, { "code": null, "e": 4924, "s": 4904, "text": "Anant Krishan Joshi" }, { "code": null, "e": 5500, "s": 4924, "text": "class Geeks{ public static long commonSum(int arr1[], int arr2[]) { //Your code here Set<integer> a = new HashSet<integer>(arr1.length); Set<integer> b = new HashSet<integer>(arr2.length); for(int i=0;i<arr1.length;i++) a.add(arr1[i]);=\"\" for(int=\"\" i=\"0;i&lt;arr2.length;i++)\" b.add(arr2[i]);=\"\" integer=\"\" sum=\"0;\" set<integer=\"\"> s = new HashSet<integer>(a); s.retainAll(b); Iterator<integer> it = s.iterator(); while(it.hasNext()) { Integer setElement = it.next(); sum+=setElement; } return sum; }" }, { "code": null, "e": 5502, "s": 5500, "text": "0" }, { "code": null, "e": 5528, "s": 5502, "text": "Devarshi Singh3 years ago" }, { "code": null, "e": 5543, "s": 5528, "text": "Devarshi Singh" }, { "code": null, "e": 5556, "s": 5543, "text": "class Geeks{" }, { "code": null, "e": 5613, "s": 5556, "text": " public static long commonSum(int arr1[], int arr2[])" }, { "code": null, "e": 5619, "s": 5613, "text": " {" }, { "code": null, "e": 5639, "s": 5619, "text": " long sum=0;" }, { "code": null, "e": 5689, "s": 5639, "text": " Set<integer> a1 = new HashSet<integer>();" }, { "code": null, "e": 5739, "s": 5689, "text": " Set<integer> a2 = new HashSet<integer>();" }, { "code": null, "e": 6062, "s": 5739, "text": " for(int i=0;i<arr1.length;i++) a1.add(new=\"\" integer(arr1[i]));=\"\" for(int=\"\" j=\"0;j&lt;arr2.length;j++)\" a2.add(new=\"\" integer(arr2[j]));=\"\" a1.retainall(a2);=\"\" can't=\"\" use=\"\" iterator=\"\" here=\"\" for(integer=\"\" a:=\"\" a1)=\"\" {=\"\" sum+=\"a;//Unboxing\" and=\"\" type=\"\" conversion=\"\" }=\"\" return=\"\" sum;=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 6208, "s": 6062, "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": 6244, "s": 6208, "text": " Login to access your submissions. " }, { "code": null, "e": 6254, "s": 6244, "text": "\nProblem\n" }, { "code": null, "e": 6264, "s": 6254, "text": "\nContest\n" }, { "code": null, "e": 6327, "s": 6264, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6475, "s": 6327, "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": 6683, "s": 6475, "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": 6789, "s": 6683, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to convert byte literals to python strings?
To convert byte literals to Python strings, you need to decode the bytes. It can be done using the decode method on the bytes object. >>> b"abcde".decode("utf-8") u'abcde' You can also map bytes to chr if the bytes represent ASCII encoding as follows − bytes = [112, 52, 52] print("".join(map(chr, bytes))) p44
[ { "code": null, "e": 1197, "s": 1062, "text": "To convert byte literals to Python strings, you need to decode the bytes. It can be done using the decode method on the bytes object. " }, { "code": null, "e": 1235, "s": 1197, "text": ">>> b\"abcde\".decode(\"utf-8\")\nu'abcde'" }, { "code": null, "e": 1316, "s": 1235, "text": "You can also map bytes to chr if the bytes represent ASCII encoding as follows −" }, { "code": null, "e": 1371, "s": 1316, "text": "bytes = [112, 52, 52]\n\nprint(\"\".join(map(chr, bytes)))" }, { "code": null, "e": 1375, "s": 1371, "text": "p44" } ]
PHP - imap_search() Function
PHP−IMAP functions helps you to access email accounts, IMAP stands for Internet Mail Access Protocol using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods. The imap_search() accepts a resource value representing an IMAP stream, and a string value representing the search criteria as parameters, searches the mailbox and returns the matched messages in the form of an array. imap_search($imap_stream, $criteria, [$options, $charset]); imap_stream (Mandatory)s This is a string value representing an IMAP stream, return value of the imap_open() function. criteria (Mandatory) This is a string value representing the search criteria. options (Optional) This is a string value representing the optional value SE_UID. On setting the array retuned contains UID’s instead of message sequences. $charset (Optional) This is a string value representing the MIME character set to use during the search. This function returns an array which contains the message numbers/UID’s representing the matched messages in case of success and a Boolean value FALSE in case of failure. This function was first introduced in PHP Version 4 and works in all the later versions. Following is another example of this function − <html> <body> <?php //Establishing connection $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX"; $id = "[email protected]"; $pwd = "cohondob_123"; $imap = imap_open($url, $id, $pwd); print("Connection established...."."<br>"); print("Results of the search: "."<br>"); $emailData = imap_search($imap, ''); print_r($emailData); //Closing the connection imap_close($imap); ?> </body> </html> This generates the following output − Connection established.... Results of the search: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) Following is another example of this function; this reads the unseen messages in the current inbox − <html> <body> <?php //Establishing connection $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX"; $id = "[email protected]"; $pwd = "cohondob_123"; $imap = imap_open($url, $id, $pwd); print("Connection established...."."<br>"); print("Contents of the matched messages: "."<br>"); $emailData = imap_search($imap, "UNSEEN"); foreach ($emailData as $msg) { $msg = imap_fetchbody($imap, $msg, "1"); print(quoted_printable_decode($msg)."<br>"); } //Closing the connection imap_close($imap); ?> </body> </html> This will generate the following output − Connection established.... Contents of the matched messages: Array ( [0] => 4 [1] => 5 [2] => 6 ) #sample_mail4 #sample_mail5 #sample_mail6 Following is an example of this function with optional parameters − <html> <body> <?php //Establishing connection $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX"; $id = "[email protected]"; $pwd = "cohondob_123"; $imap = imap_open($url, $id, $pwd); print("Connection established...."."<br>"); print("Contents of the matched messages: "."<br>"); $data = imap_search($imap, "ALL", SE_UID); print_r($data); //Closing the connection imap_close($imap); ?> </body> </html> This will generate the following output − Connection established.... Contents of the matched messages: Array ( [0] => 19 [1] => 20 [2] => 42 [3] => 49 [4] => 50 [5] => 51 ) 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2958, "s": 2757, "text": "PHP−IMAP functions helps you to access email accounts, IMAP stands for Internet Mail Access Protocol using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods." }, { "code": null, "e": 3176, "s": 2958, "text": "The imap_search() accepts a resource value representing an IMAP stream, and a string value representing the search criteria as parameters, searches the mailbox and returns the matched messages in the form of an array." }, { "code": null, "e": 3237, "s": 3176, "text": "imap_search($imap_stream, $criteria, [$options, $charset]);\n" }, { "code": null, "e": 3262, "s": 3237, "text": "imap_stream (Mandatory)s" }, { "code": null, "e": 3356, "s": 3262, "text": "This is a string value representing an IMAP stream, return value of the imap_open() function." }, { "code": null, "e": 3377, "s": 3356, "text": "criteria (Mandatory)" }, { "code": null, "e": 3434, "s": 3377, "text": "This is a string value representing the search criteria." }, { "code": null, "e": 3453, "s": 3434, "text": "options (Optional)" }, { "code": null, "e": 3590, "s": 3453, "text": "This is a string value representing the optional value SE_UID. On setting the array retuned contains UID’s instead of message sequences." }, { "code": null, "e": 3611, "s": 3590, "text": "$charset (Optional) " }, { "code": null, "e": 3696, "s": 3611, "text": "This is a string value representing the MIME character set to use during the search." }, { "code": null, "e": 3867, "s": 3696, "text": "This function returns an array which contains the message numbers/UID’s representing the matched messages in case of success and a Boolean value FALSE in case of failure." }, { "code": null, "e": 3956, "s": 3867, "text": "This function was first introduced in PHP Version 4 and works in all the later versions." }, { "code": null, "e": 4004, "s": 3956, "text": "Following is another example of this function −" }, { "code": null, "e": 4551, "s": 4004, "text": "<html>\n <body>\n <?php\n //Establishing connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"[email protected]\";\n $pwd = \"cohondob_123\";\n $imap = imap_open($url, $id, $pwd);\n print(\"Connection established....\".\"<br>\");\n print(\"Results of the search: \".\"<br>\");\n \n $emailData = imap_search($imap, '');\n print_r($emailData);\n\t \n //Closing the connection\n imap_close($imap); \n ?>\n </body>\n</html>" }, { "code": null, "e": 4589, "s": 4551, "text": "This generates the following output −" }, { "code": null, "e": 4704, "s": 4589, "text": "Connection established....\nResults of the search:\nArray ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )\n" }, { "code": null, "e": 4805, "s": 4704, "text": "Following is another example of this function; this reads the unseen messages in the current inbox −" }, { "code": null, "e": 5504, "s": 4805, "text": "<html>\n <body>\n <?php\n //Establishing connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"[email protected]\";\n $pwd = \"cohondob_123\";\n $imap = imap_open($url, $id, $pwd);\n print(\"Connection established....\".\"<br>\");\n print(\"Contents of the matched messages: \".\"<br>\");\n $emailData = imap_search($imap, \"UNSEEN\");\n foreach ($emailData as $msg) {\n $msg = imap_fetchbody($imap, $msg, \"1\");\n print(quoted_printable_decode($msg).\"<br>\"); \n } \n //Closing the connection\n imap_close($imap); \n ?>\n </body>\n</html>" }, { "code": null, "e": 5546, "s": 5504, "text": "This will generate the following output −" }, { "code": null, "e": 5687, "s": 5546, "text": "Connection established....\nContents of the matched messages:\nArray ( [0] => 4 [1] => 5 [2] => 6 )\n#sample_mail4\n#sample_mail5\n#sample_mail6\n" }, { "code": null, "e": 5755, "s": 5687, "text": "Following is an example of this function with optional parameters −" }, { "code": null, "e": 6304, "s": 5755, "text": "<html>\n <body>\n <?php\n //Establishing connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"[email protected]\";\n $pwd = \"cohondob_123\";\n $imap = imap_open($url, $id, $pwd);\n print(\"Connection established....\".\"<br>\");\n print(\"Contents of the matched messages: \".\"<br>\");\n $data = imap_search($imap, \"ALL\", SE_UID);\n print_r($data);\n \n //Closing the connection\n imap_close($imap); \n ?>\n </body>\n</html>" }, { "code": null, "e": 6346, "s": 6304, "text": "This will generate the following output −" }, { "code": null, "e": 6503, "s": 6346, "text": "Connection established....\nContents of the matched messages:\nArray ( \n [0] => 19 \n [1] => 20 \n [2] => 42 \n [3] => 49 \n [4] => 50 \n [5] => 51 \n)\n" }, { "code": null, "e": 6536, "s": 6503, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 6552, "s": 6536, "text": " Malhar Lathkar" }, { "code": null, "e": 6585, "s": 6552, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6596, "s": 6585, "text": " Syed Raza" }, { "code": null, "e": 6631, "s": 6596, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6648, "s": 6631, "text": " Frahaan Hussain" }, { "code": null, "e": 6681, "s": 6648, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6696, "s": 6681, "text": " Nivedita Jain" }, { "code": null, "e": 6731, "s": 6696, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 6743, "s": 6731, "text": " Azaz Patel" }, { "code": null, "e": 6778, "s": 6743, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6806, "s": 6778, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6813, "s": 6806, "text": " Print" }, { "code": null, "e": 6824, "s": 6813, "text": " Add Notes" } ]
log() function in C++
The C/C++ library function double log(double x) returns the natural logarithm (basee logarithm) of x. Following is the declaration for log() function. double log(double x) The parameter is a floating point value. And this function returns natural logarithm of x. Live Demo #include <iostream> #include <cmath> using namespace std; int main () { double x, ret; x = 2.7; /* finding log(2.7) */ ret = log(x); cout << "log("<< x <<") = " << ret; return(0); } log(2.7) = 0.993252
[ { "code": null, "e": 1213, "s": 1062, "text": "The C/C++ library function double log(double x) returns the natural logarithm (basee\nlogarithm) of x. Following is the declaration for log() function." }, { "code": null, "e": 1234, "s": 1213, "text": "double log(double x)" }, { "code": null, "e": 1325, "s": 1234, "text": "The parameter is a floating point value. And this function returns natural logarithm\nof x." }, { "code": null, "e": 1336, "s": 1325, "text": " Live Demo" }, { "code": null, "e": 1536, "s": 1336, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main () {\n double x, ret;\n x = 2.7;\n /* finding log(2.7) */\n ret = log(x);\n cout << \"log(\"<< x <<\") = \" << ret;\n return(0);\n}" }, { "code": null, "e": 1556, "s": 1536, "text": "log(2.7) = 0.993252" } ]
Building bar charts using Matplotlib | by Mubarak Ganiyu | Towards Data Science
A bar graph is a data visualization technique that can be used to represent numerical values in a dataset to show how different datapoints vary from each other. It utilizes a bar as a measure of magnitudes. The bigger the bar, the higher the number. For instance, if one is comparing wealth, a bigger bar in a bar graph signifies a lot of money compared to a smaller bar. The premier league 2019/20 mid-season highest goal scorers dataset was loaded using Jupyter Notebook on IBM Watson Studio. In order to run codes that will generate a bar graph, a data visualization package called matplotlib is imported. Below is a set of codes for importing the bar graph. Matplotlib is used in python programming language as a plotting library. ## Import data visualization packagesimport matplotlib.pyplot as plt%matplotlib inline The bar graph is built after installing the package by running the set of codes below. plt.bar("Player", "Stat", data = df_goal, color = "blue")plt.xlabel("Players")plt.ylabel("Goal Scored")plt.title("Highest goal scorers in the Premier league 2019-20 by mid-season")plt.show() plt.bar(“Player”, “Stat”, data = df_goal, color = “blue”) is used to signify that a bar graph wants to be plotted using the Player column as the x-axis, the Stat column as the y-axis, the df_goal dataset is to be used and the color of the bars are blue. plt.xlabel(“Players”) and plt.ylabel(“Goal Scored”) are used to label the x-axis and y-axis respectively. plt.title(“Highest goal scorers in the Premier league 2019–20 by mid-season”) is used to make a title for the graph. plt.show( ) is used to generate the graph using the previous commands. The result of the code ran above can be viewed below. It can be observed in the bar graph above that the x-axis ticks cannot be seen properly. Thus, the x-axis ticks can become visible after rotation. Below is a set of codes that modifies the bar graph. plt.bar("Player", "Stat", data = df_goal, color = "blue")plt.xlabel("Players")plt.xticks(rotation = 90)plt.ylabel("Goal Scored")plt.title("Highest goal scorers in the Premier league 2019-20 by mid-season")plt.show() By adding plt.xticks(rotation = 90), the bar graph can be transformed into: This is a cleaner bar graph with the x-axis ticks now vertical and visible. A horizontal bar graph can also be built by changing the plt.bar to plt.barh in the previous set of codes. plt.barh("Player", "Stat", data = df_goal, color = "red") plt.xlabel("Players") plt.ylabel("Goal Scored") plt.title("Highest goal scorers in the Premier league 2019-20 by mid-season")plt.show() Both the bar graph and the horizontal bar graphs can be modified to look more beautiful. The bar graph can be modified by running the set of codes below. df_goal2 = df_goal[['Player', 'Stat']].sort_values(by = 'Stat', ascending = True)ind = df_goal2.set_index("Player", inplace = True)## A modified bar graphbar = df_goal2.plot(kind='bar',figsize=(30, 16), color = "blue", legend = None)barplt.yticks(fontsize = 24)plt.xticks(ind,fontsize = 18)plt.xlabel("Players", fontsize = 20)plt.ylabel("Goal scored", fontsize = 20)plt.title("Higehst goal scorers in the premier league mid-season of 2019/20", fontsize=32)bar.spines['top'].set_visible(False)bar.spines['right'].set_visible(False)bar.spines['bottom'].set_linewidth(0.5)bar.spines['left'].set_visible(True)plt.show() A few additions were made compared to the regular codes for building a bar graph. It can be seen above an object called bar is created by using the newly-formed dataset, df_goal2, to design a bar graph with the code, bar = df_goal2.plot(kind=’bar’,figsize=(30, 16), color = “blue”, legend = None). The ind was used to store the index that would be represented by the x-axis. The spines were removed on the top and right sides but the bottom and left spines were left visible using the codes: bar.spines[‘top’].set_visible(False), bar.spines[‘right’].set_visible(False), bar.spines[‘bottom’].set_linewidth(0.5) and bar.spines[‘left’].set_visible(True). The result of these codes can be seen below. The same process for beautifying the bar graph is applied for the horizontal bar graph. Below is a set of codes for building the beautified version. ## A modified horizontal bar graphbarh = df_goal2.plot(kind='barh',figsize=(30, 16), color = "red", legend = None)barhplt.yticks(fontsize = 24)plt.xticks(ind,fontsize = 18)plt.xlabel("Goal scored", fontsize = 22)plt.ylabel("Players", fontsize = 22)plt.title("Higehst goal scorers in the premier league mid-season of 2019/20", fontsize=32)barh.spines['top'].set_visible(False)barh.spines['right'].set_visible(False)barh.spines['bottom'].set_linewidth(0.5)barh.spines['left'].set_visible(True)plt.show() After running the codes, the result came out as the horizontal bar graph below: Same observations that was made about the spines in the beautified bar graph can be made about the spines in this graph as well. Bar graphs are very useful in multiple numerical applications such as showing how people’s health improvements have changed over time, depicting how wealth increases and other interesting concepts. The full version of the code that was used for this project can be found here.
[ { "code": null, "e": 543, "s": 171, "text": "A bar graph is a data visualization technique that can be used to represent numerical values in a dataset to show how different datapoints vary from each other. It utilizes a bar as a measure of magnitudes. The bigger the bar, the higher the number. For instance, if one is comparing wealth, a bigger bar in a bar graph signifies a lot of money compared to a smaller bar." }, { "code": null, "e": 666, "s": 543, "text": "The premier league 2019/20 mid-season highest goal scorers dataset was loaded using Jupyter Notebook on IBM Watson Studio." }, { "code": null, "e": 906, "s": 666, "text": "In order to run codes that will generate a bar graph, a data visualization package called matplotlib is imported. Below is a set of codes for importing the bar graph. Matplotlib is used in python programming language as a plotting library." }, { "code": null, "e": 993, "s": 906, "text": "## Import data visualization packagesimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 1080, "s": 993, "text": "The bar graph is built after installing the package by running the set of codes below." }, { "code": null, "e": 1271, "s": 1080, "text": "plt.bar(\"Player\", \"Stat\", data = df_goal, color = \"blue\")plt.xlabel(\"Players\")plt.ylabel(\"Goal Scored\")plt.title(\"Highest goal scorers in the Premier league 2019-20 by mid-season\")plt.show()" }, { "code": null, "e": 1819, "s": 1271, "text": "plt.bar(“Player”, “Stat”, data = df_goal, color = “blue”) is used to signify that a bar graph wants to be plotted using the Player column as the x-axis, the Stat column as the y-axis, the df_goal dataset is to be used and the color of the bars are blue. plt.xlabel(“Players”) and plt.ylabel(“Goal Scored”) are used to label the x-axis and y-axis respectively. plt.title(“Highest goal scorers in the Premier league 2019–20 by mid-season”) is used to make a title for the graph. plt.show( ) is used to generate the graph using the previous commands." }, { "code": null, "e": 1873, "s": 1819, "text": "The result of the code ran above can be viewed below." }, { "code": null, "e": 2073, "s": 1873, "text": "It can be observed in the bar graph above that the x-axis ticks cannot be seen properly. Thus, the x-axis ticks can become visible after rotation. Below is a set of codes that modifies the bar graph." }, { "code": null, "e": 2289, "s": 2073, "text": "plt.bar(\"Player\", \"Stat\", data = df_goal, color = \"blue\")plt.xlabel(\"Players\")plt.xticks(rotation = 90)plt.ylabel(\"Goal Scored\")plt.title(\"Highest goal scorers in the Premier league 2019-20 by mid-season\")plt.show()" }, { "code": null, "e": 2365, "s": 2289, "text": "By adding plt.xticks(rotation = 90), the bar graph can be transformed into:" }, { "code": null, "e": 2441, "s": 2365, "text": "This is a cleaner bar graph with the x-axis ticks now vertical and visible." }, { "code": null, "e": 2548, "s": 2441, "text": "A horizontal bar graph can also be built by changing the plt.bar to plt.barh in the previous set of codes." }, { "code": null, "e": 2742, "s": 2548, "text": "plt.barh(\"Player\", \"Stat\", data = df_goal, color = \"red\") plt.xlabel(\"Players\") plt.ylabel(\"Goal Scored\") plt.title(\"Highest goal scorers in the Premier league 2019-20 by mid-season\")plt.show()" }, { "code": null, "e": 2831, "s": 2742, "text": "Both the bar graph and the horizontal bar graphs can be modified to look more beautiful." }, { "code": null, "e": 2896, "s": 2831, "text": "The bar graph can be modified by running the set of codes below." }, { "code": null, "e": 3512, "s": 2896, "text": "df_goal2 = df_goal[['Player', 'Stat']].sort_values(by = 'Stat', ascending = True)ind = df_goal2.set_index(\"Player\", inplace = True)## A modified bar graphbar = df_goal2.plot(kind='bar',figsize=(30, 16), color = \"blue\", legend = None)barplt.yticks(fontsize = 24)plt.xticks(ind,fontsize = 18)plt.xlabel(\"Players\", fontsize = 20)plt.ylabel(\"Goal scored\", fontsize = 20)plt.title(\"Higehst goal scorers in the premier league mid-season of 2019/20\", fontsize=32)bar.spines['top'].set_visible(False)bar.spines['right'].set_visible(False)bar.spines['bottom'].set_linewidth(0.5)bar.spines['left'].set_visible(True)plt.show()" }, { "code": null, "e": 3887, "s": 3512, "text": "A few additions were made compared to the regular codes for building a bar graph. It can be seen above an object called bar is created by using the newly-formed dataset, df_goal2, to design a bar graph with the code, bar = df_goal2.plot(kind=’bar’,figsize=(30, 16), color = “blue”, legend = None). The ind was used to store the index that would be represented by the x-axis." }, { "code": null, "e": 4164, "s": 3887, "text": "The spines were removed on the top and right sides but the bottom and left spines were left visible using the codes: bar.spines[‘top’].set_visible(False), bar.spines[‘right’].set_visible(False), bar.spines[‘bottom’].set_linewidth(0.5) and bar.spines[‘left’].set_visible(True)." }, { "code": null, "e": 4209, "s": 4164, "text": "The result of these codes can be seen below." }, { "code": null, "e": 4358, "s": 4209, "text": "The same process for beautifying the bar graph is applied for the horizontal bar graph. Below is a set of codes for building the beautified version." }, { "code": null, "e": 4860, "s": 4358, "text": "## A modified horizontal bar graphbarh = df_goal2.plot(kind='barh',figsize=(30, 16), color = \"red\", legend = None)barhplt.yticks(fontsize = 24)plt.xticks(ind,fontsize = 18)plt.xlabel(\"Goal scored\", fontsize = 22)plt.ylabel(\"Players\", fontsize = 22)plt.title(\"Higehst goal scorers in the premier league mid-season of 2019/20\", fontsize=32)barh.spines['top'].set_visible(False)barh.spines['right'].set_visible(False)barh.spines['bottom'].set_linewidth(0.5)barh.spines['left'].set_visible(True)plt.show()" }, { "code": null, "e": 4940, "s": 4860, "text": "After running the codes, the result came out as the horizontal bar graph below:" }, { "code": null, "e": 5069, "s": 4940, "text": "Same observations that was made about the spines in the beautified bar graph can be made about the spines in this graph as well." }, { "code": null, "e": 5267, "s": 5069, "text": "Bar graphs are very useful in multiple numerical applications such as showing how people’s health improvements have changed over time, depicting how wealth increases and other interesting concepts." } ]
Change Y-Axis to Percentage Points in ggplot2 Barplot in R - GeeksforGeeks
24 Jun, 2021 In this article, we will discuss how to change the Y-axis to percentage using the ggplot2 bar plot in R Programming Language. First, you need to install the ggplot2 package if it is not previously installed in R Studio. To install and load write the below command in R Console : install.packages("ggplot2") library(ggplo2) For creating a simple bar plot we will use the function geom_bar( ). Syntax: geom_bar(stat, fill, color, width) Parameters : stat : Set the stat parameter to identify the mode. fill : Represents color inside the bars. color : Represents color of outlines of the bars. width : Represents width of the bars. First, we will create a Data Frame which has two vectors “letter” and “probability” and stores it in a variable prob. R # Insert Dataprob <- data.frame(letter = c("B1","B2","B3","B4","B5"), probability = c(0.5, 0.1, 0.2, 0.8, 0.3)) head(prob) Let’s create a simple bar plot. R # Insert Plotlibrary("ggplot2") dt <- ggplot(data=prob, aes(x=letter, y=probability)) + geom_bar(stat = "identity") dt Some important keywords used are : accuracy: The precision value to which a number is round to. scale: It is used for scaling the data. A scaling factor is multiplied with the original data value.labels: It is used to assign labels. accuracy: The precision value to which a number is round to. scale: It is used for scaling the data. A scaling factor is multiplied with the original data value. labels: It is used to assign labels. The function used is scale_y_continuous( ) which is a default scale in “y-aesthetics” in the library ggplot2. Since we need to add percentages in the labels of the Y-axis, the keyword “labels” is used. Now use scales: : percent to convert the y-axis labels into a percentage. This will scale the y-axis data from decimal to percentage. It simply multiplies the value by 100. The scaling factor is 100. In the above code add : R # Changing Y-axis to percentagedt + scale_y_continuous(labels = scales::percent) Output: In older versions of R, using the above code you may get the percentage values having one digit after the decimal in the Y-axis as shown in the above example. In such a case, we will use the function percent_format( ) to modify the accuracy of the percentage labels in Y-axis. It is basically used to assign the precision value in order to round it. Now, modify the above code into : R # Accuracy of y-axisdt + scale_y_continuous(labels = scales::percent_format(accuracy = 1)) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n24 Jun, 2021" }, { "code": null, "e": 24977, "s": 24851, "text": "In this article, we will discuss how to change the Y-axis to percentage using the ggplot2 bar plot in R Programming Language." }, { "code": null, "e": 25130, "s": 24977, "text": "First, you need to install the ggplot2 package if it is not previously installed in R Studio. To install and load write the below command in R Console :" }, { "code": null, "e": 25174, "s": 25130, "text": "install.packages(\"ggplot2\")\nlibrary(ggplo2)" }, { "code": null, "e": 25243, "s": 25174, "text": "For creating a simple bar plot we will use the function geom_bar( )." }, { "code": null, "e": 25251, "s": 25243, "text": "Syntax:" }, { "code": null, "e": 25286, "s": 25251, "text": "geom_bar(stat, fill, color, width)" }, { "code": null, "e": 25301, "s": 25286, "text": "Parameters : " }, { "code": null, "e": 25353, "s": 25301, "text": "stat : Set the stat parameter to identify the mode." }, { "code": null, "e": 25394, "s": 25353, "text": "fill : Represents color inside the bars." }, { "code": null, "e": 25444, "s": 25394, "text": "color : Represents color of outlines of the bars." }, { "code": null, "e": 25482, "s": 25444, "text": "width : Represents width of the bars." }, { "code": null, "e": 25600, "s": 25482, "text": "First, we will create a Data Frame which has two vectors “letter” and “probability” and stores it in a variable prob." }, { "code": null, "e": 25602, "s": 25600, "text": "R" }, { "code": "# Insert Dataprob <- data.frame(letter = c(\"B1\",\"B2\",\"B3\",\"B4\",\"B5\"), probability = c(0.5, 0.1, 0.2, 0.8, 0.3)) head(prob)", "e": 25744, "s": 25602, "text": null }, { "code": null, "e": 25776, "s": 25744, "text": "Let’s create a simple bar plot." }, { "code": null, "e": 25778, "s": 25776, "text": "R" }, { "code": "# Insert Plotlibrary(\"ggplot2\") dt <- ggplot(data=prob, aes(x=letter, y=probability)) + geom_bar(stat = \"identity\") dt", "e": 25900, "s": 25778, "text": null }, { "code": null, "e": 25935, "s": 25900, "text": "Some important keywords used are :" }, { "code": null, "e": 26133, "s": 25935, "text": "accuracy: The precision value to which a number is round to. scale: It is used for scaling the data. A scaling factor is multiplied with the original data value.labels: It is used to assign labels." }, { "code": null, "e": 26195, "s": 26133, "text": "accuracy: The precision value to which a number is round to. " }, { "code": null, "e": 26296, "s": 26195, "text": "scale: It is used for scaling the data. A scaling factor is multiplied with the original data value." }, { "code": null, "e": 26333, "s": 26296, "text": "labels: It is used to assign labels." }, { "code": null, "e": 26535, "s": 26333, "text": "The function used is scale_y_continuous( ) which is a default scale in “y-aesthetics” in the library ggplot2. Since we need to add percentages in the labels of the Y-axis, the keyword “labels” is used." }, { "code": null, "e": 26735, "s": 26535, "text": "Now use scales: : percent to convert the y-axis labels into a percentage. This will scale the y-axis data from decimal to percentage. It simply multiplies the value by 100. The scaling factor is 100." }, { "code": null, "e": 26759, "s": 26735, "text": "In the above code add :" }, { "code": null, "e": 26761, "s": 26759, "text": "R" }, { "code": "# Changing Y-axis to percentagedt + scale_y_continuous(labels = scales::percent)", "e": 26842, "s": 26761, "text": null }, { "code": null, "e": 26850, "s": 26842, "text": "Output:" }, { "code": null, "e": 27200, "s": 26850, "text": "In older versions of R, using the above code you may get the percentage values having one digit after the decimal in the Y-axis as shown in the above example. In such a case, we will use the function percent_format( ) to modify the accuracy of the percentage labels in Y-axis. It is basically used to assign the precision value in order to round it." }, { "code": null, "e": 27234, "s": 27200, "text": "Now, modify the above code into :" }, { "code": null, "e": 27236, "s": 27234, "text": "R" }, { "code": "# Accuracy of y-axisdt + scale_y_continuous(labels = scales::percent_format(accuracy = 1))", "e": 27327, "s": 27236, "text": null }, { "code": null, "e": 27335, "s": 27327, "text": "Output:" }, { "code": null, "e": 27342, "s": 27335, "text": "Picked" }, { "code": null, "e": 27351, "s": 27342, "text": "R-ggplot" }, { "code": null, "e": 27362, "s": 27351, "text": "R Language" }, { "code": null, "e": 27460, "s": 27362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27469, "s": 27460, "text": "Comments" }, { "code": null, "e": 27482, "s": 27469, "text": "Old Comments" }, { "code": null, "e": 27534, "s": 27482, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27572, "s": 27534, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27607, "s": 27572, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27665, "s": 27607, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27714, "s": 27665, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27757, "s": 27714, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27807, "s": 27757, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27824, "s": 27807, "text": "R - if statement" }, { "code": null, "e": 27861, "s": 27824, "text": "How to import an Excel File into R ?" } ]
How to get the Azure storage container blobs (files) using Azure CLI in PowerShell?
To get the azure storage container blobs using Azure CLI, we can use “az storage account” along with the blob commands. If you are not connected to the Azure cloud then use “az login” and set the proper subscription using “az account set” before running the storage commands. To get access to the Azure storage account, we will use here storage connection string. In the below example, we are retrieving the connection string and store it into the variable. $storageaccount = 'az204storage05june' $connectionstring = az storage account show-connection-string - n $storageaccount -otsv Once we have the connection string available, we can retrieve the blobs (Files) stored in the container. az storage blob list --container-name container1 --connectionstring $connectionstring -otable
[ { "code": null, "e": 1463, "s": 1187, "text": "To get the azure storage container blobs using Azure CLI, we can use “az storage account” along with the blob commands. If you are not connected to the Azure cloud then use “az login” and set the proper subscription using “az account set” before running the storage commands." }, { "code": null, "e": 1645, "s": 1463, "text": "To get access to the Azure storage account, we will use here storage connection string. In the below example, we are retrieving the connection string and store it into the variable." }, { "code": null, "e": 1772, "s": 1645, "text": "$storageaccount = 'az204storage05june'\n$connectionstring = az storage account show-connection-string -\nn $storageaccount -otsv" }, { "code": null, "e": 1877, "s": 1772, "text": "Once we have the connection string available, we can retrieve the blobs (Files) stored in the container." }, { "code": null, "e": 1971, "s": 1877, "text": "az storage blob list --container-name container1 --connectionstring $connectionstring -otable" } ]
Mathematics | L U Decomposition of a System of Linear Equations
20 Jul, 2021 LU decomposition of a matrix is the factorization of a given square matrix into two triangular matrices, one upper triangular matrix and one lower triangular matrix, such that the product of these two matrices gives the original matrix. It was introduced by Alan Turing in 1948, who also created the Turing machine. This method of factorizing a matrix as a product of two triangular matrices has various applications such as a solution of a system of equations, which itself is an integral part of many applications such as finding current in a circuit and solution of discrete dynamical system problems; finding the inverse of a matrix and finding the determinant of the matrix.Basically, the LU decomposition method comes in handy whenever it is possible to model the problem to be solved into matrix form. Conversion to the matrix form and solving with triangular matrices makes it easy to do calculations in the process of finding the solution. A square matrix A can be decomposed into two square matrices L and U such that A = L U where U is an upper triangular matrix formed as a result of applying the Gauss Elimination Method on A, and L is a lower triangular matrix with diagonal elements being equal to 1. For A = , we have L = and U = ; such that A = L U. Here value of l21 , u11 etc can be compared and found. Gauss Elimination MethodAccording to the Gauss Elimination method: Any zero row should be at the bottom of the matrix.The first non zero entry of each row should be on the right-hand side of the first non zero entry of the preceding row. This method reduces the matrix to row echelon form. Any zero row should be at the bottom of the matrix. The first non zero entry of each row should be on the right-hand side of the first non zero entry of the preceding row. This method reduces the matrix to row echelon form. Steps for LU Decomposition: Given a set of linear equations, first convert them into matrix form A X = C where A is the coefficient matrix, X is the variable matrix and C is the matrix of numbers on the right-hand side of the equations. Now, reduce the coefficient matrix A, i.e., the matrix obtained from the coefficients of variables in all the given equations such that for ‘n’ variables we have an nXn matrix, to row echelon form using Gauss Elimination Method. The matrix so obtained is U. To find L, we have two methods. The first one is to assume the remaining elements as some artificial variables, make equations using A = L U and solve them to find those artificial variables.The other method is that the remaining elements are the multiplier coefficients because of which the respective positions became zero in the U matrix. (This method is a little tricky to understand by words but would get clear in the example below) Now, we have A (the nXn coefficient matrix), L (the nXn lower triangular matrix), U (the nXn upper triangular matrix), X (the nX1 matrix of variables) and C (the nX1 matrix of numbers on the right-hand side of the equations). The given system of equations is A X = C. We substitute A = L U. Thus, we have L U X = C.We put Z = U X, where Z is a matrix or artificial variables and solve for L Z = C first and then solve for U X = Z to find X or the values of the variables, which was required. Example:Solve the following system of equations using LU Decomposition method: Solution: Here, we have A = and such that A X = C. Now, we first consider and convert it to row echelon form using Gauss Elimination Method. So, by doing (1) (2) we get Now, by doing (3) we get (Remember to always keep ‘ – ‘ sign in between, replace ‘ + ‘ sign by two ‘ – ‘ signs) Hence, we get L = and U = (notice that in L matrix, is from (1), is from (2) and is from (3)) Now, we assume Z and solve L Z = C. So, we have Solving, we get , and . Now, we solve U X = Z Therefore, we get , Thus, the solution to the given system of linear equations is , , and hence the matrix X = Exercise:In the LU decomposition of the matrix | 2 2 | | 4 9 | , if the diagonal elements of U are both 1, then the lower diagonal entry l22 of L is (GATE CS 2015)(A) 4(B) 5(C) 6(D) 7For Solution, see https://www.geeksforgeeks.org/gate-gate-cs-2015-set-1-question-28/ This article is compiled by Nishant Arora. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. VaibhavRai3 Arrays Engineering Mathematics GATE CS Mathematical Matrix Arrays Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Inequalities in LaTeX Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jul, 2021" }, { "code": null, "e": 368, "s": 52, "text": "LU decomposition of a matrix is the factorization of a given square matrix into two triangular matrices, one upper triangular matrix and one lower triangular matrix, such that the product of these two matrices gives the original matrix. It was introduced by Alan Turing in 1948, who also created the Turing machine." }, { "code": null, "e": 1001, "s": 368, "text": "This method of factorizing a matrix as a product of two triangular matrices has various applications such as a solution of a system of equations, which itself is an integral part of many applications such as finding current in a circuit and solution of discrete dynamical system problems; finding the inverse of a matrix and finding the determinant of the matrix.Basically, the LU decomposition method comes in handy whenever it is possible to model the problem to be solved into matrix form. Conversion to the matrix form and solving with triangular matrices makes it easy to do calculations in the process of finding the solution." }, { "code": null, "e": 1268, "s": 1001, "text": "A square matrix A can be decomposed into two square matrices L and U such that A = L U where U is an upper triangular matrix formed as a result of applying the Gauss Elimination Method on A, and L is a lower triangular matrix with diagonal elements being equal to 1." }, { "code": null, "e": 1321, "s": 1268, "text": "For A = , we have L = and U = ; such that A = L U." }, { "code": null, "e": 1376, "s": 1321, "text": "Here value of l21 , u11 etc can be compared and found." }, { "code": null, "e": 1443, "s": 1376, "text": "Gauss Elimination MethodAccording to the Gauss Elimination method:" }, { "code": null, "e": 1666, "s": 1443, "text": "Any zero row should be at the bottom of the matrix.The first non zero entry of each row should be on the right-hand side of the first non zero entry of the preceding row. This method reduces the matrix to row echelon form." }, { "code": null, "e": 1718, "s": 1666, "text": "Any zero row should be at the bottom of the matrix." }, { "code": null, "e": 1890, "s": 1718, "text": "The first non zero entry of each row should be on the right-hand side of the first non zero entry of the preceding row. This method reduces the matrix to row echelon form." }, { "code": null, "e": 1918, "s": 1890, "text": "Steps for LU Decomposition:" }, { "code": null, "e": 2127, "s": 1918, "text": "Given a set of linear equations, first convert them into matrix form A X = C where A is the coefficient matrix, X is the variable matrix and C is the matrix of numbers on the right-hand side of the equations." }, { "code": null, "e": 2385, "s": 2127, "text": "Now, reduce the coefficient matrix A, i.e., the matrix obtained from the coefficients of variables in all the given equations such that for ‘n’ variables we have an nXn matrix, to row echelon form using Gauss Elimination Method. The matrix so obtained is U." }, { "code": null, "e": 2824, "s": 2385, "text": "To find L, we have two methods. The first one is to assume the remaining elements as some artificial variables, make equations using A = L U and solve them to find those artificial variables.The other method is that the remaining elements are the multiplier coefficients because of which the respective positions became zero in the U matrix. (This method is a little tricky to understand by words but would get clear in the example below)" }, { "code": null, "e": 3050, "s": 2824, "text": "Now, we have A (the nXn coefficient matrix), L (the nXn lower triangular matrix), U (the nXn upper triangular matrix), X (the nX1 matrix of variables) and C (the nX1 matrix of numbers on the right-hand side of the equations)." }, { "code": null, "e": 3316, "s": 3050, "text": "The given system of equations is A X = C. We substitute A = L U. Thus, we have L U X = C.We put Z = U X, where Z is a matrix or artificial variables and solve for L Z = C first and then solve for U X = Z to find X or the values of the variables, which was required." }, { "code": null, "e": 3395, "s": 3316, "text": "Example:Solve the following system of equations using LU Decomposition method:" }, { "code": null, "e": 3424, "s": 3400, "text": "Solution: Here, we have" }, { "code": null, "e": 3453, "s": 3424, "text": "A = and such that A X = C." }, { "code": null, "e": 3544, "s": 3453, "text": "Now, we first consider and convert it to row echelon form using Gauss Elimination Method." }, { "code": null, "e": 3557, "s": 3544, "text": "So, by doing" }, { "code": null, "e": 3564, "s": 3557, "text": "(1) " }, { "code": null, "e": 3571, "s": 3564, "text": "(2) " }, { "code": null, "e": 3578, "s": 3571, "text": "we get" }, { "code": null, "e": 3594, "s": 3580, "text": "Now, by doing" }, { "code": null, "e": 3601, "s": 3594, "text": "(3) " }, { "code": null, "e": 3608, "s": 3601, "text": "we get" }, { "code": null, "e": 3695, "s": 3608, "text": "(Remember to always keep ‘ – ‘ sign in between, replace ‘ + ‘ sign by two ‘ – ‘ signs)" }, { "code": null, "e": 3723, "s": 3695, "text": "Hence, we get L = and U = " }, { "code": null, "e": 3794, "s": 3723, "text": "(notice that in L matrix, is from (1), is from (2) and is from (3))" }, { "code": null, "e": 3831, "s": 3794, "text": "Now, we assume Z and solve L Z = C." }, { "code": null, "e": 3848, "s": 3833, "text": "So, we have " }, { "code": null, "e": 3874, "s": 3848, "text": "Solving, we get , and ." }, { "code": null, "e": 3896, "s": 3874, "text": "Now, we solve U X = Z" }, { "code": null, "e": 3921, "s": 3898, "text": "Therefore, we get , " }, { "code": null, "e": 4014, "s": 3921, "text": "Thus, the solution to the given system of linear equations is , , and hence the matrix X = " }, { "code": null, "e": 4062, "s": 4014, "text": " Exercise:In the LU decomposition of the matrix" }, { "code": null, "e": 4080, "s": 4062, "text": "| 2 2 |\n| 4 9 |" }, { "code": null, "e": 4285, "s": 4080, "text": ", if the diagonal elements of U are both 1, then the lower diagonal entry l22 of L is (GATE CS 2015)(A) 4(B) 5(C) 6(D) 7For Solution, see https://www.geeksforgeeks.org/gate-gate-cs-2015-set-1-question-28/" }, { "code": null, "e": 4453, "s": 4285, "text": "This article is compiled by Nishant Arora. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4465, "s": 4453, "text": "VaibhavRai3" }, { "code": null, "e": 4472, "s": 4465, "text": "Arrays" }, { "code": null, "e": 4496, "s": 4472, "text": "Engineering Mathematics" }, { "code": null, "e": 4504, "s": 4496, "text": "GATE CS" }, { "code": null, "e": 4517, "s": 4504, "text": "Mathematical" }, { "code": null, "e": 4524, "s": 4517, "text": "Matrix" }, { "code": null, "e": 4531, "s": 4524, "text": "Arrays" }, { "code": null, "e": 4544, "s": 4531, "text": "Mathematical" }, { "code": null, "e": 4551, "s": 4544, "text": "Matrix" }, { "code": null, "e": 4649, "s": 4551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4664, "s": 4649, "text": "Arrays in Java" }, { "code": null, "e": 4710, "s": 4664, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 4778, "s": 4710, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 4822, "s": 4778, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 4854, "s": 4822, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 4876, "s": 4854, "text": "Inequalities in LaTeX" }, { "code": null, "e": 4935, "s": 4876, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 4958, "s": 4935, "text": "Arrow Symbols in LaTeX" } ]
Node.js Streams
08 Oct, 2021 Streams are one of the fundamental concepts of Node.js. Streams are a type of data-handling methods and are used to read or write input into output sequentially. Streams are used to handle reading/writing files or exchanging information in an efficient way. The official Node.js documentation defines streams as “A stream is an abstract interface for working with streaming data in Node.js.” The stream module provides an API for implementing the stream interface. Examples of the stream object in Node.js can be a request to an HTTP server and process.stdout are both stream instances. In short, Streams are objects in Node.js that lets the user read data from a source or write data to a destination in a continuous manner. Accessing Streams: const stream = require('stream'); Note: What makes streams powerful while dealing with large amounts of data is that instead of reading a file into memory all at once, streams actually read chunks of data, processing its content data without keeping it all in memory. Advantages of Streams over other data handling methods: Time Efficient: We don’t have to wait until entire file has been transmitted. We can start processing data as soon as we have it. Memory Efficient: We don’t have to load huge amount of data in memory before we start processing. Types of Streams in Node.js: There are namely four types of streams in Node.js. Writable: We can write data to these streams. Example: fs.createWriteStream().Readable: We can read data from these streams. Example: fs.createReadStream().Duplex: Streams that are both, Writable as well as Readable. Example: net.socket.Transform: Streams that can modify or transform the data as it is written and read. Example: zlib.createDeflate. Writable: We can write data to these streams. Example: fs.createWriteStream(). Readable: We can read data from these streams. Example: fs.createReadStream(). Duplex: Streams that are both, Writable as well as Readable. Example: net.socket. Transform: Streams that can modify or transform the data as it is written and read. Example: zlib.createDeflate. Some Node APIs that uses streams are: net.Socket() process.stdin() process.stdout() process.stderr() fs.createReadStream() fs.createWriteStream() net.connect() http.request() zlib.createGzip() zlib.createGunzip() zlib.createDeflate() zlib.createInflate() Implementing a Readable Stream: We will read the data from inStream and echoing it to the standard output using process.stdout. // Sample JavaScript Code for creating// a Readable Stream// Accessing streamsconst { Readable } = require('stream'); // Reading the data const inStream = new Readable({ read() { }}); // Pushing the data to the streaminStream.push('GeeksForGeeks : ');inStream.push( 'A Computer Science portal for Geeks'); // Indicates that no more data is// left in the streaminStream.push(null); // Echoing data to the standard outputinStream.pipe(process.stdout); Output: GeeksForGeeks : A Computer Science portal for Geeks Implementing a Writable Stream: In the outStream, we simply console.log the chunk as a string. We also call the callback function to indicate success without any errors. We will read the data from inStream and echo it to the standard output using process.stdout. // Sample JavaScript Code for// Writable Stream// Accessing Streamsconst { Writable } = require('stream'); // Whatever is passed in standard // input is out streamed here.const outStream = new Writable({ // The Write function takes three // arguments // Chunk is for Buffer // Encoding is used in case we want // to configure the stream differently // In this sample code, Encoding is ignored // callback is used to indicate // successful execution write(chunk, encoding, callback) { console.log(chunk.toString()); callback(); } }); // Echo the data to the standard outputprocess.stdin.pipe(outStream); Output: Hello Geeks Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 286, "s": 28, "text": "Streams are one of the fundamental concepts of Node.js. Streams are a type of data-handling methods and are used to read or write input into output sequentially. Streams are used to handle reading/writing files or exchanging information in an efficient way." }, { "code": null, "e": 754, "s": 286, "text": "The official Node.js documentation defines streams as “A stream is an abstract interface for working with streaming data in Node.js.” The stream module provides an API for implementing the stream interface. Examples of the stream object in Node.js can be a request to an HTTP server and process.stdout are both stream instances. In short, Streams are objects in Node.js that lets the user read data from a source or write data to a destination in a continuous manner." }, { "code": null, "e": 773, "s": 754, "text": "Accessing Streams:" }, { "code": null, "e": 807, "s": 773, "text": "const stream = require('stream');" }, { "code": null, "e": 1041, "s": 807, "text": "Note: What makes streams powerful while dealing with large amounts of data is that instead of reading a file into memory all at once, streams actually read chunks of data, processing its content data without keeping it all in memory." }, { "code": null, "e": 1097, "s": 1041, "text": "Advantages of Streams over other data handling methods:" }, { "code": null, "e": 1227, "s": 1097, "text": "Time Efficient: We don’t have to wait until entire file has been transmitted. We can start processing data as soon as we have it." }, { "code": null, "e": 1325, "s": 1227, "text": "Memory Efficient: We don’t have to load huge amount of data in memory before we start processing." }, { "code": null, "e": 1405, "s": 1325, "text": "Types of Streams in Node.js: There are namely four types of streams in Node.js." }, { "code": null, "e": 1755, "s": 1405, "text": "Writable: We can write data to these streams. Example: fs.createWriteStream().Readable: We can read data from these streams. Example: fs.createReadStream().Duplex: Streams that are both, Writable as well as Readable. Example: net.socket.Transform: Streams that can modify or transform the data as it is written and read. Example: zlib.createDeflate." }, { "code": null, "e": 1834, "s": 1755, "text": "Writable: We can write data to these streams. Example: fs.createWriteStream()." }, { "code": null, "e": 1913, "s": 1834, "text": "Readable: We can read data from these streams. Example: fs.createReadStream()." }, { "code": null, "e": 1995, "s": 1913, "text": "Duplex: Streams that are both, Writable as well as Readable. Example: net.socket." }, { "code": null, "e": 2108, "s": 1995, "text": "Transform: Streams that can modify or transform the data as it is written and read. Example: zlib.createDeflate." }, { "code": null, "e": 2146, "s": 2108, "text": "Some Node APIs that uses streams are:" }, { "code": null, "e": 2159, "s": 2146, "text": "net.Socket()" }, { "code": null, "e": 2175, "s": 2159, "text": "process.stdin()" }, { "code": null, "e": 2192, "s": 2175, "text": "process.stdout()" }, { "code": null, "e": 2209, "s": 2192, "text": "process.stderr()" }, { "code": null, "e": 2231, "s": 2209, "text": "fs.createReadStream()" }, { "code": null, "e": 2254, "s": 2231, "text": "fs.createWriteStream()" }, { "code": null, "e": 2268, "s": 2254, "text": "net.connect()" }, { "code": null, "e": 2283, "s": 2268, "text": "http.request()" }, { "code": null, "e": 2301, "s": 2283, "text": "zlib.createGzip()" }, { "code": null, "e": 2321, "s": 2301, "text": "zlib.createGunzip()" }, { "code": null, "e": 2342, "s": 2321, "text": "zlib.createDeflate()" }, { "code": null, "e": 2363, "s": 2342, "text": "zlib.createInflate()" }, { "code": null, "e": 2491, "s": 2363, "text": "Implementing a Readable Stream: We will read the data from inStream and echoing it to the standard output using process.stdout." }, { "code": "// Sample JavaScript Code for creating// a Readable Stream// Accessing streamsconst { Readable } = require('stream'); // Reading the data const inStream = new Readable({ read() { }}); // Pushing the data to the streaminStream.push('GeeksForGeeks : ');inStream.push( 'A Computer Science portal for Geeks'); // Indicates that no more data is// left in the streaminStream.push(null); // Echoing data to the standard outputinStream.pipe(process.stdout);", "e": 2951, "s": 2491, "text": null }, { "code": null, "e": 2959, "s": 2951, "text": "Output:" }, { "code": null, "e": 3012, "s": 2959, "text": "GeeksForGeeks : A Computer Science portal for Geeks " }, { "code": null, "e": 3275, "s": 3012, "text": "Implementing a Writable Stream: In the outStream, we simply console.log the chunk as a string. We also call the callback function to indicate success without any errors. We will read the data from inStream and echo it to the standard output using process.stdout." }, { "code": "// Sample JavaScript Code for// Writable Stream// Accessing Streamsconst { Writable } = require('stream'); // Whatever is passed in standard // input is out streamed here.const outStream = new Writable({ // The Write function takes three // arguments // Chunk is for Buffer // Encoding is used in case we want // to configure the stream differently // In this sample code, Encoding is ignored // callback is used to indicate // successful execution write(chunk, encoding, callback) { console.log(chunk.toString()); callback(); } }); // Echo the data to the standard outputprocess.stdin.pipe(outStream);", "e": 3930, "s": 3275, "text": null }, { "code": null, "e": 3938, "s": 3930, "text": "Output:" }, { "code": null, "e": 3950, "s": 3938, "text": "Hello Geeks" }, { "code": null, "e": 3957, "s": 3950, "text": "Picked" }, { "code": null, "e": 3965, "s": 3957, "text": "Node.js" }, { "code": null, "e": 3982, "s": 3965, "text": "Web Technologies" }, { "code": null, "e": 4080, "s": 3982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4128, "s": 4080, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4161, "s": 4128, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 4191, "s": 4161, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 4211, "s": 4191, "text": "How to update NPM ?" }, { "code": null, "e": 4265, "s": 4211, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 4327, "s": 4265, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4388, "s": 4327, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4438, "s": 4388, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4481, "s": 4438, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | OCR on All the Images present in a Folder Simultaneously
11 Nov, 2019 If you have a folder full of images that has some text which needs to be extracted into a separate folder with the corresponding image file name or in a single file, then this is the perfect code you are looking for. This article not only gives you the basis of OCR (Optical Character Recognition) but also helps you to create output.txt file for every image inside the main folder and save it in some predetermined direction. Libraries Needed – pip3 install pillow pip3 install os-sys You will also need the tesseract-oct and pytesseract library. The tesseract-ocr can be downloaded and installed from here and the pytesseract can be installed using pip3 install pytesseract # Python program to extract text from all the images in a folder# storing the text in corresponding files in a different folderfrom PIL import Imageimport pytesseract as ptimport os def main(): # path for the folder for getting the raw images path ="E:\\GeeksforGeeks\\images" # path for the folder for getting the output tempPath ="E:\\GeeksforGeeks\\textFiles" # iterating the images inside the folder for imageName in os.listdir(path): inputPath = os.path.join(path, imageName) img = Image.open(inputPath) # applying ocr using pytesseract for python text = pt.image_to_string(img, lang ="eng") # for removing the .jpg from the imagePath imagePath = imagePath[0:-4] fullTempPath = os.path.join(tempPath, 'time_'+imageName+".txt") print(text) # saving the text for every image in a separate .txt file file1 = open(fullTempPath, "w") file1.write(text) file1.close() if __name__ == '__main__': main() Input Image : image_sample1 Output : geeksforgeeks geeksforgeeks If you want to store all the text from the images in a single output file then the code will be a little different. The main difference is that the mode of the file in which we will be writing will change to “+a” to append the text and create the output.txt file if it is not present already. # extract text from all the images in a folder# storing the text in a single filefrom PIL import Imageimport pytesseract as ptimport os def main(): # path for the folder for getting the raw images path ="E:\\GeeksforGeeks\\images" # link to the file in which output needs to be kept fullTempPath ="E:\\GeeksforGeeks\\output\\outputFile.txt" # iterating the images inside the folder for imageName in os.listdir(path): inputPath = os.path.join(path, imageName) img = Image.open(inputPath) # applying ocr using pytesseract for python text = pt.image_to_string(img, lang ="eng") # saving the text for appending it to the output.txt file # a + parameter used for creating the file if not present # and if present then append the text content file1 = open(fullTempPath, "a+") # providing the name of the image file1.write(imageName+"\n") # providing the content in the image file1.write(text+"\n") file1.close() # for printing the output file file2 = open(fullTempPath, 'r') print(file2.read()) file2.close() if __name__ == '__main__': main() Input Image : image_sample1 image_sample2 Output: It gave an output of the single file created after extracting all the information from the image inside the folder. The format of the file goes like this – Name of the image Content of the image Name of the next image and so on ..... Image-Processing Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Nov, 2019" }, { "code": null, "e": 269, "s": 52, "text": "If you have a folder full of images that has some text which needs to be extracted into a separate folder with the corresponding image file name or in a single file, then this is the perfect code you are looking for." }, { "code": null, "e": 479, "s": 269, "text": "This article not only gives you the basis of OCR (Optical Character Recognition) but also helps you to create output.txt file for every image inside the main folder and save it in some predetermined direction." }, { "code": null, "e": 498, "s": 479, "text": "Libraries Needed –" }, { "code": null, "e": 538, "s": 498, "text": "pip3 install pillow\npip3 install os-sys" }, { "code": null, "e": 728, "s": 538, "text": "You will also need the tesseract-oct and pytesseract library. The tesseract-ocr can be downloaded and installed from here and the pytesseract can be installed using pip3 install pytesseract" }, { "code": "# Python program to extract text from all the images in a folder# storing the text in corresponding files in a different folderfrom PIL import Imageimport pytesseract as ptimport os def main(): # path for the folder for getting the raw images path =\"E:\\\\GeeksforGeeks\\\\images\" # path for the folder for getting the output tempPath =\"E:\\\\GeeksforGeeks\\\\textFiles\" # iterating the images inside the folder for imageName in os.listdir(path): inputPath = os.path.join(path, imageName) img = Image.open(inputPath) # applying ocr using pytesseract for python text = pt.image_to_string(img, lang =\"eng\") # for removing the .jpg from the imagePath imagePath = imagePath[0:-4] fullTempPath = os.path.join(tempPath, 'time_'+imageName+\".txt\") print(text) # saving the text for every image in a separate .txt file file1 = open(fullTempPath, \"w\") file1.write(text) file1.close() if __name__ == '__main__': main()", "e": 1767, "s": 728, "text": null }, { "code": null, "e": 1781, "s": 1767, "text": "Input Image :" }, { "code": null, "e": 1795, "s": 1781, "text": "image_sample1" }, { "code": null, "e": 1804, "s": 1795, "text": "Output :" }, { "code": null, "e": 1833, "s": 1804, "text": "geeksforgeeks\ngeeksforgeeks\n" }, { "code": null, "e": 2126, "s": 1833, "text": "If you want to store all the text from the images in a single output file then the code will be a little different. The main difference is that the mode of the file in which we will be writing will change to “+a” to append the text and create the output.txt file if it is not present already." }, { "code": "# extract text from all the images in a folder# storing the text in a single filefrom PIL import Imageimport pytesseract as ptimport os def main(): # path for the folder for getting the raw images path =\"E:\\\\GeeksforGeeks\\\\images\" # link to the file in which output needs to be kept fullTempPath =\"E:\\\\GeeksforGeeks\\\\output\\\\outputFile.txt\" # iterating the images inside the folder for imageName in os.listdir(path): inputPath = os.path.join(path, imageName) img = Image.open(inputPath) # applying ocr using pytesseract for python text = pt.image_to_string(img, lang =\"eng\") # saving the text for appending it to the output.txt file # a + parameter used for creating the file if not present # and if present then append the text content file1 = open(fullTempPath, \"a+\") # providing the name of the image file1.write(imageName+\"\\n\") # providing the content in the image file1.write(text+\"\\n\") file1.close() # for printing the output file file2 = open(fullTempPath, 'r') print(file2.read()) file2.close() if __name__ == '__main__': main()", "e": 3319, "s": 2126, "text": null }, { "code": null, "e": 3333, "s": 3319, "text": "Input Image :" }, { "code": null, "e": 3347, "s": 3333, "text": "image_sample1" }, { "code": null, "e": 3361, "s": 3347, "text": "image_sample2" }, { "code": null, "e": 3369, "s": 3361, "text": "Output:" }, { "code": null, "e": 3525, "s": 3369, "text": "It gave an output of the single file created after extracting all the information from the image inside the folder. The format of the file goes like this –" }, { "code": null, "e": 3603, "s": 3525, "text": "Name of the image\nContent of the image\nName of the next image and so on ....." }, { "code": null, "e": 3620, "s": 3603, "text": "Image-Processing" }, { "code": null, "e": 3631, "s": 3620, "text": "Python-pil" }, { "code": null, "e": 3638, "s": 3631, "text": "Python" }, { "code": null, "e": 3736, "s": 3638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3754, "s": 3736, "text": "Python Dictionary" }, { "code": null, "e": 3796, "s": 3754, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3818, "s": 3796, "text": "Enumerate() in Python" }, { "code": null, "e": 3853, "s": 3818, "text": "Read a file line by line in Python" }, { "code": null, "e": 3879, "s": 3853, "text": "Python String | replace()" }, { "code": null, "e": 3911, "s": 3879, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3940, "s": 3911, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3967, "s": 3940, "text": "Python Classes and Objects" }, { "code": null, "e": 3997, "s": 3967, "text": "Iterate over a list in Python" } ]
How to use javascript function in check box?
08 Feb, 2022 Checkboxes are used for instances where a user may wish to select multiple options, such as in the instance of a “check all that apply” question, in forms. HTML Checkboxes Selected. A checkbox element can be placed onto a web page in a pre-checked fashion by setting the checked attribute with a “yes” value. Typically shaped as square. Allow the user to select options with a single click. Options share a single name. Checkbox allow you to select more than one options per groupHTML Code: HTML document by employing the dedicated HTML tag that wraps around JavaScript code. The tag can be placed in the section of your HTML, in the section, or after the close tag, depending on when you want the JavaScript to load. HTML Code: HTML document by employing the dedicated HTML tag that wraps around JavaScript code. The tag can be placed in the section of your HTML, in the section, or after the close tag, depending on when you want the JavaScript to load. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <form> <fieldset> <legend> <bold>Checkbox</bold> </legend> <div class="form-group"> <label for="yesgraduated"> Are you graduated? </label> <input id="yesgraduated" name="yesgraduated" type="checkbox" value="yes" onchange="graduatedFunction()" /> <br /> </div> <div id="graduated" class="form-group"> <label for="degreename"> Degree Name: </label> <input type="text" class="form-control" name="degreename" id="degreename" /> <br /> </div> <button type="button" class="btn btn-primary" value="Verify"> Submit </button> </fieldset> </form> </div> <div class="col-md-3"></div> </div> </div> </body></html> JavaScript Code: Now, in the javaScript code we’re trying to give the option of including the degree in the form. The user need to tell if he/she is graduated or not. So when we click on this checkbox, a new input field opens up. So if someone clicks or doesn’t click it, the “graduatedFunction” function will either display the hidden part or display none. javascript <script> function graduatedFunction() { if (document.getElementById("yesgraduated") .checked) { document.getElementById("graduated") .style.display = "inline"; document.getElementById("degreename") .setAttribute("required", true); } else { document.getElementById("degreename") .removeAttribute("required"); document.getElementById("graduated") .style.display = "none"; } }</script> sumitgumber28 HTML-Misc JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Feb, 2022" }, { "code": null, "e": 365, "s": 54, "text": "Checkboxes are used for instances where a user may wish to select multiple options, such as in the instance of a “check all that apply” question, in forms. HTML Checkboxes Selected. A checkbox element can be placed onto a web page in a pre-checked fashion by setting the checked attribute with a “yes” value. " }, { "code": null, "e": 393, "s": 365, "text": "Typically shaped as square." }, { "code": null, "e": 447, "s": 393, "text": "Allow the user to select options with a single click." }, { "code": null, "e": 476, "s": 447, "text": "Options share a single name." }, { "code": null, "e": 776, "s": 476, "text": "Checkbox allow you to select more than one options per groupHTML Code: HTML document by employing the dedicated HTML tag that wraps around JavaScript code. The tag can be placed in the section of your HTML, in the section, or after the close tag, depending on when you want the JavaScript to load. " }, { "code": null, "e": 1016, "s": 776, "text": "HTML Code: HTML document by employing the dedicated HTML tag that wraps around JavaScript code. The tag can be placed in the section of your HTML, in the section, or after the close tag, depending on when you want the JavaScript to load. " }, { "code": null, "e": 1021, "s": 1016, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" /> </head> <body> <div class=\"container\"> <div class=\"row\"> <div class=\"col-md-3\"></div> <div class=\"col-md-6\"> <form> <fieldset> <legend> <bold>Checkbox</bold> </legend> <div class=\"form-group\"> <label for=\"yesgraduated\"> Are you graduated? </label> <input id=\"yesgraduated\" name=\"yesgraduated\" type=\"checkbox\" value=\"yes\" onchange=\"graduatedFunction()\" /> <br /> </div> <div id=\"graduated\" class=\"form-group\"> <label for=\"degreename\"> Degree Name: </label> <input type=\"text\" class=\"form-control\" name=\"degreename\" id=\"degreename\" /> <br /> </div> <button type=\"button\" class=\"btn btn-primary\" value=\"Verify\"> Submit </button> </fieldset> </form> </div> <div class=\"col-md-3\"></div> </div> </div> </body></html> ", "e": 3117, "s": 1021, "text": null }, { "code": null, "e": 3477, "s": 3117, "text": "JavaScript Code: Now, in the javaScript code we’re trying to give the option of including the degree in the form. The user need to tell if he/she is graduated or not. So when we click on this checkbox, a new input field opens up. So if someone clicks or doesn’t click it, the “graduatedFunction” function will either display the hidden part or display none. " }, { "code": null, "e": 3488, "s": 3477, "text": "javascript" }, { "code": "<script> function graduatedFunction() { if (document.getElementById(\"yesgraduated\") .checked) { document.getElementById(\"graduated\") .style.display = \"inline\"; document.getElementById(\"degreename\") .setAttribute(\"required\", true); } else { document.getElementById(\"degreename\") .removeAttribute(\"required\"); document.getElementById(\"graduated\") .style.display = \"none\"; } }</script>", "e": 4000, "s": 3488, "text": null }, { "code": null, "e": 4014, "s": 4000, "text": "sumitgumber28" }, { "code": null, "e": 4024, "s": 4014, "text": "HTML-Misc" }, { "code": null, "e": 4040, "s": 4024, "text": "JavaScript-Misc" }, { "code": null, "e": 4051, "s": 4040, "text": "JavaScript" }, { "code": null, "e": 4068, "s": 4051, "text": "Web Technologies" }, { "code": null, "e": 4095, "s": 4068, "text": "Web technologies Questions" }, { "code": null, "e": 4193, "s": 4095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4254, "s": 4193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4294, "s": 4254, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4335, "s": 4294, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4377, "s": 4335, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4399, "s": 4377, "text": "JavaScript | Promises" }, { "code": null, "e": 4461, "s": 4399, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4494, "s": 4461, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4555, "s": 4494, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4605, "s": 4555, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Debugging ReactJS applications
While building a real-world application, the most important thing that a developer should know is how to properly debug the React application. There are many ways to debug our React application and some of the proven methods are explained below − Tools like ESLint help to write better and clean codes, as it follows proper guidelines which prevent errors at the time of developing the codes. This tool comes very handy while debugging ReactJS applications, as it allows to navigate through the Component Tree and allows to take a look at the state or the props or other data being passed to a component on the fly. Note: For the production-ready code, it obfuscates the name of the components to enhance the security by default, but you can still view it by setting the displayName property to the component you want to have a look at. It is the most powerful feature while debugging a React application. We can log any state, props or data at any point in the component and it will log that data in the console. You can add console.log() statement anywhere in the component and JSX, except for the objects and arrays. App.jsx import React from 'react'; import Name from './Name.js'; const App = () => ( <div> <Name name="Rahul Bansal" /> </div> ); export default App; Name.jsx import React from 'react'; const Name = (props) => { return ( <div> {console.log('Props: ', props)} Name: {props.name} </div> ); }; export default Name; This will produce the following output −
[ { "code": null, "e": 1434, "s": 1187, "text": "While building a real-world application, the most important thing that a developer should know is how to properly debug the React application. There are many ways to debug our React application and some of the proven methods are explained below −" }, { "code": null, "e": 1580, "s": 1434, "text": "Tools like ESLint help to write better and clean codes, as it follows proper guidelines which prevent errors at the time of developing the codes." }, { "code": null, "e": 1803, "s": 1580, "text": "This tool comes very handy while debugging ReactJS applications, as it allows to navigate through the Component Tree and allows to take a look at the state or the props or other data being passed to a component on the fly." }, { "code": null, "e": 2024, "s": 1803, "text": "Note: For the production-ready code, it obfuscates the name of the components to enhance the security by default, but you can still view it by setting the displayName property to the component you want to have a look at." }, { "code": null, "e": 2307, "s": 2024, "text": "It is the most powerful feature while debugging a React application. We can log any state, props or data at any point in the component and it will log that data in the console. You can add console.log() statement anywhere in the component and JSX, except for the objects and arrays." }, { "code": null, "e": 2315, "s": 2307, "text": "App.jsx" }, { "code": null, "e": 2471, "s": 2315, "text": "import React from 'react';\n\nimport Name from './Name.js';\n\nconst App = () => (\n <div>\n <Name name=\"Rahul Bansal\" />\n </div>\n);\nexport default App;" }, { "code": null, "e": 2480, "s": 2471, "text": "Name.jsx" }, { "code": null, "e": 2664, "s": 2480, "text": "import React from 'react';\n\nconst Name = (props) => {\n return (\n <div>\n {console.log('Props: ', props)}\n Name: {props.name}\n </div>\n );\n};\nexport default Name;" }, { "code": null, "e": 2705, "s": 2664, "text": "This will produce the following output −" } ]
Creating a chessboard pattern with JavaScript and DOM
10 Sep, 2021 A chessboard pattern can be created very easily using JavaScript and the concept of document object module (DOM). Using this method, you can create a chessboard with any number of rows and columns as you desire by just tweaking few parameters. Also, the lines of code written using this method will also be way lesser than creating the same using pure HTML and CSS especially when the number of rows and columns is very large. Approach: Create a nested for loop. Let us call the outer loop “i” and the inner loop “j”. The outer loop will be used to create rows and the inner loop will be used to create cells in each column. By doing so a N*M cells will be created where N is the number of rows and M is the number of columns. The combination of i and j value in the inner loop can be used to distinguish between each cell so formed. At the end of the loop, we will have a table created. Also, we need to color the cells with an appropriate color. If the summation of i and j yields an even number then the cell has to be colored white else it has to be colored black. This will create cells of alternative colors of white and black as seen in a chessboard. Creation of table and table cells can use done using DOM and coloration of cells can be done using CSS. Below is the implementation of the above approach. Filename: index.html HTML <!DOCTYPE html><html> <head> <title>Chess board</title> <style> body { text-align: center; } .cell { height: 30px; width: 30px; border: 1.5px solid grey; border-style: inset; } .blackcell { background-color: black; } .whitecell { background-color: white; } </style></head> <body> <span style="color:green; font-size:30px;"> GeeksforGeeks </span> <br><br> <script type="text/javascript"> // Create a center tag to center all the elements var center = document.createElement('center'); // Create a table element var ChessTable = document.createElement('table'); for (var i = 0; i < 8; i++) { // Create a row var tr = document.createElement('tr'); for (var j = 0; j < 8; j++) { // Create a cell var td = document.createElement('td'); // If the sum of cell coordinates is even // then color the cell white if ((i + j) % 2 == 0) { // Create a class attribute for all white cells td.setAttribute('class', 'cell whitecell'); tr.appendChild(td); } // If the sum of cell coordinates is odd then // color the cell black else { // Create a class attribute for all black cells td.setAttribute('class', 'cell blackcell'); // Append the cell to its row tr.appendChild(td); } } // Append the row ChessTable.appendChild(tr); } center.appendChild(ChessTable); // Modifying table attribute properties ChessTable.setAttribute('cellspacing', '0'); ChessTable.setAttribute('width', '270px'); document.body.appendChild(center); </script></body> </html> Output: Output Code explanation: An 8 x 8 chessboard will be created for the above code. However, just by modifying the termination condition of i and j, we will be able to create a N x M chessboard with ease. Using Javascript DOM a table element is created initially using createElement(). we know that the i loop is used to create rows, hence a row element will be created during each iteration. similarly, the j loop is responsible for creating cells. Hence table cells are created during each iteration. As discussed before the color of each cell can be decided by the summation of i and j values. If the sum is even then the cell has to be colored white and if it is odd then the cell has to be colored black. This is done by creating and assigning an appropriate class attribute to each cell using setAttribute() and assigning the right color, size, and other properties as you wish using CSS. At the end, all the elements are appended inside the body of the HTML document. Hence, we are able to create a simple chessboard pattern using javascript and DOM very easily. surinderdawra388 CSS-Properties HTML-DOM HTML-Questions JavaScript-Questions CSS HTML JavaScript 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 Form validation using jQuery Design a web page using HTML and CSS 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 ? HTTP headers | Content-Type
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Sep, 2021" }, { "code": null, "e": 479, "s": 52, "text": "A chessboard pattern can be created very easily using JavaScript and the concept of document object module (DOM). Using this method, you can create a chessboard with any number of rows and columns as you desire by just tweaking few parameters. Also, the lines of code written using this method will also be way lesser than creating the same using pure HTML and CSS especially when the number of rows and columns is very large." }, { "code": null, "e": 1314, "s": 479, "text": "Approach: Create a nested for loop. Let us call the outer loop “i” and the inner loop “j”. The outer loop will be used to create rows and the inner loop will be used to create cells in each column. By doing so a N*M cells will be created where N is the number of rows and M is the number of columns. The combination of i and j value in the inner loop can be used to distinguish between each cell so formed. At the end of the loop, we will have a table created. Also, we need to color the cells with an appropriate color. If the summation of i and j yields an even number then the cell has to be colored white else it has to be colored black. This will create cells of alternative colors of white and black as seen in a chessboard. Creation of table and table cells can use done using DOM and coloration of cells can be done using CSS." }, { "code": null, "e": 1365, "s": 1314, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1386, "s": 1365, "text": "Filename: index.html" }, { "code": null, "e": 1391, "s": 1386, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Chess board</title> <style> body { text-align: center; } .cell { height: 30px; width: 30px; border: 1.5px solid grey; border-style: inset; } .blackcell { background-color: black; } .whitecell { background-color: white; } </style></head> <body> <span style=\"color:green; font-size:30px;\"> GeeksforGeeks </span> <br><br> <script type=\"text/javascript\"> // Create a center tag to center all the elements var center = document.createElement('center'); // Create a table element var ChessTable = document.createElement('table'); for (var i = 0; i < 8; i++) { // Create a row var tr = document.createElement('tr'); for (var j = 0; j < 8; j++) { // Create a cell var td = document.createElement('td'); // If the sum of cell coordinates is even // then color the cell white if ((i + j) % 2 == 0) { // Create a class attribute for all white cells td.setAttribute('class', 'cell whitecell'); tr.appendChild(td); } // If the sum of cell coordinates is odd then // color the cell black else { // Create a class attribute for all black cells td.setAttribute('class', 'cell blackcell'); // Append the cell to its row tr.appendChild(td); } } // Append the row ChessTable.appendChild(tr); } center.appendChild(ChessTable); // Modifying table attribute properties ChessTable.setAttribute('cellspacing', '0'); ChessTable.setAttribute('width', '270px'); document.body.appendChild(center); </script></body> </html>", "e": 3427, "s": 1391, "text": null }, { "code": null, "e": 3435, "s": 3427, "text": "Output:" }, { "code": null, "e": 3442, "s": 3435, "text": "Output" }, { "code": null, "e": 4503, "s": 3442, "text": "Code explanation: An 8 x 8 chessboard will be created for the above code. However, just by modifying the termination condition of i and j, we will be able to create a N x M chessboard with ease. Using Javascript DOM a table element is created initially using createElement(). we know that the i loop is used to create rows, hence a row element will be created during each iteration. similarly, the j loop is responsible for creating cells. Hence table cells are created during each iteration. As discussed before the color of each cell can be decided by the summation of i and j values. If the sum is even then the cell has to be colored white and if it is odd then the cell has to be colored black. This is done by creating and assigning an appropriate class attribute to each cell using setAttribute() and assigning the right color, size, and other properties as you wish using CSS. At the end, all the elements are appended inside the body of the HTML document. Hence, we are able to create a simple chessboard pattern using javascript and DOM very easily. " }, { "code": null, "e": 4520, "s": 4503, "text": "surinderdawra388" }, { "code": null, "e": 4535, "s": 4520, "text": "CSS-Properties" }, { "code": null, "e": 4544, "s": 4535, "text": "HTML-DOM" }, { "code": null, "e": 4559, "s": 4544, "text": "HTML-Questions" }, { "code": null, "e": 4580, "s": 4559, "text": "JavaScript-Questions" }, { "code": null, "e": 4584, "s": 4580, "text": "CSS" }, { "code": null, "e": 4589, "s": 4584, "text": "HTML" }, { "code": null, "e": 4600, "s": 4589, "text": "JavaScript" }, { "code": null, "e": 4617, "s": 4600, "text": "Web Technologies" }, { "code": null, "e": 4622, "s": 4617, "text": "HTML" }, { "code": null, "e": 4720, "s": 4622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4759, "s": 4720, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4798, "s": 4759, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4837, "s": 4798, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4866, "s": 4837, "text": "Form validation using jQuery" }, { "code": null, "e": 4903, "s": 4866, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4927, "s": 4903, "text": "REST API (Introduction)" }, { "code": null, "e": 4980, "s": 4927, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5040, "s": 4980, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5101, "s": 5040, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Scala - for Loops
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. There are various forms of for loop in Scala which are described below − The simplest syntax of for loop with ranges in Scala is − for( var x <- Range ){ statement(s); } Here, the Range could be a range of numbers and that is represented as i to j or sometime like i until j. The left-arrow ← operator is called a generator, so named because it's generating individual values from a range. Try the following example program to understand loop control statements (for statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { var a = 0; // for loop execution with a range for( a <- 1 to 10){ println( "Value of a: " + a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 1 value of a: 2 value of a: 3 value of a: 4 value of a: 5 value of a: 6 value of a: 7 value of a: 8 value of a: 9 value of a: 10 Try the following example program to understand loop control statements (for statement) to print loop with the range i until j in Scala Programming Language. object Demo { def main(args: Array[String]) { var a = 0; // for loop execution with a range for( a <- 1 until 10){ println( "Value of a: " + a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 1 value of a: 2 value of a: 3 value of a: 4 value of a: 5 value of a: 6 value of a: 7 value of a: 8 value of a: 9 You can use multiple ranges separated by semicolon (;) within for loop and in that case loop will iterate through all the possible computations of the given ranges. Following is an example of using just two ranges, you can use more than two ranges as well. object Demo { def main(args: Array[String]) { var a = 0; var b = 0; // for loop execution with a range for( a <- 1 to 3; b <- 1 to 3){ println( "Value of a: " + a ); println( "Value of b: " + b ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Value of a: 1 Value of b: 1 Value of a: 1 Value of b: 2 Value of a: 1 Value of b: 3 Value of a: 2 Value of b: 1 Value of a: 2 Value of b: 2 Value of a: 2 Value of b: 3 Value of a: 3 Value of b: 1 Value of a: 3 Value of b: 2 Value of a: 3 Value of b: 3 The following syntax for loop with collections. for( var x <- List ){ statement(s); } Here, the List variable is a collection type having a list of elements and for loop iterate through all the elements returning one element in x variable at a time. Try the following example program to understand loop with a collection of numbers. Here we created this collection using List(). We will study collections in a separate chapter. Loop control statements (for statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { var a = 0; val numList = List(1,2,3,4,5,6); // for loop execution with a collection for( a <- numList ){ println( "Value of a: " + a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 1 value of a: 2 value of a: 3 value of a: 4 value of a: 5 value of a: 6 Scala's for loop allows to filter out some elements using one or more if statement(s). Following is the syntax of for loop along with filters. To add more than one filter to a 'for' expression, separate the filters with semicolons(;). for( var x <- List if condition1; if condition2... ){ statement(s); } Try the following example program to understand loop with a filter. object Demo { def main(args: Array[String]) { var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for loop execution with multiple filters for( a <- numList if a != 3; if a < 8 ){ println( "Value of a: " + a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 1 value of a: 2 value of a: 4 value of a: 5 value of a: 6 value of a: 7 You can store return values from a "for" loop in a variable or can return through a function. To do so, you prefix the body of the 'for' expression by the keyword yield. The following is the syntax. var retVal = for{ var x <- List if condition1; if condition2... } yield x Note − the curly braces have been used to keep the variables and conditions and retVal is a variable where all the values of x will be stored in the form of collection. Try the following example program to understand loop with yield. object Demo { def main(args: Array[String]) { var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for loop execution with a yield var retVal = for{ a <- numList if a != 3; if a < 8 }yield a // Now print returned values using another loop. for( a <- retVal){ println( "Value of a: " + a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 1 value of a: 2 value of a: 4 value of a: 5 value of a: 6 value of a: 7
[ { "code": null, "e": 2344, "s": 2132, "text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. There are various forms of for loop in Scala which are described below −" }, { "code": null, "e": 2402, "s": 2344, "text": "The simplest syntax of for loop with ranges in Scala is −" }, { "code": null, "e": 2445, "s": 2402, "text": "for( var x <- Range ){\n statement(s);\n}\n" }, { "code": null, "e": 2665, "s": 2445, "text": "Here, the Range could be a range of numbers and that is represented as i to j or sometime like i until j. The left-arrow ← operator is called a generator, so named because it's generating individual values from a range." }, { "code": null, "e": 2784, "s": 2665, "text": "Try the following example program to understand loop control statements (for statement) in Scala Programming Language." }, { "code": null, "e": 2979, "s": 2784, "text": "object Demo {\n def main(args: Array[String]) {\n var a = 0;\n \n // for loop execution with a range\n for( a <- 1 to 10){\n println( \"Value of a: \" + a );\n }\n }\n}" }, { "code": null, "e": 3086, "s": 2979, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3120, "s": 3086, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3262, "s": 3120, "text": "value of a: 1\nvalue of a: 2\nvalue of a: 3\nvalue of a: 4\nvalue of a: 5\nvalue of a: 6\nvalue of a: 7\nvalue of a: 8\nvalue of a: 9\nvalue of a: 10\n" }, { "code": null, "e": 3420, "s": 3262, "text": "Try the following example program to understand loop control statements (for statement) to print loop with the range i until j in Scala Programming Language." }, { "code": null, "e": 3618, "s": 3420, "text": "object Demo {\n def main(args: Array[String]) {\n var a = 0;\n \n // for loop execution with a range\n for( a <- 1 until 10){\n println( \"Value of a: \" + a );\n }\n }\n}" }, { "code": null, "e": 3725, "s": 3618, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3759, "s": 3725, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3886, "s": 3759, "text": "value of a: 1\nvalue of a: 2\nvalue of a: 3\nvalue of a: 4\nvalue of a: 5\nvalue of a: 6\nvalue of a: 7\nvalue of a: 8\nvalue of a: 9\n" }, { "code": null, "e": 4143, "s": 3886, "text": "You can use multiple ranges separated by semicolon (;) within for loop and in that case loop will iterate through all the possible computations of the given ranges. Following is an example of using just two ranges, you can use more than two ranges as well." }, { "code": null, "e": 4407, "s": 4143, "text": "object Demo {\n def main(args: Array[String]) {\n var a = 0;\n var b = 0;\n \n // for loop execution with a range\n for( a <- 1 to 3; b <- 1 to 3){\n println( \"Value of a: \" + a );\n println( \"Value of b: \" + b );\n }\n }\n}" }, { "code": null, "e": 4514, "s": 4407, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4548, "s": 4514, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4801, "s": 4548, "text": "Value of a: 1\nValue of b: 1\nValue of a: 1\nValue of b: 2\nValue of a: 1\nValue of b: 3\nValue of a: 2\nValue of b: 1\nValue of a: 2\nValue of b: 2\nValue of a: 2\nValue of b: 3\nValue of a: 3\nValue of b: 1\nValue of a: 3\nValue of b: 2\nValue of a: 3\nValue of b: 3\n" }, { "code": null, "e": 4849, "s": 4801, "text": "The following syntax for loop with collections." }, { "code": null, "e": 4891, "s": 4849, "text": "for( var x <- List ){\n statement(s);\n}\n" }, { "code": null, "e": 5055, "s": 4891, "text": "Here, the List variable is a collection type having a list of elements and for loop iterate through all the elements returning one element in x variable at a time." }, { "code": null, "e": 5304, "s": 5055, "text": "Try the following example program to understand loop with a collection of numbers. Here we created this collection using List(). We will study collections in a separate chapter. Loop control statements (for statement) in Scala Programming Language." }, { "code": null, "e": 5538, "s": 5304, "text": "object Demo {\n def main(args: Array[String]) {\n var a = 0;\n val numList = List(1,2,3,4,5,6);\n\n // for loop execution with a collection\n for( a <- numList ){\n println( \"Value of a: \" + a );\n }\n }\n}" }, { "code": null, "e": 5645, "s": 5538, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 5679, "s": 5645, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 5764, "s": 5679, "text": "value of a: 1\nvalue of a: 2\nvalue of a: 3\nvalue of a: 4\nvalue of a: 5\nvalue of a: 6\n" }, { "code": null, "e": 5999, "s": 5764, "text": "Scala's for loop allows to filter out some elements using one or more if statement(s). Following is the syntax of for loop along with filters. To add more than one filter to a 'for' expression, separate the filters with semicolons(;)." }, { "code": null, "e": 6082, "s": 5999, "text": "for( var x <- List\n if condition1; if condition2...\n ){\n statement(s);\n}\n" }, { "code": null, "e": 6150, "s": 6082, "text": "Try the following example program to understand loop with a filter." }, { "code": null, "e": 6428, "s": 6150, "text": "object Demo {\n def main(args: Array[String]) {\n var a = 0;\n val numList = List(1,2,3,4,5,6,7,8,9,10);\n\n // for loop execution with multiple filters\n for( a <- numList\n if a != 3; if a < 8 ){\n println( \"Value of a: \" + a );\n }\n }\n}" }, { "code": null, "e": 6535, "s": 6428, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 6569, "s": 6535, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 6654, "s": 6569, "text": "value of a: 1\nvalue of a: 2\nvalue of a: 4\nvalue of a: 5\nvalue of a: 6\nvalue of a: 7\n" }, { "code": null, "e": 6853, "s": 6654, "text": "You can store return values from a \"for\" loop in a variable or can return through a function. To do so, you prefix the body of the 'for' expression by the keyword yield. The following is the syntax." }, { "code": null, "e": 6931, "s": 6853, "text": "var retVal = for{ var x <- List\n if condition1; if condition2...\n}\nyield x\n" }, { "code": null, "e": 7100, "s": 6931, "text": "Note − the curly braces have been used to keep the variables and conditions and retVal is a variable where all the values of x will be stored in the form of collection." }, { "code": null, "e": 7165, "s": 7100, "text": "Try the following example program to understand loop with yield." }, { "code": null, "e": 7523, "s": 7165, "text": "object Demo {\n def main(args: Array[String]) {\n var a = 0;\n val numList = List(1,2,3,4,5,6,7,8,9,10);\n\n // for loop execution with a yield\n var retVal = for{ a <- numList if a != 3; if a < 8 }yield a\n\n // Now print returned values using another loop.\n for( a <- retVal){\n println( \"Value of a: \" + a );\n }\n }\n}" }, { "code": null, "e": 7630, "s": 7523, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 7664, "s": 7630, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" } ]
Python – Skew-Normal Distribution in Statistics
10 Jan, 2020 scipy.stats.skewnorm() is a skew-normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : skew-normal continuous random variable Code #1 : Creating skew-normal continuous random variable # importing library from scipy.stats import skewnorm numargs = skewnorm .numargs a, b = 4.32, 3.18rv = skewnorm (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D843A9C8 Code #2 : skew-normal continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = skewnorm.rvs(a, b) print ("Random Variates : \n", R) # PDF R = skewnorm.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R) Output : Random Variates : 4.2082825614230845 Probability Distribution : [7.38229165e-05 1.13031801e-04 1.71343310e-04 2.57152477e-04 3.82094976e-04 5.62094062e-04 8.18660285e-04 1.18047149e-03 1.68525001e-03 2.38193677e-03] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735 1.95918367 2. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = skewnorm .pdf(x, 1, 3, 5) y2 = skewnorm .pdf(x, 1, 4, 4) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2020" }, { "code": null, "e": 264, "s": 28, "text": "scipy.stats.skewnorm() is a skew-normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 277, "s": 264, "text": "Parameters :" }, { "code": null, "e": 623, "s": 277, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 672, "s": 623, "text": "Results : skew-normal continuous random variable" }, { "code": null, "e": 730, "s": 672, "text": "Code #1 : Creating skew-normal continuous random variable" }, { "code": "# importing library from scipy.stats import skewnorm numargs = skewnorm .numargs a, b = 4.32, 3.18rv = skewnorm (a, b) print (\"RV : \\n\", rv) ", "e": 881, "s": 730, "text": null }, { "code": null, "e": 890, "s": 881, "text": "Output :" }, { "code": null, "e": 971, "s": 890, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D843A9C8\n" }, { "code": null, "e": 1042, "s": 971, "text": "Code #2 : skew-normal continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = skewnorm.rvs(a, b) print (\"Random Variates : \\n\", R) # PDF R = skewnorm.pdf(a, b, quantile) print (\"\\nProbability Distribution : \\n\", R) ", "e": 1261, "s": 1042, "text": null }, { "code": null, "e": 1270, "s": 1261, "text": "Output :" }, { "code": null, "e": 1494, "s": 1270, "text": "Random Variates : \n 4.2082825614230845\n\nProbability Distribution : \n [7.38229165e-05 1.13031801e-04 1.71343310e-04 2.57152477e-04\n 3.82094976e-04 5.62094062e-04 8.18660285e-04 1.18047149e-03\n 1.68525001e-03 2.38193677e-03]\n" }, { "code": null, "e": 1530, "s": 1494, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 1741, "s": 1530, "text": null }, { "code": null, "e": 1750, "s": 1741, "text": "Output :" }, { "code": null, "e": 2330, "s": 1750, "text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n " }, { "code": null, "e": 2369, "s": 2330, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = skewnorm .pdf(x, 1, 3, 5) y2 = skewnorm .pdf(x, 1, 4, 4) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 2586, "s": 2369, "text": null }, { "code": null, "e": 2595, "s": 2586, "text": "Output :" }, { "code": null, "e": 2624, "s": 2595, "text": "Python scipy-stats-functions" }, { "code": null, "e": 2631, "s": 2624, "text": "Python" }, { "code": null, "e": 2729, "s": 2631, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2761, "s": 2729, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2788, "s": 2761, "text": "Python Classes and Objects" }, { "code": null, "e": 2809, "s": 2788, "text": "Python OOPs Concepts" }, { "code": null, "e": 2832, "s": 2809, "text": "Introduction To PYTHON" }, { "code": null, "e": 2888, "s": 2832, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2919, "s": 2888, "text": "Python | os.path.join() method" }, { "code": null, "e": 2961, "s": 2919, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3003, "s": 2961, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3042, "s": 3003, "text": "Python | Get unique values from a list" } ]
DynamoDB - Environment
The DynamoDB Environment only consists of using your Amazon Web Services account to access the DynamoDB GUI console, however, you can also perform a local install. Navigate to the following website − https://aws.amazon.com/dynamodb/ Click the “Get Started with Amazon DynamoDB” button, or the “Create an AWS Account” button if you do not have an Amazon Web Services account. The simple, guided process will inform you of all the related fees and requirements. After performing all the necessary steps of the process, you will have the access. Simply sign in to the AWS console, and then navigate to the DynamoDB console. Be sure to delete unused or unnecessary material to avoid associated fees. The AWS (Amazon Web Service) provides a version of DynamoDB for local installations. It supports creating applications without the web service or a connection. It also reduces provisioned throughput, data storage, and transfer fees by allowing a local database. This guide assumes a local install. When ready for deployment, you can make a few small adjustments to your application to convert it to AWS use. The install file is a .jar executable. It runs in Linux, Unix, Windows, and any other OS with Java support. Download the file by using one of the following links − Tarball − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.tar.gz Tarball − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.tar.gz Zip archive − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.zip Zip archive − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.zip Note − Other repositories offer the file, but not necessarily the latest version. Use the links above for up-to-date install files. Also, ensure you have Java Runtime Engine (JRE) version 6.x or a newer version. DynamoDB cannot run with older versions. After downloading the appropriate archive, extract its directory (DynamoDBLocal.jar) and place it in the desired location. You can then start DynamoDB by opening a command prompt, navigating to the directory containing DynamoDBLocal.jar, and entering the following command − java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb You can also stop the DynamoDB by closing the command prompt used to start it. You can use a JavaScript shell, a GUI console, and multiple languages to work with DynamoDB. The languages available include Ruby, Java, Python, C#, Erlang, PHP, and Perl. In this tutorial, we use Java and GUI console examples for conceptual and code clarity. Install a Java IDE, the AWS SDK for Java, and setup AWS security credentials for the Java SDK in order to utilize Java. When ready for deployment, you will need to alter your code. The adjustments depend on code language and other factors. The main change merely consists of changing the endpoint from a local point to an AWS region. Other changes require deeper analysis of your application. A local install differs from the web service in many ways including, but not limited to the following key differences − The local install creates tables immediately, but the service takes much longer. The local install creates tables immediately, but the service takes much longer. The local install ignores throughput. The local install ignores throughput. The deletion occurs immediately in a local install. The deletion occurs immediately in a local install. The reads/writes occur quickly in local installs due to the absence of network overhead. The reads/writes occur quickly in local installs due to the absence of network overhead.
[ { "code": null, "e": 2689, "s": 2525, "text": "The DynamoDB Environment only consists of using your Amazon Web Services account to access the DynamoDB GUI console, however, you can also perform a local install." }, { "code": null, "e": 2758, "s": 2689, "text": "Navigate to the following website − https://aws.amazon.com/dynamodb/" }, { "code": null, "e": 2985, "s": 2758, "text": "Click the “Get Started with Amazon DynamoDB” button, or the “Create an AWS Account” button if you do not have an Amazon Web Services account. The simple, guided process will inform you of all the related fees and requirements." }, { "code": null, "e": 3146, "s": 2985, "text": "After performing all the necessary steps of the process, you will have the access. Simply sign in to the AWS console, and then navigate to the DynamoDB console." }, { "code": null, "e": 3221, "s": 3146, "text": "Be sure to delete unused or unnecessary material to avoid associated fees." }, { "code": null, "e": 3519, "s": 3221, "text": "The AWS (Amazon Web Service) provides a version of DynamoDB for local installations. It supports creating applications without the web service or a connection. It also reduces provisioned throughput, data storage, and transfer fees by allowing a local database. This guide assumes a local install." }, { "code": null, "e": 3629, "s": 3519, "text": "When ready for deployment, you can make a few small adjustments to your application to convert it to AWS use." }, { "code": null, "e": 3793, "s": 3629, "text": "The install file is a .jar executable. It runs in Linux, Unix, Windows, and any other OS with Java support. Download the file by using one of the following links −" }, { "code": null, "e": 3888, "s": 3793, "text": "Tarball − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.tar.gz" }, { "code": null, "e": 3983, "s": 3888, "text": "Tarball − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.tar.gz" }, { "code": null, "e": 4079, "s": 3983, "text": "Zip archive − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.zip" }, { "code": null, "e": 4175, "s": 4079, "text": "Zip archive − http://dynamodb-local.s3-website-us-west2.amazonaws.com/dynamodb_local_latest.zip" }, { "code": null, "e": 4428, "s": 4175, "text": "Note − Other repositories offer the file, but not necessarily the latest version. Use the links above for up-to-date install files. Also, ensure you have Java Runtime Engine (JRE) version 6.x or a newer version. DynamoDB cannot run with older versions." }, { "code": null, "e": 4551, "s": 4428, "text": "After downloading the appropriate archive, extract its directory (DynamoDBLocal.jar) and place it in the desired location." }, { "code": null, "e": 4703, "s": 4551, "text": "You can then start DynamoDB by opening a command prompt, navigating to the directory containing DynamoDBLocal.jar, and entering the following command −" }, { "code": null, "e": 4782, "s": 4703, "text": "java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb\n" }, { "code": null, "e": 4861, "s": 4782, "text": "You can also stop the DynamoDB by closing the command prompt used to start it." }, { "code": null, "e": 5033, "s": 4861, "text": "You can use a JavaScript shell, a GUI console, and multiple languages to work with DynamoDB. The languages available include Ruby, Java, Python, C#, Erlang, PHP, and Perl." }, { "code": null, "e": 5241, "s": 5033, "text": "In this tutorial, we use Java and GUI console examples for conceptual and code clarity. Install a Java IDE, the AWS SDK for Java, and setup AWS security credentials for the Java SDK in order to utilize Java." }, { "code": null, "e": 5514, "s": 5241, "text": "When ready for deployment, you will need to alter your code. The adjustments depend on code language and other factors. The main change merely consists of changing the endpoint from a local point to an AWS region. Other changes require deeper analysis of your application." }, { "code": null, "e": 5634, "s": 5514, "text": "A local install differs from the web service in many ways including, but not limited to the following key differences −" }, { "code": null, "e": 5715, "s": 5634, "text": "The local install creates tables immediately, but the service takes much longer." }, { "code": null, "e": 5796, "s": 5715, "text": "The local install creates tables immediately, but the service takes much longer." }, { "code": null, "e": 5834, "s": 5796, "text": "The local install ignores throughput." }, { "code": null, "e": 5872, "s": 5834, "text": "The local install ignores throughput." }, { "code": null, "e": 5924, "s": 5872, "text": "The deletion occurs immediately in a local install." }, { "code": null, "e": 5976, "s": 5924, "text": "The deletion occurs immediately in a local install." }, { "code": null, "e": 6065, "s": 5976, "text": "The reads/writes occur quickly in local installs due to the absence of network overhead." } ]
trunc() in Python
22 Jan, 2022 Truncate in Python There are many built-in modules in python. Out of these module there is one interesting module known as math module which have several functions in it like, ceil, floor, truncate, factorial, fabs, etc. Out of these functions there is an interesting function called truncate which behaves as a ceiling function for negative number and floor function for positive number. In case of positive number Python3 # Python program to show output of floor(), ceil()# truncate() for a positive number.import mathprint (math.floor(3.5)) # floorprint (math.trunc(3.5)) # work as floorprint (math.ceil(3.5)) # ceil Output: 3.0 3 4.0 In case of negative number Python3 # Python program to show output of floor(), ceil()# truncate() for a negative number.import mathprint (math.floor(-3.5)) # floorprint (math.trunc(-3.5)) # work as ceilprint (math.ceil(-3.5)) # ceil Output: -4.0 -3 -3.0 This is because the ceiling function is used to round up, i.e., towards positive infinity and floor function is used to round down, i.e., towards negative infinity. But the truncate function is used to round up or down towards zero.Diagrammatic representation of truncate function:- This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ASuresh amartyaghoshgfg 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": "\n22 Jan, 2022" }, { "code": null, "e": 72, "s": 53, "text": "Truncate in Python" }, { "code": null, "e": 274, "s": 72, "text": "There are many built-in modules in python. Out of these module there is one interesting module known as math module which have several functions in it like, ceil, floor, truncate, factorial, fabs, etc." }, { "code": null, "e": 442, "s": 274, "text": "Out of these functions there is an interesting function called truncate which behaves as a ceiling function for negative number and floor function for positive number." }, { "code": null, "e": 470, "s": 442, "text": "In case of positive number " }, { "code": null, "e": 478, "s": 470, "text": "Python3" }, { "code": "# Python program to show output of floor(), ceil()# truncate() for a positive number.import mathprint (math.floor(3.5)) # floorprint (math.trunc(3.5)) # work as floorprint (math.ceil(3.5)) # ceil", "e": 675, "s": 478, "text": null }, { "code": null, "e": 683, "s": 675, "text": "Output:" }, { "code": null, "e": 693, "s": 683, "text": "3.0\n3\n4.0" }, { "code": null, "e": 721, "s": 693, "text": "In case of negative number " }, { "code": null, "e": 729, "s": 721, "text": "Python3" }, { "code": "# Python program to show output of floor(), ceil()# truncate() for a negative number.import mathprint (math.floor(-3.5)) # floorprint (math.trunc(-3.5)) # work as ceilprint (math.ceil(-3.5)) # ceil", "e": 928, "s": 729, "text": null }, { "code": null, "e": 936, "s": 928, "text": "Output:" }, { "code": null, "e": 949, "s": 936, "text": "-4.0\n-3\n-3.0" }, { "code": null, "e": 1116, "s": 949, "text": "This is because the ceiling function is used to round up, i.e., towards positive infinity and floor function is used to round down, i.e., towards negative infinity. " }, { "code": null, "e": 1236, "s": 1116, "text": "But the truncate function is used to round up or down towards zero.Diagrammatic representation of truncate function:- " }, { "code": null, "e": 1628, "s": 1236, "text": "This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 1636, "s": 1628, "text": "ASuresh" }, { "code": null, "e": 1652, "s": 1636, "text": "amartyaghoshgfg" }, { "code": null, "e": 1659, "s": 1652, "text": "Python" }, { "code": null, "e": 1757, "s": 1659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1775, "s": 1757, "text": "Python Dictionary" }, { "code": null, "e": 1817, "s": 1775, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1839, "s": 1817, "text": "Enumerate() in Python" }, { "code": null, "e": 1874, "s": 1839, "text": "Read a file line by line in Python" }, { "code": null, "e": 1900, "s": 1874, "text": "Python String | replace()" }, { "code": null, "e": 1932, "s": 1900, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1961, "s": 1932, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1988, "s": 1961, "text": "Python Classes and Objects" }, { "code": null, "e": 2018, "s": 1988, "text": "Iterate over a list in Python" } ]
How to create Calendar in ReactJS ?
29 Oct, 2021 In this article, we are going to learn how we can create calendars in ReactJS. You can use this calendar in your to-do list, e-commerce site, Ticket booking site, and many more apps. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Approach: To create our calendar we are going to see 2 different methods. In the first method, we will see how we can create a simple calendar without any styling and In the second method, we will also add some styling to our calendar to make it more attractive. Create ReactJs Application: You can create a new ReactJs project using the below command: npx create-react-app gfg Project Structure: It will look like this. Example 1: In this example, we are going to create a very simple calendar without any styling. So for this, we are going to install a new npm package. Run the below code in your terminal to install the package. npm i @natscale/react-calendar Now we are going to add the calendar to our homepage. For this, add the below code in your App.js file. App.js import React, { useState, useCallback } from 'react';import { Calendar } from '@natscale/react-calendar'; export default function CalendarGfg() { const [value, setValue] = useState(); const onChange = useCallback( (value) => { setValue(value); }, [setValue], ); return ( <div> <h1>Calendar - GeeksforGeeks</h1> <Calendar value={value} onChange={onChange} /> </div> );} Explanation: In the above file, we are first importing our Calendar from the package that we installed. After that, we are using the useState() hook to create and set values on the onChange function. Then we are returning our Calendar. Steps to run the application: Run the below command in the terminal to run the app. npm start Example 2: In this example, we are going to create a very calendar with some styling. So for this, we are going to install a new npm package. Run the below code in your terminal to install the package. npm i react-calendar Now we are going to add the calendar to our homepage. For this, add the below code in your App.js file. App.js import React, { useState } from 'react';import Calendar from 'react-calendar';import 'react-calendar/dist/Calendar.css'; export default function CalendarGfg() { const [value, onChange] = useState(new Date()); return ( <div> <h1>Calendar - GeeksforGeeks</h1> <Calendar onChange={onChange} value={value} /> </div> );} Steps to run the application: Run the below command in the terminal to run the app. npm start React-Questions JavaScript ReactJS 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 Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 211, "s": 28, "text": "In this article, we are going to learn how we can create calendars in ReactJS. You can use this calendar in your to-do list, e-commerce site, Ticket booking site, and many more apps." }, { "code": null, "e": 404, "s": 211, "text": "React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies." }, { "code": null, "e": 667, "s": 404, "text": "Approach: To create our calendar we are going to see 2 different methods. In the first method, we will see how we can create a simple calendar without any styling and In the second method, we will also add some styling to our calendar to make it more attractive." }, { "code": null, "e": 757, "s": 667, "text": "Create ReactJs Application: You can create a new ReactJs project using the below command:" }, { "code": null, "e": 784, "s": 757, "text": "npx create-react-app gfg " }, { "code": null, "e": 827, "s": 784, "text": "Project Structure: It will look like this." }, { "code": null, "e": 1038, "s": 827, "text": "Example 1: In this example, we are going to create a very simple calendar without any styling. So for this, we are going to install a new npm package. Run the below code in your terminal to install the package." }, { "code": null, "e": 1069, "s": 1038, "text": "npm i @natscale/react-calendar" }, { "code": null, "e": 1173, "s": 1069, "text": "Now we are going to add the calendar to our homepage. For this, add the below code in your App.js file." }, { "code": null, "e": 1180, "s": 1173, "text": "App.js" }, { "code": "import React, { useState, useCallback } from 'react';import { Calendar } from '@natscale/react-calendar'; export default function CalendarGfg() { const [value, setValue] = useState(); const onChange = useCallback( (value) => { setValue(value); }, [setValue], ); return ( <div> <h1>Calendar - GeeksforGeeks</h1> <Calendar value={value} onChange={onChange} /> </div> );}", "e": 1589, "s": 1180, "text": null }, { "code": null, "e": 1825, "s": 1589, "text": "Explanation: In the above file, we are first importing our Calendar from the package that we installed. After that, we are using the useState() hook to create and set values on the onChange function. Then we are returning our Calendar." }, { "code": null, "e": 1909, "s": 1825, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 1919, "s": 1909, "text": "npm start" }, { "code": null, "e": 2121, "s": 1919, "text": "Example 2: In this example, we are going to create a very calendar with some styling. So for this, we are going to install a new npm package. Run the below code in your terminal to install the package." }, { "code": null, "e": 2142, "s": 2121, "text": "npm i react-calendar" }, { "code": null, "e": 2246, "s": 2142, "text": "Now we are going to add the calendar to our homepage. For this, add the below code in your App.js file." }, { "code": null, "e": 2253, "s": 2246, "text": "App.js" }, { "code": "import React, { useState } from 'react';import Calendar from 'react-calendar';import 'react-calendar/dist/Calendar.css'; export default function CalendarGfg() { const [value, onChange] = useState(new Date()); return ( <div> <h1>Calendar - GeeksforGeeks</h1> <Calendar onChange={onChange} value={value} /> </div> );}", "e": 2610, "s": 2253, "text": null }, { "code": null, "e": 2694, "s": 2610, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 2704, "s": 2694, "text": "npm start" }, { "code": null, "e": 2720, "s": 2704, "text": "React-Questions" }, { "code": null, "e": 2731, "s": 2720, "text": "JavaScript" }, { "code": null, "e": 2739, "s": 2731, "text": "ReactJS" }, { "code": null, "e": 2756, "s": 2739, "text": "Web Technologies" }, { "code": null, "e": 2854, "s": 2756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2915, "s": 2854, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2955, "s": 2915, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2996, "s": 2955, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3038, "s": 2996, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3060, "s": 3038, "text": "JavaScript | Promises" }, { "code": null, "e": 3103, "s": 3060, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3148, "s": 3103, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 3186, "s": 3148, "text": "Axios in React: A Guide for Beginners" } ]
HTML | loop Attribute
31 Aug, 2021 The HTML loop Attribute is used to restart the audio and video again and again after finishing it. It contains the Boolean value. Syntax: <element loop> Applicable <audio> <video> <marquee> <bgsound> Example 1: Below Example illustrates the use of loop attribute in <audio> element. html <!DOCTYPE html><html> <head> <title> Audio loop Attribute </title></head> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks</h1> <h2 style="font-family: Impact"> HTML Audio loop Attribute</h2> <br> <audio id="Test_Audio" controls loop> <source src="beep.mp3" type="audio/mpeg"> </audio></body> </html> Output: Example 2: Below Example illustrates the use of loop attribute in <video> element. html <!DOCTYPE html><html> <head> <title> HTML video loop Attribute </title></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3>HTML video loop Attribute</h3> <video width="400" height="200" controls loop> <source src="Canvas.move_.mp4" type="video/mp4"> <source src="Canvas.move_.ogg" type="video/ogg"> </video> </center></body> </html> Output: Supported Browsers: The browsers supported by loop Attribute are listed below: Google Chrome 4.0/4.0 Internet Explorer 9.0/9.0 Firefox 3.5/11.0 Apple Safari 4.0/4.0 Opera 10.5/10.5 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Remove elements from a JavaScript Array Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 159, "s": 28, "text": "The HTML loop Attribute is used to restart the audio and video again and again after finishing it. It contains the Boolean value. " }, { "code": null, "e": 169, "s": 159, "text": "Syntax: " }, { "code": null, "e": 184, "s": 169, "text": "<element loop>" }, { "code": null, "e": 197, "s": 184, "text": "Applicable " }, { "code": null, "e": 205, "s": 197, "text": "<audio>" }, { "code": null, "e": 213, "s": 205, "text": "<video>" }, { "code": null, "e": 223, "s": 213, "text": "<marquee>" }, { "code": null, "e": 233, "s": 223, "text": "<bgsound>" }, { "code": null, "e": 318, "s": 233, "text": "Example 1: Below Example illustrates the use of loop attribute in <audio> element. " }, { "code": null, "e": 323, "s": 318, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Audio loop Attribute </title></head> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks</h1> <h2 style=\"font-family: Impact\"> HTML Audio loop Attribute</h2> <br> <audio id=\"Test_Audio\" controls loop> <source src=\"beep.mp3\" type=\"audio/mpeg\"> </audio></body> </html>", "e": 717, "s": 323, "text": null }, { "code": null, "e": 727, "s": 717, "text": "Output: " }, { "code": null, "e": 812, "s": 727, "text": "Example 2: Below Example illustrates the use of loop attribute in <video> element. " }, { "code": null, "e": 817, "s": 812, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML video loop Attribute </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3>HTML video loop Attribute</h3> <video width=\"400\" height=\"200\" controls loop> <source src=\"Canvas.move_.mp4\" type=\"video/mp4\"> <source src=\"Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center></body> </html>", "e": 1330, "s": 817, "text": null }, { "code": null, "e": 1340, "s": 1330, "text": "Output: " }, { "code": null, "e": 1421, "s": 1340, "text": "Supported Browsers: The browsers supported by loop Attribute are listed below: " }, { "code": null, "e": 1443, "s": 1421, "text": "Google Chrome 4.0/4.0" }, { "code": null, "e": 1469, "s": 1443, "text": "Internet Explorer 9.0/9.0" }, { "code": null, "e": 1486, "s": 1469, "text": "Firefox 3.5/11.0" }, { "code": null, "e": 1507, "s": 1486, "text": "Apple Safari 4.0/4.0" }, { "code": null, "e": 1523, "s": 1507, "text": "Opera 10.5/10.5" }, { "code": null, "e": 1545, "s": 1525, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1561, "s": 1545, "text": "HTML-Attributes" }, { "code": null, "e": 1566, "s": 1561, "text": "HTML" }, { "code": null, "e": 1583, "s": 1566, "text": "Web Technologies" }, { "code": null, "e": 1588, "s": 1583, "text": "HTML" }, { "code": null, "e": 1686, "s": 1588, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1734, "s": 1686, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1758, "s": 1734, "text": "REST API (Introduction)" }, { "code": null, "e": 1808, "s": 1758, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1845, "s": 1808, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1873, "s": 1845, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1906, "s": 1873, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1967, "s": 1906, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2010, "s": 1967, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2050, "s": 2010, "text": "Remove elements from a JavaScript Array" } ]
Why java.lang.VerifyError Occurs in Java and How to Solve this?
30 May, 2022 The Java Virtual Machine (JVM) distrusts all loaded bytecode as a core tenet of the Java Security Model. During runtime, the JVM will load .class files and attempt to link them together to form an executable — but the validity of these loaded .class files is unknown. To ensure that the loaded .class files do not pose a threat to the final executable, a verification process is done on the .class files by the JVM. Additionally, the JVM ensures that binaries are well-formed. For example, the JVM will verify classes do not subtype final classes. In many cases, verification fails on valid, non-malicious bytecode because a newer version of Java has a stricter verification process than older versions. For example, JDK 13 may have added a verification step that was not enforced in JDK 7. Thus, if we run an application with JVM 13 and include dependencies compiled with an older version of the Java Compiler (javac), the JVM may consider the outdated dependencies to be invalid. Thus, when linking older .class files with a newer JVM, the JVM may throw a java.lang.VerifyError. The VerifyError exists since the 1.0 version of Java. The Structure of VerifyError: Constructors VerifyError() This constructor creates an instance of the VerifyError class, setting null as its message. VerifyError(String s) This constructor creates an instance of the VerifyError class, using the specified string as message. Here the class which threw the error is indicated through string argument. The three most common reasons upon which this error may occur as follows: Reason 1: “This error will be thrown whenever a class which is declared as final is extended.” Program: Java // Java program to show the occurrence// of java.lang.VerifyError class B extends A { public static void main(String args[]) { System.out.println("my super class name:-" + myname); }} public class A { static String myname = "A";} As you see if you compile these two programs and execute it, it must have to work fine without showing any error. Now after changing the class A as follows and compile it alone. final public class A { static String myname="A"; } Note that here we have recompiled the “class A” alone. Now if we execute the class B (class that contains main() method) then an error message like below will be thrown at run-time. Exception in thread "main" java.lang.VerifyError: Cannot inherit from final class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: B. This error was caused because that we changed the definition of class TestClassA, but class TestClassB was compiled using an older version of the class TestClassA. Reason 2: “Consider a class that extends another class before and if it no longer extends that class now, then this error may be thrown at run-time.” Program: Java // Java program to show the occurrence// of java.lang.VerifyError class C extends B { public static void main(String args[]) { B b = new B(); display(b); } public static void display(A a) { System.out.println(a.supername); }} class B extends A { String subname = "B";} public class A { String supername = "A";} A The above program will also work fine, but if class B is changed to no longer extend class A then error may get thrown. Now if we change the class B as follows , and “recompile it alone” , then class C will have no idea about the changes made in class B thus causing this error. class B { String subname="B"; } Exception in thread “main” java.lang.VerifyError: (class: C, method: main signature: ([Ljava/lang/String;)V) Incompatible argument to function Could not find the main class: C. Program will exit. Reason 3: “If we try to override a method which is declared as final then also this error will be thrown”. Let us have classes A and B as follows: Program: Java // Java program to show the occurrence// of java.lang.VerifyError class B extends A{ public static void main(String args[]) { A a = new A(); a.display(); } void display() { super.display(); }} public class A{ String supername = "A"; void display() { System.out.println("My name is " + supername); }} In class A if the method display() is changed to be of final and “recompile it alone”, then this verify error will be thrown if class B is executed since no other class can override this method. Output: Exception in thread "main" java.lang.VerifyError: class B overrides final method display.()V at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: B. Program will exit. Here you could have noticed that this verifies Error is thrown because we have recompiled only the edited class” and not all the classes as a whole. So you may think that this error can be easily identified if you recompile all the classes as a whole by recompiling the class which contains the main() method. Of course, it is true but there are certain situations in which you cannot be able to identify this error at Compile time, which is mainly because of using two different versions of third-party libraries in your application. How to deal with the VerifyError? In order to avoid the VerifyError, you must compile all your classes using the same version of Java. Also, once a change is done to a class, then make sure that you re-compile your project from scratch. Finally, if your application makes use of external libraries, verify that you use the appropriate version of every library and of course, consult the corresponding javadocs, in order to be sure that everything is correct. Whenever possible, use the latest versions of dependencies rather than disabling verification. nikhatkhan11 Java-Exceptions Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2022" }, { "code": null, "e": 445, "s": 28, "text": "The Java Virtual Machine (JVM) distrusts all loaded bytecode as a core tenet of the Java Security Model. During runtime, the JVM will load .class files and attempt to link them together to form an executable — but the validity of these loaded .class files is unknown. To ensure that the loaded .class files do not pose a threat to the final executable, a verification process is done on the .class files by the JVM." }, { "code": null, "e": 1011, "s": 445, "text": "Additionally, the JVM ensures that binaries are well-formed. For example, the JVM will verify classes do not subtype final classes. In many cases, verification fails on valid, non-malicious bytecode because a newer version of Java has a stricter verification process than older versions. For example, JDK 13 may have added a verification step that was not enforced in JDK 7. Thus, if we run an application with JVM 13 and include dependencies compiled with an older version of the Java Compiler (javac), the JVM may consider the outdated dependencies to be invalid." }, { "code": null, "e": 1110, "s": 1011, "text": "Thus, when linking older .class files with a newer JVM, the JVM may throw a java.lang.VerifyError." }, { "code": null, "e": 1164, "s": 1110, "text": "The VerifyError exists since the 1.0 version of Java." }, { "code": null, "e": 1194, "s": 1164, "text": "The Structure of VerifyError:" }, { "code": null, "e": 1207, "s": 1194, "text": "Constructors" }, { "code": null, "e": 1221, "s": 1207, "text": "VerifyError()" }, { "code": null, "e": 1313, "s": 1221, "text": "This constructor creates an instance of the VerifyError class, setting null as its message." }, { "code": null, "e": 1335, "s": 1313, "text": "VerifyError(String s)" }, { "code": null, "e": 1513, "s": 1335, "text": "This constructor creates an instance of the VerifyError class, using the specified string as message. Here the class which threw the error is indicated through string argument." }, { "code": null, "e": 1587, "s": 1513, "text": "The three most common reasons upon which this error may occur as follows:" }, { "code": null, "e": 1683, "s": 1587, "text": "Reason 1: “This error will be thrown whenever a class which is declared as final is extended.” " }, { "code": null, "e": 1692, "s": 1683, "text": "Program:" }, { "code": null, "e": 1697, "s": 1692, "text": "Java" }, { "code": "// Java program to show the occurrence// of java.lang.VerifyError class B extends A { public static void main(String args[]) { System.out.println(\"my super class name:-\" + myname); }} public class A { static String myname = \"A\";}", "e": 1977, "s": 1697, "text": null }, { "code": null, "e": 2156, "s": 1977, "text": "As you see if you compile these two programs and execute it, it must have to work fine without showing any error. Now after changing the class A as follows and compile it alone. " }, { "code": null, "e": 2209, "s": 2156, "text": "final public class A\n{\n static String myname=\"A\";\n}" }, { "code": null, "e": 2391, "s": 2209, "text": "Note that here we have recompiled the “class A” alone. Now if we execute the class B (class that contains main() method) then an error message like below will be thrown at run-time." }, { "code": null, "e": 3256, "s": 2391, "text": "Exception in thread \"main\" java.lang.VerifyError: Cannot inherit from final class\n at java.lang.ClassLoader.defineClass1(Native Method)\n at java.lang.ClassLoader.defineClassCond(Unknown Source)\n at java.lang.ClassLoader.defineClass(Unknown Source)\n at java.security.SecureClassLoader.defineClass(Unknown Source)\n at java.net.URLClassLoader.defineClass(Unknown Source)\n at java.net.URLClassLoader.access$000(Unknown Source)\n at java.net.URLClassLoader$1.run(Unknown Source)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.net.URLClassLoader.findClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\nCould not find the main class: B. " }, { "code": null, "e": 3420, "s": 3256, "text": "This error was caused because that we changed the definition of class TestClassA, but class TestClassB was compiled using an older version of the class TestClassA." }, { "code": null, "e": 3570, "s": 3420, "text": "Reason 2: “Consider a class that extends another class before and if it no longer extends that class now, then this error may be thrown at run-time.”" }, { "code": null, "e": 3579, "s": 3570, "text": "Program:" }, { "code": null, "e": 3584, "s": 3579, "text": "Java" }, { "code": "// Java program to show the occurrence// of java.lang.VerifyError class C extends B { public static void main(String args[]) { B b = new B(); display(b); } public static void display(A a) { System.out.println(a.supername); }} class B extends A { String subname = \"B\";} public class A { String supername = \"A\";}", "e": 3941, "s": 3584, "text": null }, { "code": null, "e": 3943, "s": 3941, "text": "A" }, { "code": null, "e": 4222, "s": 3943, "text": "The above program will also work fine, but if class B is changed to no longer extend class A then error may get thrown. Now if we change the class B as follows , and “recompile it alone” , then class C will have no idea about the changes made in class B thus causing this error." }, { "code": null, "e": 4254, "s": 4222, "text": "class B {\nString subname=\"B\";\n}" }, { "code": null, "e": 4397, "s": 4254, "text": "Exception in thread “main” java.lang.VerifyError: (class: C, method: main signature: ([Ljava/lang/String;)V) Incompatible argument to function" }, { "code": null, "e": 4433, "s": 4397, "text": "Could not find the main class: C. " }, { "code": null, "e": 4452, "s": 4433, "text": "Program will exit." }, { "code": null, "e": 4599, "s": 4452, "text": "Reason 3: “If we try to override a method which is declared as final then also this error will be thrown”. Let us have classes A and B as follows:" }, { "code": null, "e": 4608, "s": 4599, "text": "Program:" }, { "code": null, "e": 4613, "s": 4608, "text": "Java" }, { "code": "// Java program to show the occurrence// of java.lang.VerifyError class B extends A{ public static void main(String args[]) { A a = new A(); a.display(); } void display() { super.display(); }} public class A{ String supername = \"A\"; void display() { System.out.println(\"My name is \" + supername); }}", "e": 4967, "s": 4613, "text": null }, { "code": null, "e": 5163, "s": 4967, "text": "In class A if the method display() is changed to be of final and “recompile it alone”, then this verify error will be thrown if class B is executed since no other class can override this method." }, { "code": null, "e": 5171, "s": 5163, "text": "Output:" }, { "code": null, "e": 6065, "s": 5171, "text": "Exception in thread \"main\" java.lang.VerifyError: class B overrides final method\ndisplay.()V\n at java.lang.ClassLoader.defineClass1(Native Method)\n at java.lang.ClassLoader.defineClassCond(Unknown Source)\n at java.lang.ClassLoader.defineClass(Unknown Source)\n at java.security.SecureClassLoader.defineClass(Unknown Source)\n at java.net.URLClassLoader.defineClass(Unknown Source)\n at java.net.URLClassLoader.access$000(Unknown Source)\n at java.net.URLClassLoader$1.run(Unknown Source)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.net.URLClassLoader.findClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\nCould not find the main class: B. Program will exit." }, { "code": null, "e": 6601, "s": 6065, "text": "Here you could have noticed that this verifies Error is thrown because we have recompiled only the edited class” and not all the classes as a whole. So you may think that this error can be easily identified if you recompile all the classes as a whole by recompiling the class which contains the main() method. Of course, it is true but there are certain situations in which you cannot be able to identify this error at Compile time, which is mainly because of using two different versions of third-party libraries in your application. " }, { "code": null, "e": 6635, "s": 6601, "text": "How to deal with the VerifyError?" }, { "code": null, "e": 7060, "s": 6635, "text": "In order to avoid the VerifyError, you must compile all your classes using the same version of Java. Also, once a change is done to a class, then make sure that you re-compile your project from scratch. Finally, if your application makes use of external libraries, verify that you use the appropriate version of every library and of course, consult the corresponding javadocs, in order to be sure that everything is correct." }, { "code": null, "e": 7155, "s": 7060, "text": "Whenever possible, use the latest versions of dependencies rather than disabling verification." }, { "code": null, "e": 7168, "s": 7155, "text": "nikhatkhan11" }, { "code": null, "e": 7184, "s": 7168, "text": "Java-Exceptions" }, { "code": null, "e": 7191, "s": 7184, "text": "Picked" }, { "code": null, "e": 7196, "s": 7191, "text": "Java" }, { "code": null, "e": 7201, "s": 7196, "text": "Java" }, { "code": null, "e": 7299, "s": 7201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7314, "s": 7299, "text": "Stream In Java" }, { "code": null, "e": 7335, "s": 7314, "text": "Introduction to Java" }, { "code": null, "e": 7356, "s": 7335, "text": "Constructors in Java" }, { "code": null, "e": 7375, "s": 7356, "text": "Exceptions in Java" }, { "code": null, "e": 7392, "s": 7375, "text": "Generics in Java" }, { "code": null, "e": 7422, "s": 7392, "text": "Functional Interfaces in Java" }, { "code": null, "e": 7448, "s": 7422, "text": "Java Programming Examples" }, { "code": null, "e": 7464, "s": 7448, "text": "Strings in Java" }, { "code": null, "e": 7501, "s": 7464, "text": "Differences between JDK, JRE and JVM" } ]
Find minimum steps required to reach the end of a matrix | Set – 1
12 Sep, 2021 Given a 2d-matrix consisting of positive integers, the task is to find the minimum number of steps required to reach the end(leftmost-bottom cell) of the matrix. If we are at cell (i, j) we can go to cells (i, j+arr[i][j]) or (i+arr[i][j], j). We can not go out of bounds. If no path exists, print -1. Examples: Input : mat[][] = {{2, 1, 2}, {1, 1, 1}, {1, 1, 1}} Output : 2 Explanation : The path will be {0, 0} -> {0, 2} -> {2, 2} Thus, we are reaching end in two steps. Input : mat[][] = {{1, 1, 2}, {1, 1, 1}, {2, 1, 1}} Output : 3 A simple solution is to explore all possible solutions. This will take exponential time.Better approach: We can use dynamic programming to solve this problem in polynomial time.Let’s decide the states of ‘dp’. We will build up our solution on 2d DP. Let’s say we are at cell {i, j}. We will try to find the minimum number of steps required to reach the cell (n-1, n-1) from this cell. We only have two possible paths i.e. to cells {i, j+arr[i][j]} or {i+arr[i][j], j}.A simple recurrence relation will be: dp[i][j] = 1 + min(dp[i+arr[i]][j], dp[i][j+arr[i][j]]) Below is the implementation of the above idea: C++ Java Python3 C# Javascript // C++ program to implement above approach #include <bits/stdc++.h>#define n 3using namespace std; // 2d array to store// states of dpint dp[n][n]; // array to determine whether// a state has been solved beforeint v[n][n]; // Function to find the minimum number of// steps to reach the end of matrixint minSteps(int i, int j, int arr[][n]){ // base cases if (i == n - 1 and j == n - 1) return 0; if (i > n - 1 || j > n - 1) return 9999999; // if a state has been solved before // it won't be evaluated again. if (v[i][j]) return dp[i][j]; v[i][j] = 1; // recurrence relation dp[i][j] = 1 + min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j];} // Driver Codeint main(){ int arr[n][n] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = minSteps(0, 0, arr); if (ans >= 9999999) cout << -1; else cout << ans; return 0;} // Java program to implement above approachclass GFG { static int n = 3; // 2d array to store // states of dp static int dp[][] = new int[n][n]; // array to determine whether // a state has been solved before static int[][] v = new int[n][n]; // Function to find the minimum number of // steps to reach the end of matrix static int minSteps(int i, int j, int arr[][]) { // base cases if (i == n - 1 && j == n - 1) { return 0; } if (i > n - 1 || j > n - 1) { return 9999999; } // if a state has been solved before // it won't be evaluated again. if (v[i][j] == 1) { return dp[i][j]; } v[i][j] = 1; // recurrence relation dp[i][j] = 1 + Math.min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j]; } // Driver Code public static void main(String[] args) { int arr[][] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = minSteps(0, 0, arr); if (ans >= 9999999) { System.out.println(-1); } else { System.out.println(ans); } }} // This code contributed by Rajput-Ji # Python3 program to implement above approachimport numpy as np; n = 3 # 2d array to store# states of dpdp = np.zeros((n, n)); # array to determine whether# a state has been solved beforev = np.zeros((n, n)); # Function to find the minimum number of# steps to reach the end of matrixdef minSteps(i, j, arr) : # base cases if (i == n - 1 and j == n - 1) : return 0; if (i > n - 1 or j > n - 1) : return 9999999; # if a state has been solved before # it won't be evaluated again. if (v[i][j]) : return dp[i][j]; v[i][j] = 1; # recurrence relation dp[i][j] = 1 + min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j]; # Driver Codearr = [ [ 2, 1, 2 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ]; ans = minSteps(0, 0, arr);if (ans >= 9999999) : print(-1); else : print(ans); # This code is contributed by AnkitRai01 // C# program to implement above approachusing System; class GFG{ static int n = 3; // 2d array to store // states of dp static int [,]dp = new int[n, n]; // array to determine whether // a state has been solved before static int[,] v = new int[n, n]; // Function to find the minimum number of // steps to reach the end of matrix static int minSteps(int i, int j, int [,]arr) { // base cases if (i == n - 1 && j == n - 1) { return 0; } if (i > n - 1 || j > n - 1) { return 9999999; } // if a state has been solved before // it won't be evaluated again. if (v[i, j] == 1) { return dp[i, j]; } v[i, j] = 1; // recurrence relation dp[i, j] = 1 + Math.Min(minSteps(i + arr[i,j], j, arr), minSteps(i, j + arr[i,j], arr)); return dp[i, j]; } // Driver Code static public void Main () { int [,]arr = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = minSteps(0, 0, arr); if (ans >= 9999999) { Console.WriteLine(-1); } else { Console.WriteLine(ans); } }} // This code contributed by ajit. <script> // Javascript program to implement // above approach let n = 3; // 2d array to store // states of dp let dp = new Array(n); for(let i = 0; i < n; i++) { dp[i] = new Array(n); } // array to determine whether // a state has been solved before let v = new Array(n); for(let i = 0; i < n; i++) { v[i] = new Array(n); } // Function to find the minimum number of // steps to reach the end of matrix function minSteps(i, j, arr) { // base cases if (i == n - 1 && j == n - 1) { return 0; } if (i > n - 1 || j > n - 1) { return 9999999; } // if a state has been solved before // it won't be evaluated again. if (v[i][j] == 1) { return dp[i][j]; } v[i][j] = 1; // recurrence relation dp[i][j] = 1 + Math.min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j]; } let arr = [ [ 2, 1, 2 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ]; let ans = minSteps(0, 0, arr); if (ans >= 9999999) { document.write(-1); } else { document.write(ans); } </script> 2 Time Complexity: O(N2). Rajput-Ji jit_t ankthon mukesh07 simmytarika5 Divide and Conquer Dynamic Programming Matrix Dynamic Programming Divide and Conquer Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Program for Tower of Hanoi Find cubic root of a number Write a program to calculate pow(x,n) 0-1 Knapsack Problem | DP-10 Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Sep, 2021" }, { "code": null, "e": 354, "s": 52, "text": "Given a 2d-matrix consisting of positive integers, the task is to find the minimum number of steps required to reach the end(leftmost-bottom cell) of the matrix. If we are at cell (i, j) we can go to cells (i, j+arr[i][j]) or (i+arr[i][j], j). We can not go out of bounds. If no path exists, print -1." }, { "code": null, "e": 365, "s": 354, "text": "Examples: " }, { "code": null, "e": 635, "s": 365, "text": "Input : \nmat[][] = {{2, 1, 2},\n {1, 1, 1},\n {1, 1, 1}}\nOutput : 2\nExplanation : The path will be {0, 0} -> {0, 2} -> {2, 2}\nThus, we are reaching end in two steps.\n\nInput :\nmat[][] = {{1, 1, 2},\n {1, 1, 1},\n {2, 1, 1}}\nOutput : 3" }, { "code": null, "e": 1142, "s": 635, "text": "A simple solution is to explore all possible solutions. This will take exponential time.Better approach: We can use dynamic programming to solve this problem in polynomial time.Let’s decide the states of ‘dp’. We will build up our solution on 2d DP. Let’s say we are at cell {i, j}. We will try to find the minimum number of steps required to reach the cell (n-1, n-1) from this cell. We only have two possible paths i.e. to cells {i, j+arr[i][j]} or {i+arr[i][j], j}.A simple recurrence relation will be: " }, { "code": null, "e": 1198, "s": 1142, "text": "dp[i][j] = 1 + min(dp[i+arr[i]][j], dp[i][j+arr[i][j]])" }, { "code": null, "e": 1246, "s": 1198, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 1250, "s": 1246, "text": "C++" }, { "code": null, "e": 1255, "s": 1250, "text": "Java" }, { "code": null, "e": 1263, "s": 1255, "text": "Python3" }, { "code": null, "e": 1266, "s": 1263, "text": "C#" }, { "code": null, "e": 1277, "s": 1266, "text": "Javascript" }, { "code": "// C++ program to implement above approach #include <bits/stdc++.h>#define n 3using namespace std; // 2d array to store// states of dpint dp[n][n]; // array to determine whether// a state has been solved beforeint v[n][n]; // Function to find the minimum number of// steps to reach the end of matrixint minSteps(int i, int j, int arr[][n]){ // base cases if (i == n - 1 and j == n - 1) return 0; if (i > n - 1 || j > n - 1) return 9999999; // if a state has been solved before // it won't be evaluated again. if (v[i][j]) return dp[i][j]; v[i][j] = 1; // recurrence relation dp[i][j] = 1 + min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j];} // Driver Codeint main(){ int arr[n][n] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = minSteps(0, 0, arr); if (ans >= 9999999) cout << -1; else cout << ans; return 0;}", "e": 2284, "s": 1277, "text": null }, { "code": "// Java program to implement above approachclass GFG { static int n = 3; // 2d array to store // states of dp static int dp[][] = new int[n][n]; // array to determine whether // a state has been solved before static int[][] v = new int[n][n]; // Function to find the minimum number of // steps to reach the end of matrix static int minSteps(int i, int j, int arr[][]) { // base cases if (i == n - 1 && j == n - 1) { return 0; } if (i > n - 1 || j > n - 1) { return 9999999; } // if a state has been solved before // it won't be evaluated again. if (v[i][j] == 1) { return dp[i][j]; } v[i][j] = 1; // recurrence relation dp[i][j] = 1 + Math.min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j]; } // Driver Code public static void main(String[] args) { int arr[][] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = minSteps(0, 0, arr); if (ans >= 9999999) { System.out.println(-1); } else { System.out.println(ans); } }} // This code contributed by Rajput-Ji", "e": 3574, "s": 2284, "text": null }, { "code": "# Python3 program to implement above approachimport numpy as np; n = 3 # 2d array to store# states of dpdp = np.zeros((n, n)); # array to determine whether# a state has been solved beforev = np.zeros((n, n)); # Function to find the minimum number of# steps to reach the end of matrixdef minSteps(i, j, arr) : # base cases if (i == n - 1 and j == n - 1) : return 0; if (i > n - 1 or j > n - 1) : return 9999999; # if a state has been solved before # it won't be evaluated again. if (v[i][j]) : return dp[i][j]; v[i][j] = 1; # recurrence relation dp[i][j] = 1 + min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j]; # Driver Codearr = [ [ 2, 1, 2 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ]; ans = minSteps(0, 0, arr);if (ans >= 9999999) : print(-1); else : print(ans); # This code is contributed by AnkitRai01", "e": 4539, "s": 3574, "text": null }, { "code": "// C# program to implement above approachusing System; class GFG{ static int n = 3; // 2d array to store // states of dp static int [,]dp = new int[n, n]; // array to determine whether // a state has been solved before static int[,] v = new int[n, n]; // Function to find the minimum number of // steps to reach the end of matrix static int minSteps(int i, int j, int [,]arr) { // base cases if (i == n - 1 && j == n - 1) { return 0; } if (i > n - 1 || j > n - 1) { return 9999999; } // if a state has been solved before // it won't be evaluated again. if (v[i, j] == 1) { return dp[i, j]; } v[i, j] = 1; // recurrence relation dp[i, j] = 1 + Math.Min(minSteps(i + arr[i,j], j, arr), minSteps(i, j + arr[i,j], arr)); return dp[i, j]; } // Driver Code static public void Main () { int [,]arr = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = minSteps(0, 0, arr); if (ans >= 9999999) { Console.WriteLine(-1); } else { Console.WriteLine(ans); } }} // This code contributed by ajit.", "e": 5882, "s": 4539, "text": null }, { "code": "<script> // Javascript program to implement // above approach let n = 3; // 2d array to store // states of dp let dp = new Array(n); for(let i = 0; i < n; i++) { dp[i] = new Array(n); } // array to determine whether // a state has been solved before let v = new Array(n); for(let i = 0; i < n; i++) { v[i] = new Array(n); } // Function to find the minimum number of // steps to reach the end of matrix function minSteps(i, j, arr) { // base cases if (i == n - 1 && j == n - 1) { return 0; } if (i > n - 1 || j > n - 1) { return 9999999; } // if a state has been solved before // it won't be evaluated again. if (v[i][j] == 1) { return dp[i][j]; } v[i][j] = 1; // recurrence relation dp[i][j] = 1 + Math.min(minSteps(i + arr[i][j], j, arr), minSteps(i, j + arr[i][j], arr)); return dp[i][j]; } let arr = [ [ 2, 1, 2 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ]; let ans = minSteps(0, 0, arr); if (ans >= 9999999) { document.write(-1); } else { document.write(ans); } </script>", "e": 7160, "s": 5882, "text": null }, { "code": null, "e": 7162, "s": 7160, "text": "2" }, { "code": null, "e": 7189, "s": 7164, "text": "Time Complexity: O(N2). " }, { "code": null, "e": 7199, "s": 7189, "text": "Rajput-Ji" }, { "code": null, "e": 7205, "s": 7199, "text": "jit_t" }, { "code": null, "e": 7213, "s": 7205, "text": "ankthon" }, { "code": null, "e": 7222, "s": 7213, "text": "mukesh07" }, { "code": null, "e": 7235, "s": 7222, "text": "simmytarika5" }, { "code": null, "e": 7254, "s": 7235, "text": "Divide and Conquer" }, { "code": null, "e": 7274, "s": 7254, "text": "Dynamic Programming" }, { "code": null, "e": 7281, "s": 7274, "text": "Matrix" }, { "code": null, "e": 7301, "s": 7281, "text": "Dynamic Programming" }, { "code": null, "e": 7320, "s": 7301, "text": "Divide and Conquer" }, { "code": null, "e": 7327, "s": 7320, "text": "Matrix" }, { "code": null, "e": 7425, "s": 7327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7469, "s": 7425, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 7516, "s": 7469, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 7543, "s": 7516, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 7571, "s": 7543, "text": "Find cubic root of a number" }, { "code": null, "e": 7609, "s": 7571, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 7638, "s": 7609, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 7670, "s": 7638, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 7704, "s": 7670, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 7731, "s": 7704, "text": "Subset Sum Problem | DP-25" } ]
cron command in Linux with Examples
22 Jan, 2021 The cron is a software utility, offered by a Linux-like operating system that automates the scheduled task at a predetermined time. It is a daemon process, which runs as a background process and performs the specified operations at the predefined time when a certain event or condition is triggered without the intervention of a user. Dealing with a repeated task frequently is an intimidating task for the system administrator and thus he can schedule such processes to run automatically in the background at regular intervals of time by creating a list of those commands using cron. It enables the users to execute the scheduled task on a regular basis unobtrusively like doing the backup every day at midnight, scheduling updates on a weekly basis, synchronizing the files at some regular interval. Cron checks for the scheduled job recurrently and when the scheduled time fields match the current time fields, the scheduled commands are executed. It is started automatically from /etc/init.d on entering multi-user run levels. Syntax: cron [-f] [-l] [-L loglevel] Options: -f : Used to stay in foreground mode, and don’t daemonize. -l : This will enable the LSB compliant names for /etc/cron.d files. -n : Used to add the FQDN in the subject when sending mails. -L loglevel : This option will tell the cron what to log about the jobs with the following values: 1 : It will log the start of all cron jobs.2 : It will log the end of all cron jobs.4 : It will log all the failed jobs. Here the exit status will not equal to zero.8 : It will log the process number of all the cron jobs. 1 : It will log the start of all cron jobs. 2 : It will log the end of all cron jobs. 4 : It will log all the failed jobs. Here the exit status will not equal to zero. 8 : It will log the process number of all the cron jobs. The crontab (abbreviation for “cron table”) is list of commands to execute the scheduled tasks at specific time. It allows the user to add, remove or modify the scheduled tasks. The crontab command syntax has six fields separated by space where the first five represent the time to run the task and the last one is for the command. Minute (holds a value between 0-59) Hour (holds value between 0-23) Day of Month (holds value between 1-31) Month of the year (holds a value between 1-12 or Jan-Dec, the first three letters of the month’s name shall be used) Day of the week (holds a value between 0-6 or Sun-Sat, here also first three letters of the day shall be used) Command The rules which govern the format of date and time field as follows: When any of the first five fields are set to an asterisk(*), it stands for all the values of the field. For instance, to execute a command daily, we can put an asterisk(*) in the week’s field. One can also use a range of numbers, separated with a hyphen(-) in the time and date field to include more than one contiguous value but not all the values of the field. For example, we can use the 7-10 to run a command from July to October. The comma (, ) operator is used to include a list of numbers which may or may not be consecutive. For example, “1, 3, 5” in the weeks’ field signifies execution of a command every Monday, Wednesday, and Friday. A slash character(/) is included to skip given number of values. For instance, “*/4” in the hour’s field specifies ‘every 4 hours’ which is equivalent to 0, 4, 8, 12, 16, 20. Permitting users to run cron jobs: The user must be listed in this file to be able to run cron jobs if the file exists. /etc/cron.allow If the cron.allow file doesn’t exist but the cron.deny file exists, then a user must not be listed in this file to be able to run the cron job. /etc/cron.deny Note: If neither of these files exists then only the superuser(system administrator) will be allowed to use a given command. Sample commands: Run /home/folder/gfg-code.sh every hour, from 9:00 AM to 6:00 PM, everyday. 00 09-18 * * * /home/folder/gfg-code.sh Run /usr/local/bin/backup at 11:30 PM, every weekday. 30 23 * * Mon, Tue, Wed, Thu, Fri /usr/local/bin/backup Run sample-command.sh at 07:30, 09:30, 13:30 and 15:30. 30 07, 09, 13, 15 * * * sample-command.sh The following points should be remembered while working with cron: Have a source version control to track and maintain the changes to the cron expressions. Organize the scheduled jobs based on their importance or the frequency and group them by their action or the time range. Test the scheduled job by having a high frequency initially. Do not write complex code or several pipings and redirection in the cron expression directly. Instead, write them to a script and schedule the script to the cron tab. Use aliases when the same set of commands are frequently repeated. Avoid running commands or scripts through cron as a root user. Aman884036 linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples Tail command in Linux with examples Conditional Statements | Shell Script Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C echo command in Linux with Examples Cat command in Linux with examples touch command in Linux with Examples chown command in Linux with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jan, 2021" }, { "code": null, "e": 1092, "s": 52, "text": "The cron is a software utility, offered by a Linux-like operating system that automates the scheduled task at a predetermined time. It is a daemon process, which runs as a background process and performs the specified operations at the predefined time when a certain event or condition is triggered without the intervention of a user. Dealing with a repeated task frequently is an intimidating task for the system administrator and thus he can schedule such processes to run automatically in the background at regular intervals of time by creating a list of those commands using cron. It enables the users to execute the scheduled task on a regular basis unobtrusively like doing the backup every day at midnight, scheduling updates on a weekly basis, synchronizing the files at some regular interval. Cron checks for the scheduled job recurrently and when the scheduled time fields match the current time fields, the scheduled commands are executed. It is started automatically from /etc/init.d on entering multi-user run levels. Syntax: " }, { "code": null, "e": 1121, "s": 1092, "text": "cron [-f] [-l] [-L loglevel]" }, { "code": null, "e": 1132, "s": 1121, "text": "Options: " }, { "code": null, "e": 1191, "s": 1132, "text": "-f : Used to stay in foreground mode, and don’t daemonize." }, { "code": null, "e": 1260, "s": 1191, "text": "-l : This will enable the LSB compliant names for /etc/cron.d files." }, { "code": null, "e": 1321, "s": 1260, "text": "-n : Used to add the FQDN in the subject when sending mails." }, { "code": null, "e": 1642, "s": 1321, "text": "-L loglevel : This option will tell the cron what to log about the jobs with the following values: 1 : It will log the start of all cron jobs.2 : It will log the end of all cron jobs.4 : It will log all the failed jobs. Here the exit status will not equal to zero.8 : It will log the process number of all the cron jobs." }, { "code": null, "e": 1686, "s": 1642, "text": "1 : It will log the start of all cron jobs." }, { "code": null, "e": 1728, "s": 1686, "text": "2 : It will log the end of all cron jobs." }, { "code": null, "e": 1810, "s": 1728, "text": "4 : It will log all the failed jobs. Here the exit status will not equal to zero." }, { "code": null, "e": 1867, "s": 1810, "text": "8 : It will log the process number of all the cron jobs." }, { "code": null, "e": 2200, "s": 1867, "text": "The crontab (abbreviation for “cron table”) is list of commands to execute the scheduled tasks at specific time. It allows the user to add, remove or modify the scheduled tasks. The crontab command syntax has six fields separated by space where the first five represent the time to run the task and the last one is for the command. " }, { "code": null, "e": 2236, "s": 2200, "text": "Minute (holds a value between 0-59)" }, { "code": null, "e": 2268, "s": 2236, "text": "Hour (holds value between 0-23)" }, { "code": null, "e": 2308, "s": 2268, "text": "Day of Month (holds value between 1-31)" }, { "code": null, "e": 2425, "s": 2308, "text": "Month of the year (holds a value between 1-12 or Jan-Dec, the first three letters of the month’s name shall be used)" }, { "code": null, "e": 2536, "s": 2425, "text": "Day of the week (holds a value between 0-6 or Sun-Sat, here also first three letters of the day shall be used)" }, { "code": null, "e": 2544, "s": 2536, "text": "Command" }, { "code": null, "e": 2614, "s": 2544, "text": "The rules which govern the format of date and time field as follows: " }, { "code": null, "e": 2807, "s": 2614, "text": "When any of the first five fields are set to an asterisk(*), it stands for all the values of the field. For instance, to execute a command daily, we can put an asterisk(*) in the week’s field." }, { "code": null, "e": 3049, "s": 2807, "text": "One can also use a range of numbers, separated with a hyphen(-) in the time and date field to include more than one contiguous value but not all the values of the field. For example, we can use the 7-10 to run a command from July to October." }, { "code": null, "e": 3260, "s": 3049, "text": "The comma (, ) operator is used to include a list of numbers which may or may not be consecutive. For example, “1, 3, 5” in the weeks’ field signifies execution of a command every Monday, Wednesday, and Friday." }, { "code": null, "e": 3435, "s": 3260, "text": "A slash character(/) is included to skip given number of values. For instance, “*/4” in the hour’s field specifies ‘every 4 hours’ which is equivalent to 0, 4, 8, 12, 16, 20." }, { "code": null, "e": 3471, "s": 3435, "text": "Permitting users to run cron jobs: " }, { "code": null, "e": 3556, "s": 3471, "text": "The user must be listed in this file to be able to run cron jobs if the file exists." }, { "code": null, "e": 3572, "s": 3556, "text": "/etc/cron.allow" }, { "code": null, "e": 3716, "s": 3572, "text": "If the cron.allow file doesn’t exist but the cron.deny file exists, then a user must not be listed in this file to be able to run the cron job." }, { "code": null, "e": 3731, "s": 3716, "text": "/etc/cron.deny" }, { "code": null, "e": 3874, "s": 3731, "text": "Note: If neither of these files exists then only the superuser(system administrator) will be allowed to use a given command. Sample commands: " }, { "code": null, "e": 3950, "s": 3874, "text": "Run /home/folder/gfg-code.sh every hour, from 9:00 AM to 6:00 PM, everyday." }, { "code": null, "e": 3990, "s": 3950, "text": "00 09-18 * * * /home/folder/gfg-code.sh" }, { "code": null, "e": 4044, "s": 3990, "text": "Run /usr/local/bin/backup at 11:30 PM, every weekday." }, { "code": null, "e": 4100, "s": 4044, "text": "30 23 * * Mon, Tue, Wed, Thu, Fri /usr/local/bin/backup" }, { "code": null, "e": 4156, "s": 4100, "text": "Run sample-command.sh at 07:30, 09:30, 13:30 and 15:30." }, { "code": null, "e": 4198, "s": 4156, "text": "30 07, 09, 13, 15 * * * sample-command.sh" }, { "code": null, "e": 4266, "s": 4198, "text": "The following points should be remembered while working with cron: " }, { "code": null, "e": 4355, "s": 4266, "text": "Have a source version control to track and maintain the changes to the cron expressions." }, { "code": null, "e": 4476, "s": 4355, "text": "Organize the scheduled jobs based on their importance or the frequency and group them by their action or the time range." }, { "code": null, "e": 4537, "s": 4476, "text": "Test the scheduled job by having a high frequency initially." }, { "code": null, "e": 4704, "s": 4537, "text": "Do not write complex code or several pipings and redirection in the cron expression directly. Instead, write them to a script and schedule the script to the cron tab." }, { "code": null, "e": 4771, "s": 4704, "text": "Use aliases when the same set of commands are frequently repeated." }, { "code": null, "e": 4834, "s": 4771, "text": "Avoid running commands or scripts through cron as a root user." }, { "code": null, "e": 4845, "s": 4834, "text": "Aman884036" }, { "code": null, "e": 4859, "s": 4845, "text": "linux-command" }, { "code": null, "e": 4879, "s": 4859, "text": "Linux-misc-commands" }, { "code": null, "e": 4886, "s": 4879, "text": "Picked" }, { "code": null, "e": 4897, "s": 4886, "text": "Linux-Unix" }, { "code": null, "e": 4995, "s": 4897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5030, "s": 4995, "text": "tar command in Linux with examples" }, { "code": null, "e": 5066, "s": 5030, "text": "Tail command in Linux with examples" }, { "code": null, "e": 5104, "s": 5066, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 5130, "s": 5104, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5165, "s": 5130, "text": "scp command in Linux with Examples" }, { "code": null, "e": 5203, "s": 5165, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 5239, "s": 5203, "text": "echo command in Linux with Examples" }, { "code": null, "e": 5274, "s": 5239, "text": "Cat command in Linux with examples" }, { "code": null, "e": 5311, "s": 5274, "text": "touch command in Linux with Examples" } ]
Function overloading and return type in C++
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. The function overloading is basically the compile time polymorphism. It checks the function signature. If the signatures are not same, then they can be overloaded. The return type of a function does not create any effect on function overloading. Same function signature with different return type will not be overloaded. Following is the example where same function print() is being used to print different data types #include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void) { printData pd; pd.print(5); // Call print to print integer pd.print(500.263); // Call print to print float pd.print("Hello C++"); // Call print to print character return 0; } Printing int: 5 Printing float: 500.263 Printing character: Hello C++
[ { "code": null, "e": 1342, "s": 1062, "text": "You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type." }, { "code": null, "e": 1663, "s": 1342, "text": "The function overloading is basically the compile time polymorphism. It checks the function signature. If the signatures are not same, then they can be overloaded. The return type of a function does not create any effect on function overloading. Same function signature with different return type will not be overloaded." }, { "code": null, "e": 1760, "s": 1663, "text": "Following is the example where same function print() is being used to print different data types" }, { "code": null, "e": 2298, "s": 1760, "text": "#include <iostream>\nusing namespace std;\nclass printData {\n public:\n void print(int i) {\n cout << \"Printing int: \" << i << endl;\n }\n void print(double f) {\n cout << \"Printing float: \" << f << endl;\n }\n void print(char* c) {\n cout << \"Printing character: \" << c << endl;\n }\n};\nint main(void) {\n printData pd;\n pd.print(5); // Call print to print integer\n pd.print(500.263); // Call print to print float\n pd.print(\"Hello C++\"); // Call print to print character\n return 0;\n}" }, { "code": null, "e": 2368, "s": 2298, "text": "Printing int: 5\nPrinting float: 500.263\nPrinting character: Hello C++" } ]
Live Video Sketching through Webcam using Computer Vision | by Kaushik Jadhav | Towards Data Science
Computer Vision refers to a field of Computer Science that focuses on enabling computers to see, identify and process images in the same way as the human mind does. It is a branch of Artificial Intelligence that allows computer to extract useful features from a set of images, perform the required operations on them and generate the output. This article aims to implement a Computer Vision model that generates a Live Video Sketch of the real time footage of a Webcam. The complete source code for the project is available on my Github repo. Install all the required packages for the project using pip by running the commands given below on Command Prompt: pip install opencv-pythonpip install keraspip install numpypip install matplotlib We will break the implementation process into two parts. The first part consists of defining a function that takes a single frame of the video as input and generates a sketched image frame as output. The Python code for doing this is as follows: import kerasimport cv2import numpy as npimport matplotlibimport cv2import numpy as np# Our sketch generating functiondef sketch(image): # Convert image to grayscale img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Clean up image using Guassian Blur img_gray_blur = cv2.GaussianBlur(img_gray, (5,5), 0) # Extract edges canny_edges = cv2.Canny(img_gray_blur, 30, 60) # Do an invert binarize the image ret, mask = cv2.threshold(canny_edges, 240, 255, cv2.THRESH_BINARY_INV) return mask First, we convert the colored image frames of the video to gray scale. Then, we clean up the image using the GaussianBlur() function of OpenCV. Finally, to generate a sketch of the frame, we extract the canny edges and do an invert binarize operation on the edges. The second part consists of applying the above sketch function recursively to all the frames of the Webcam video. The Python code to do this is as follows: cap = cv2.VideoCapture(0)cap2 = cv2.VideoCapture(1)while True: ret, frame = cap.read() ret1, frame1 = cap2.read() cv2.imshow('Original', (frame)) cv2.imshow('Our Live Sketcher', sketch(frame)) if cv2.waitKey(1) == 13: #13 is the Enter Key break # Release camera and close windowscap.release()cap2.release()cv2.destroyAllWindows() As shown in the above code snippet, initialize two VideoCapture objects: one for displaying Webcam footage and the other for displaying the live video sketch. Create a loop which breaks when someone presses the Enter key. Inside the loop, fetch the frames of both the VideoCapture objects. Pass the original frame to the sketch function and display both the original and sketched frames till the loop breaks. The above figure shows the final result of the model. We can see that the model generates a Live Video Sketch of the Webcam video successfully. Note that video performance differs depending upon your Webcam. To improve performance, you might want to play around with the canny_edges 30,60 and the binarize 240 values in the code. Change them such that it suits your webcam. Furthermore, I encourage the readers of this article to experiment with the code on their own to increase the precision of the model. Feel free to share this article with others if you found it useful. Thank you so much for reading. Feel free to connect with me on other platforms: Github — https://github.com/kaushikjadhav01 LinkedIn — https://www.linkedin.com/in/kaushikjadhav01/ The source code for the entire project is available on my Github repo. Feel free to use it for educational purposes.
[ { "code": null, "e": 513, "s": 171, "text": "Computer Vision refers to a field of Computer Science that focuses on enabling computers to see, identify and process images in the same way as the human mind does. It is a branch of Artificial Intelligence that allows computer to extract useful features from a set of images, perform the required operations on them and generate the output." }, { "code": null, "e": 714, "s": 513, "text": "This article aims to implement a Computer Vision model that generates a Live Video Sketch of the real time footage of a Webcam. The complete source code for the project is available on my Github repo." }, { "code": null, "e": 829, "s": 714, "text": "Install all the required packages for the project using pip by running the commands given below on Command Prompt:" }, { "code": null, "e": 911, "s": 829, "text": "pip install opencv-pythonpip install keraspip install numpypip install matplotlib" }, { "code": null, "e": 968, "s": 911, "text": "We will break the implementation process into two parts." }, { "code": null, "e": 1157, "s": 968, "text": "The first part consists of defining a function that takes a single frame of the video as input and generates a sketched image frame as output. The Python code for doing this is as follows:" }, { "code": null, "e": 1688, "s": 1157, "text": "import kerasimport cv2import numpy as npimport matplotlibimport cv2import numpy as np# Our sketch generating functiondef sketch(image): # Convert image to grayscale img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Clean up image using Guassian Blur img_gray_blur = cv2.GaussianBlur(img_gray, (5,5), 0) # Extract edges canny_edges = cv2.Canny(img_gray_blur, 30, 60) # Do an invert binarize the image ret, mask = cv2.threshold(canny_edges, 240, 255, cv2.THRESH_BINARY_INV) return mask" }, { "code": null, "e": 1953, "s": 1688, "text": "First, we convert the colored image frames of the video to gray scale. Then, we clean up the image using the GaussianBlur() function of OpenCV. Finally, to generate a sketch of the frame, we extract the canny edges and do an invert binarize operation on the edges." }, { "code": null, "e": 2109, "s": 1953, "text": "The second part consists of applying the above sketch function recursively to all the frames of the Webcam video. The Python code to do this is as follows:" }, { "code": null, "e": 2468, "s": 2109, "text": "cap = cv2.VideoCapture(0)cap2 = cv2.VideoCapture(1)while True: ret, frame = cap.read() ret1, frame1 = cap2.read() cv2.imshow('Original', (frame)) cv2.imshow('Our Live Sketcher', sketch(frame)) if cv2.waitKey(1) == 13: #13 is the Enter Key break # Release camera and close windowscap.release()cap2.release()cv2.destroyAllWindows()" }, { "code": null, "e": 2877, "s": 2468, "text": "As shown in the above code snippet, initialize two VideoCapture objects: one for displaying Webcam footage and the other for displaying the live video sketch. Create a loop which breaks when someone presses the Enter key. Inside the loop, fetch the frames of both the VideoCapture objects. Pass the original frame to the sketch function and display both the original and sketched frames till the loop breaks." }, { "code": null, "e": 3021, "s": 2877, "text": "The above figure shows the final result of the model. We can see that the model generates a Live Video Sketch of the Webcam video successfully." }, { "code": null, "e": 3251, "s": 3021, "text": "Note that video performance differs depending upon your Webcam. To improve performance, you might want to play around with the canny_edges 30,60 and the binarize 240 values in the code. Change them such that it suits your webcam." }, { "code": null, "e": 3385, "s": 3251, "text": "Furthermore, I encourage the readers of this article to experiment with the code on their own to increase the precision of the model." }, { "code": null, "e": 3484, "s": 3385, "text": "Feel free to share this article with others if you found it useful. Thank you so much for reading." }, { "code": null, "e": 3533, "s": 3484, "text": "Feel free to connect with me on other platforms:" }, { "code": null, "e": 3577, "s": 3533, "text": "Github — https://github.com/kaushikjadhav01" }, { "code": null, "e": 3633, "s": 3577, "text": "LinkedIn — https://www.linkedin.com/in/kaushikjadhav01/" } ]
HTTP headers | Expect-CT - GeeksforGeeks
19 Nov, 2019 The HTTP Expect-CT header is a response-type header that prevents the usage of wrongly issued certificates for a site and makes sure that they do not go unnoticed and it also allows sites to decide on reporting or enforcement of Certificate Transparency requirements. Syntax: Expect-CT max-age=<age>, enforce, report-uri="<uri>" Note: Enforce and report-uri are optional directives. Directives: The HTTP Expect-CT header accepts three directives mentioned above and described below: max-age:<age>: This directive tells the number of seconds for which the user should consider the Expect-CT host(from whom the message was received) after the reception of the Expect-CT header. enforce: It is an optional directive which prompts the user to refuse further connections which do not comply with the Certificate Transparency(CT) policy and also enforces the policy. report-uri:<uri>: It is an optional directive that describes the URL where the user can report the failure of the Expect-CT header. Examples: In this example, the Certificate Transparency is enforced for 12 hours and the reports are made to geeksforgeeks.org .Expect-CT: max-age=43200, enforce, report-uri="https://geeksforgeeks.org/report" Expect-CT: max-age=43200, enforce, report-uri="https://geeksforgeeks.org/report" In this example, the Certificate Transparency is enforced for an hour.Expect-CT: max-age=3600, enforceTo check the Expect-CT in action go to Inspect Element -> Network check the response header for Expect-CT like below, Expect-CT is highlighted.Supported browsers: The browsers are compatible with HTTP Expect-CT header are listed below:Google ChromeOperaMy Personal Notes arrow_drop_upSave Expect-CT: max-age=3600, enforce To check the Expect-CT in action go to Inspect Element -> Network check the response header for Expect-CT like below, Expect-CT is highlighted. Supported browsers: The browsers are compatible with HTTP Expect-CT header are listed below: Google Chrome Opera HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React How to redirect to another page in ReactJS ? Remove elements from a JavaScript Array JQuery | Set the value of an input text field How to execute PHP code using command line ?
[ { "code": null, "e": 24746, "s": 24718, "text": "\n19 Nov, 2019" }, { "code": null, "e": 25014, "s": 24746, "text": "The HTTP Expect-CT header is a response-type header that prevents the usage of wrongly issued certificates for a site and makes sure that they do not go unnoticed and it also allows sites to decide on reporting or enforcement of Certificate Transparency requirements." }, { "code": null, "e": 25022, "s": 25014, "text": "Syntax:" }, { "code": null, "e": 25075, "s": 25022, "text": "Expect-CT max-age=<age>, enforce, report-uri=\"<uri>\"" }, { "code": null, "e": 25129, "s": 25075, "text": "Note: Enforce and report-uri are optional directives." }, { "code": null, "e": 25229, "s": 25129, "text": "Directives: The HTTP Expect-CT header accepts three directives mentioned above and described below:" }, { "code": null, "e": 25422, "s": 25229, "text": "max-age:<age>: This directive tells the number of seconds for which the user should consider the Expect-CT host(from whom the message was received) after the reception of the Expect-CT header." }, { "code": null, "e": 25607, "s": 25422, "text": "enforce: It is an optional directive which prompts the user to refuse further connections which do not comply with the Certificate Transparency(CT) policy and also enforces the policy." }, { "code": null, "e": 25739, "s": 25607, "text": "report-uri:<uri>: It is an optional directive that describes the URL where the user can report the failure of the Expect-CT header." }, { "code": null, "e": 25749, "s": 25739, "text": "Examples:" }, { "code": null, "e": 25948, "s": 25749, "text": "In this example, the Certificate Transparency is enforced for 12 hours and the reports are made to geeksforgeeks.org .Expect-CT: max-age=43200, enforce, report-uri=\"https://geeksforgeeks.org/report\"" }, { "code": null, "e": 26029, "s": 25948, "text": "Expect-CT: max-age=43200, enforce, report-uri=\"https://geeksforgeeks.org/report\"" }, { "code": null, "e": 26420, "s": 26029, "text": "In this example, the Certificate Transparency is enforced for an hour.Expect-CT: max-age=3600, enforceTo check the Expect-CT in action go to Inspect Element -> Network check the response header for Expect-CT like below, Expect-CT is highlighted.Supported browsers: The browsers are compatible with HTTP Expect-CT header are listed below:Google ChromeOperaMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26453, "s": 26420, "text": "Expect-CT: max-age=3600, enforce" }, { "code": null, "e": 26597, "s": 26453, "text": "To check the Expect-CT in action go to Inspect Element -> Network check the response header for Expect-CT like below, Expect-CT is highlighted." }, { "code": null, "e": 26690, "s": 26597, "text": "Supported browsers: The browsers are compatible with HTTP Expect-CT header are listed below:" }, { "code": null, "e": 26704, "s": 26690, "text": "Google Chrome" }, { "code": null, "e": 26710, "s": 26704, "text": "Opera" }, { "code": null, "e": 26723, "s": 26710, "text": "HTTP-headers" }, { "code": null, "e": 26730, "s": 26723, "text": "Picked" }, { "code": null, "e": 26747, "s": 26730, "text": "Web Technologies" }, { "code": null, "e": 26845, "s": 26747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26887, "s": 26845, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26930, "s": 26887, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26975, "s": 26930, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27036, "s": 26975, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27094, "s": 27036, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27166, "s": 27094, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27211, "s": 27166, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27251, "s": 27211, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27297, "s": 27251, "text": "JQuery | Set the value of an input text field" } ]
H2 Database - JDBC Connection
H2 is a JAVA database. We can interact with this database by using JDBC. In this chapter, we will see how to create a JDBC connection with H2 database and the CRUD operations with the H2 database. Generally, there are five steps to create a JDBC connection. Step 1 − Registering the JDBC database driver. Class.forName ("org.h2.Driver"); Step 2 − Opening the connection. Connection conn = DriverManager.getConnection ("jdbc:h2:~/test", "sa",""); Step 3 − Creating a statement. Statement st = conn.createStatement(); Step 4 − Executing a statement and receiving Resultset. Stmt.executeUpdate("sql statement"); Step 5 − Closing a connection. conn.close(); Before moving on to create a full program, we need to add h2-1.4.192.jar file to CLASSPATH. We can get this jar from the folder C:\Program Files (x86)\H2\bin. In this example, we will write a program for create table. Consider a table named Registration having the following fields. Following is an example program named H2jdbcCreateDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcCreateDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 3: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); System.out.println("Created table in given database..."); // STEP 4: Clean-up environment stmt.close(); conn.close(); } catch(SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try{ if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } //end finally try } //end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcCreateDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcCreateDemo.java \>java H2jdbcCreateDemo The above command produces the following output. Connecting to database... Creating table in given database... Created table in given database... Goodbye! After this execution, we can check the table created using the H2 SQL interface. In this example, we will write a program for inserting records. Let us insert the following records into the table Registration. Following is an example program named H2jdbcInsertDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcInsertDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println("Connected database successfully..."); // STEP 3: Execute a query stmt = conn.createStatement(); String sql = "INSERT INTO Registration " + "VALUES (100, 'Zara', 'Ali', 18)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz', 'Fatma', 25)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES (102, 'Zaid', 'Khan', 30)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES(103, 'Sumit', 'Mittal', 28)"; stmt.executeUpdate(sql); System.out.println("Inserted records into the table..."); // STEP 4: Clean-up environment stmt.close(); conn.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcInsertDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcInsertDemo.java \>java H2jdbcInsertDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... Inserted records into the table... Goodbye! In this example, we will write a program for reading records. Let us try to read all records from the table Registration. Following is an example program named H2jdbcRecordDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcReadDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // STEP 3: Execute a query System.out.println("Connected database successfully..."); stmt = conn.createStatement(); String sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); // STEP 4: Extract data from result set while(rs.next()) { // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } // STEP 5: Clean-up environment rs.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcReadDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcReadDemo.java \>java H2jdbcReadDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! In this example, we will write a program to update records. Let us try to read all records from the table Registration. Following is an example program named H2jdbcUpdateDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcUpdateDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to a database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // STEP 3: Execute a query System.out.println("Connected database successfully..."); stmt = conn.createStatement(); String sql = "UPDATE Registration " + "SET age = 30 WHERE id in (100, 101)"; stmt.executeUpdate(sql); // Now you can extract all the records // to see the updated records sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcUpdateDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcUpdateDemo.java \>java H2jdbcUpdateDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... ID: 100, Age: 30, First: Zara, Last: Ali ID: 101, Age: 30, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! In this example, we will write a program to delete records. Let us try to read all records from the table Registration. Following is an example program named H2jdbcDeleteDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcDeleteDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // STEP 3: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "DELETE FROM Registration " + "WHERE id = 101"; stmt.executeUpdate(sql); // Now you can extract all the records // to see the remaining records sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcDeleteDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcDeleteDemo.java \>java H2jdbcDeleteDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... ID: 100, Age: 30, First: Zara, Last: Ali ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! 14 Lectures 1 hours Mahesh Kumar 100 Lectures 9.5 hours Hari Om Singh 108 Lectures 8 hours Pavan Lalwani 10 Lectures 1 hours Deepti Trivedi 20 Lectures 2 hours Deepti Trivedi 14 Lectures 1 hours Deepti Trivedi Print Add Notes Bookmark this page
[ { "code": null, "e": 2304, "s": 2107, "text": "H2 is a JAVA database. We can interact with this database by using JDBC. In this chapter, we will see how to create a JDBC connection with H2 database and the CRUD operations with the H2 database." }, { "code": null, "e": 2365, "s": 2304, "text": "Generally, there are five steps to create a JDBC connection." }, { "code": null, "e": 2412, "s": 2365, "text": "Step 1 − Registering the JDBC database driver." }, { "code": null, "e": 2447, "s": 2412, "text": "Class.forName (\"org.h2.Driver\"); \n" }, { "code": null, "e": 2480, "s": 2447, "text": "Step 2 − Opening the connection." }, { "code": null, "e": 2557, "s": 2480, "text": "Connection conn = DriverManager.getConnection (\"jdbc:h2:~/test\", \"sa\",\"\"); \n" }, { "code": null, "e": 2588, "s": 2557, "text": "Step 3 − Creating a statement." }, { "code": null, "e": 2629, "s": 2588, "text": "Statement st = conn.createStatement(); \n" }, { "code": null, "e": 2685, "s": 2629, "text": "Step 4 − Executing a statement and receiving Resultset." }, { "code": null, "e": 2724, "s": 2685, "text": "Stmt.executeUpdate(\"sql statement\"); \n" }, { "code": null, "e": 2755, "s": 2724, "text": "Step 5 − Closing a connection." }, { "code": null, "e": 2771, "s": 2755, "text": "conn.close(); \n" }, { "code": null, "e": 2930, "s": 2771, "text": "Before moving on to create a full program, we need to add h2-1.4.192.jar file to CLASSPATH. We can get this jar from the folder C:\\Program Files (x86)\\H2\\bin." }, { "code": null, "e": 3054, "s": 2930, "text": "In this example, we will write a program for create table. Consider a table named Registration having the following fields." }, { "code": null, "e": 3110, "s": 3054, "text": "Following is an example program named H2jdbcCreateDemo." }, { "code": null, "e": 5130, "s": 3110, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcCreateDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n //STEP 2: Open a connection \n System.out.println(\"Connecting to database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n //STEP 3: Execute a query \n System.out.println(\"Creating table in given database...\"); \n stmt = conn.createStatement(); \n String sql = \"CREATE TABLE REGISTRATION \" + \n \"(id INTEGER not NULL, \" + \n \" first VARCHAR(255), \" + \n \" last VARCHAR(255), \" + \n \" age INTEGER, \" + \n \" PRIMARY KEY ( id ))\"; \n stmt.executeUpdate(sql);\n System.out.println(\"Created table in given database...\"); \n \n // STEP 4: Clean-up environment \n stmt.close(); \n conn.close(); \n } catch(SQLException se) { \n //Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n //Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n //finally block used to close resources \n try{ \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se){ \n se.printStackTrace(); \n } //end finally try \n } //end try \n System.out.println(\"Goodbye!\");\n } \n}" }, { "code": null, "e": 5278, "s": 5130, "text": "Save the above program into H2jdbcCreateDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 5335, "s": 5278, "text": "\\>javac H2jdbcCreateDemo.java \n\\>java H2jdbcCreateDemo \n" }, { "code": null, "e": 5384, "s": 5335, "text": "The above command produces the following output." }, { "code": null, "e": 5494, "s": 5384, "text": "Connecting to database... \nCreating table in given database... \nCreated table in given database... \nGoodbye!\n" }, { "code": null, "e": 5575, "s": 5494, "text": "After this execution, we can check the table created using the H2 SQL interface." }, { "code": null, "e": 5704, "s": 5575, "text": "In this example, we will write a program for inserting records. Let us insert the following records into the table Registration." }, { "code": null, "e": 5760, "s": 5704, "text": "Following is an example program named H2jdbcInsertDemo." }, { "code": null, "e": 8034, "s": 5760, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcInsertDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try{\n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to a selected database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n System.out.println(\"Connected database successfully...\"); \n \n // STEP 3: Execute a query \n stmt = conn.createStatement(); \n String sql = \"INSERT INTO Registration \" + \"VALUES (100, 'Zara', 'Ali', 18)\"; \n \n stmt.executeUpdate(sql); \n sql = \"INSERT INTO Registration \" + \"VALUES (101, 'Mahnaz', 'Fatma', 25)\"; \n \n stmt.executeUpdate(sql); \n sql = \"INSERT INTO Registration \" + \"VALUES (102, 'Zaid', 'Khan', 30)\"; \n \n stmt.executeUpdate(sql); \n sql = \"INSERT INTO Registration \" + \"VALUES(103, 'Sumit', 'Mittal', 28)\"; \n \n stmt.executeUpdate(sql); \n System.out.println(\"Inserted records into the table...\"); \n \n // STEP 4: Clean-up environment \n stmt.close(); \n conn.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try {\n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try \n } // end try \n System.out.println(\"Goodbye!\"); \n } \n}" }, { "code": null, "e": 8182, "s": 8034, "text": "Save the above program into H2jdbcInsertDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 8239, "s": 8182, "text": "\\>javac H2jdbcInsertDemo.java \n\\>java H2jdbcInsertDemo \n" }, { "code": null, "e": 8288, "s": 8239, "text": "The above command produces the following output." }, { "code": null, "e": 8409, "s": 8288, "text": "Connecting to a selected database... \nConnected database successfully... \nInserted records into the table... \nGoodbye! \n" }, { "code": null, "e": 8531, "s": 8409, "text": "In this example, we will write a program for reading records. Let us try to read all records from the table Registration." }, { "code": null, "e": 8587, "s": 8531, "text": "Following is an example program named H2jdbcRecordDemo." }, { "code": null, "e": 10939, "s": 8587, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcReadDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n // STEP 3: Execute a query \n System.out.println(\"Connected database successfully...\"); \n stmt = conn.createStatement(); \n String sql = \"SELECT id, first, last, age FROM Registration\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n // STEP 4: Extract data from result set \n while(rs.next()) { \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n int age = rs.getInt(\"age\"); \n String first = rs.getString(\"first\"); \n String last = rs.getString(\"last\"); \n \n // Display values \n System.out.print(\"ID: \" + id); \n System.out.print(\", Age: \" + age); \n System.out.print(\", First: \" + first); \n System.out.println(\", Last: \" + last); \n } \n // STEP 5: Clean-up environment \n rs.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try { \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try \n } // end try \n System.out.println(\"Goodbye!\"); \n } \n}" }, { "code": null, "e": 11085, "s": 10939, "text": "Save the above program into H2jdbcReadDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 11138, "s": 11085, "text": "\\>javac H2jdbcReadDemo.java \n\\>java H2jdbcReadDemo \n" }, { "code": null, "e": 11187, "s": 11138, "text": "The above command produces the following output." }, { "code": null, "e": 11448, "s": 11187, "text": "Connecting to a selected database... \nConnected database successfully... \nID: 100, Age: 18, First: Zara, Last: Ali \nID: 101, Age: 25, First: Mahnaz, Last: Fatma \nID: 102, Age: 30, First: Zaid, Last: Khan \nID: 103, Age: 28, First: Sumit, Last: Mittal \nGoodbye!\n" }, { "code": null, "e": 11568, "s": 11448, "text": "In this example, we will write a program to update records. Let us try to read all records from the table Registration." }, { "code": null, "e": 11624, "s": 11568, "text": "Following is an example program named H2jdbcUpdateDemo." }, { "code": null, "e": 14106, "s": 11624, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcUpdateDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to a database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n // STEP 3: Execute a query \n System.out.println(\"Connected database successfully...\"); \n stmt = conn.createStatement(); \n String sql = \"UPDATE Registration \" + \"SET age = 30 WHERE id in (100, 101)\"; \n stmt.executeUpdate(sql); \n \n // Now you can extract all the records \n // to see the updated records \n sql = \"SELECT id, first, last, age FROM Registration\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n while(rs.next()){ \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n int age = rs.getInt(\"age\"); \n String first = rs.getString(\"first\"); \n String last = rs.getString(\"last\"); \n \n // Display values \n System.out.print(\"ID: \" + id); \n System.out.print(\", Age: \" + age); \n System.out.print(\", First: \" + first); \n System.out.println(\", Last: \" + last); \n } \n rs.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try { \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try \n } // end try \n System.out.println(\"Goodbye!\"); \n } \n} " }, { "code": null, "e": 14254, "s": 14106, "text": "Save the above program into H2jdbcUpdateDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 14311, "s": 14254, "text": "\\>javac H2jdbcUpdateDemo.java \n\\>java H2jdbcUpdateDemo \n" }, { "code": null, "e": 14360, "s": 14311, "text": "The above command produces the following output." }, { "code": null, "e": 14621, "s": 14360, "text": "Connecting to a selected database... \nConnected database successfully... \nID: 100, Age: 30, First: Zara, Last: Ali \nID: 101, Age: 30, First: Mahnaz, Last: Fatma \nID: 102, Age: 30, First: Zaid, Last: Khan \nID: 103, Age: 28, First: Sumit, Last: Mittal \nGoodbye!\n" }, { "code": null, "e": 14741, "s": 14621, "text": "In this example, we will write a program to delete records. Let us try to read all records from the table Registration." }, { "code": null, "e": 14797, "s": 14741, "text": "Following is an example program named H2jdbcDeleteDemo." }, { "code": null, "e": 17259, "s": 14797, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcDeleteDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n // STEP 3: Execute a query\n System.out.println(\"Creating table in given database...\"); \n stmt = conn.createStatement(); \n String sql = \"DELETE FROM Registration \" + \"WHERE id = 101\"; \n stmt.executeUpdate(sql); \n \n // Now you can extract all the records \n // to see the remaining records \n sql = \"SELECT id, first, last, age FROM Registration\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n while(rs.next()){ \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n int age = rs.getInt(\"age\"); \n String first = rs.getString(\"first\"); \n String last = rs.getString(\"last\"); \n \n // Display values \n System.out.print(\"ID: \" + id); \n System.out.print(\", Age: \" + age); \n System.out.print(\", First: \" + first); \n System.out.println(\", Last: \" + last); \n } \n rs.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try { \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try\n } // end try \n System.out.println(\"Goodbye!\"); \n } \n}" }, { "code": null, "e": 17407, "s": 17259, "text": "Save the above program into H2jdbcDeleteDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 17463, "s": 17407, "text": "\\>javac H2jdbcDeleteDemo.java \n\\>java H2jdbcDeleteDemo\n" }, { "code": null, "e": 17512, "s": 17463, "text": "The above command produces the following output." }, { "code": null, "e": 17728, "s": 17512, "text": "Connecting to a selected database... \nConnected database successfully... \nID: 100, Age: 30, First: Zara, Last: Ali \nID: 102, Age: 30, First: Zaid, Last: Khan \nID: 103, Age: 28, First: Sumit, Last: Mittal \nGoodbye! \n" }, { "code": null, "e": 17761, "s": 17728, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 17775, "s": 17761, "text": " Mahesh Kumar" }, { "code": null, "e": 17811, "s": 17775, "text": "\n 100 Lectures \n 9.5 hours \n" }, { "code": null, "e": 17826, "s": 17811, "text": " Hari Om Singh" }, { "code": null, "e": 17860, "s": 17826, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 17875, "s": 17860, "text": " Pavan Lalwani" }, { "code": null, "e": 17908, "s": 17875, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 17924, "s": 17908, "text": " Deepti Trivedi" }, { "code": null, "e": 17957, "s": 17924, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 17973, "s": 17957, "text": " Deepti Trivedi" }, { "code": null, "e": 18006, "s": 17973, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 18022, "s": 18006, "text": " Deepti Trivedi" }, { "code": null, "e": 18029, "s": 18022, "text": " Print" }, { "code": null, "e": 18040, "s": 18029, "text": " Add Notes" } ]
How to Count Occurrences of Each Character in String in Android?
This example demonstrates How to Count Occurrences of Each Character in String in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> <TextView android:id = "@+id/textview" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken name when user click on button, it will check occurrence of letter in string and gives result in textview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class MainActivity extends AppCompatActivity { EditText name; HashMap<Character,Integer> charCountMap; TextView textview; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.name); textview = findViewById(R.id.textview); charCountMap = new HashMap<>(); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { char[] strArray = name.getText().toString().toCharArray(); for(char charItem:strArray) { if(charCountMap.containsKey(charItem)) { charCountMap.put(charItem,charCountMap.get(charItem)+1); } else { charCountMap.put(charItem,1); } } textview.setText(charCountMap.toString()); Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { name.setError("Enter NAME"); } } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result, we are getting number of occurance of characters in textview. Click here to download the project code
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates How to Count Occurrences of Each Character in String in Android." }, { "code": null, "e": 1282, "s": 1153, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2301, "s": 1347, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <TextView\n android:id = \"@+id/textview\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 2441, "s": 2301, "text": "In the above code, we have taken name when user click on button, it will check occurrence of letter in string and gives result in textview." }, { "code": null, "e": 2498, "s": 2441, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4165, "s": 2498, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Set;\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n HashMap<Character,Integer> charCountMap;\n TextView textview;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n textview = findViewById(R.id.textview);\n charCountMap = new HashMap<>();\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n char[] strArray = name.getText().toString().toCharArray();\n for(char charItem:strArray) {\n if(charCountMap.containsKey(charItem)) {\n charCountMap.put(charItem,charCountMap.get(charItem)+1);\n } else {\n charCountMap.put(charItem,1);\n }\n }\n textview.setText(charCountMap.toString());\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 4512, "s": 4165, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4595, "s": 4512, "text": "In the above result, we are getting number of occurance of characters in textview." }, { "code": null, "e": 4635, "s": 4595, "text": "Click here to download the project code" } ]
The Top Data Science Datasets Right Now | Towards Data Science
IntroductionKaggleDatasetsSummaryReferences Introduction Kaggle Datasets Summary References Over a certain amount of time, you might notice that there are similar datasets being utilized in data science blogs, undergraduate studies, graduate courses, and online learning. These datasets can sometimes reflect the current events happening in the world or can be general, yet extremely popular datasets used for practicing and showcasing data science techniques and processes. The most important aspect of these datasets is that they are ultimately used to promote the greater good by bringing together intelligent minds to solve a pressing issue. There are several sites where datasets can be housed, but I find myself going to the same one — that is Kaggle. This platform offers countless datasets and ranks them by trending metrics. I will be discussing four of the top 10 data science datasets right now. As data becomes more easily obtainable, it is crucial to be aware that with this data there becomes an even bigger focus on what you do with it. These datasets highlight certain call-to-actions, tasks, and inspirations, so if you are unsure of how to handle the data, this part of the dataset information can be quite useful. Kaggle [2] is a platform for data analysis, data scientists, and machine learning engineers that allow for collaboration of solving problems, competing, and overall, learning from one another. At the time that this article is written, there are nearly 46,000 datasets on Kaggle. You can filter the datasets by ‘Hottest’, ‘Most Votes’, ‘New’, ‘Updated’, and ‘Usability’. The datasets I will be describing in this article are sorted by the ‘Hottest’ filter and consist of four of the top 10 datasets. Below, I will highlight names, descriptions, and facts about four of the most popular datasets on Kaggle. Some datasets also have call-to-actions, tasks, inspiration, and prizes. Of course, in these unprecedented times, the top dataset is pertaining to COVID-19. COVID-19 Open Research Dataset Challenge (CORD-19) [3] Description — This dataset has around 7,900 votes. The main purpose of the dataset is to be utilized as an artificial intelligence (AI) challenge with AI2, CZI, MSR, Georgetown, as well as NIH & The White House. This open dataset is in response to the COVID-19 pandemic consisting of nearly 15 GB of data. There are about 17 tasks associated with this dataset. An example of a task would be ‘What do we know about COVID-19 risk factors?’. It is recommended that data scientists use this dataset with natural language processing and AI techniques to ultimately serve as support in fighting this prevalent disease. This reason alone is what separates Kaggle from other dataset websites — the website encourages people from different backgrounds to come together to fight a pressing cause. As with the description, there are also other key features of a dataset, including the ‘Call to Action’ and ‘Prizes’. Call to Action — Creating text and data mining tools from posing scientific questions with the use of data science. Prizes — $1,000 per task award. Daily Power Generation in India (2017–2020) [4] Description — This dataset describes the electricity of India from the years 2017–2020. It consists of 265 KB. The dataset context mentions that India has been apart of rapid growth in electricity from nearly 35 years ago, and in turn, has shown an increase in the economy, exports, infrastructure, and household incomes. The main tags include computing, education, news, energy, renewable energy, and research. The inspiration of the dataset is to discover how data science can impact renewable and non-renewable energy sources in India. World Happiness Report up to 2020 [5] Description — This unique dataset includes features over financial matters, brain research, national insights, and wellbeing. The exact factors are: GDP per capitaHealth Life Expectancy Social supportFreedom to make life choicesGenerosityCorruption PerceptionResidual error Composed of about 116 KB, this dataset has six separate CSVs including respective years of 2015, 2016, 2017, 2018, 2019, and 2020. There is one task associated with this dataset: ‘Compare countries by happiness and other human metrics’. The goal of this dataset can ultimately be up to you, as with any dataset. It serves as a different approach to quantifying happiness. Malaria Dataset [6] Similar to the COVID-19 dataset, this data can serve to provide support to a pressing health topic that is inhibiting in several countries. The good news, according to the context of this dataset, is that Malaria is preventable and curable. The features in this 212 KB sized dataset include, but are not limited to: country, year, and the number of cases. There are three CSVs including: reported_numbers.csv, estiamted_numbers.csv, and incidenceper100popat_risk.csv. The one task of this dataset is to ‘Explore whether the no. of cases of malaria increases every year?’. All in all, these datasets are just some of the most popular datasets on the prominent platform, Kaggle. There are thousands more, but these are some of the most voted and relevant datasets right now. The datasets surround topics of health mainly with COVID-19, power/electricity, happiness, and Malaria. To find out more information with detailed features/columns, source of data, as well as examples of how to use the dataset with code and visualizations, check out the respective links attached to each title of the dataset. I hope you found this article interesting and useful. Thank you for reading! [1] Photo by Patrick Assalé on Unsplash, (March 19, 2020) [2] Kaggle, Kaggle Datasets, (2020) [3] Kaggle, COVID-19 Open Research Dataset Challenge (CORD-19), (2020) [4] Kaggle, Daily Power Generation in India (2017–2020), (2020) [5] Kaggle, World Happiness Report up to 2020, (2020) [6] Kagle, Malaria Dataset, (2020) [7] Photo by Mika Baumeister on Unsplash, (2018)
[ { "code": null, "e": 216, "s": 172, "text": "IntroductionKaggleDatasetsSummaryReferences" }, { "code": null, "e": 229, "s": 216, "text": "Introduction" }, { "code": null, "e": 236, "s": 229, "text": "Kaggle" }, { "code": null, "e": 245, "s": 236, "text": "Datasets" }, { "code": null, "e": 253, "s": 245, "text": "Summary" }, { "code": null, "e": 264, "s": 253, "text": "References" }, { "code": null, "e": 1079, "s": 264, "text": "Over a certain amount of time, you might notice that there are similar datasets being utilized in data science blogs, undergraduate studies, graduate courses, and online learning. These datasets can sometimes reflect the current events happening in the world or can be general, yet extremely popular datasets used for practicing and showcasing data science techniques and processes. The most important aspect of these datasets is that they are ultimately used to promote the greater good by bringing together intelligent minds to solve a pressing issue. There are several sites where datasets can be housed, but I find myself going to the same one — that is Kaggle. This platform offers countless datasets and ranks them by trending metrics. I will be discussing four of the top 10 data science datasets right now." }, { "code": null, "e": 1405, "s": 1079, "text": "As data becomes more easily obtainable, it is crucial to be aware that with this data there becomes an even bigger focus on what you do with it. These datasets highlight certain call-to-actions, tasks, and inspirations, so if you are unsure of how to handle the data, this part of the dataset information can be quite useful." }, { "code": null, "e": 1775, "s": 1405, "text": "Kaggle [2] is a platform for data analysis, data scientists, and machine learning engineers that allow for collaboration of solving problems, competing, and overall, learning from one another. At the time that this article is written, there are nearly 46,000 datasets on Kaggle. You can filter the datasets by ‘Hottest’, ‘Most Votes’, ‘New’, ‘Updated’, and ‘Usability’." }, { "code": null, "e": 1904, "s": 1775, "text": "The datasets I will be describing in this article are sorted by the ‘Hottest’ filter and consist of four of the top 10 datasets." }, { "code": null, "e": 2167, "s": 1904, "text": "Below, I will highlight names, descriptions, and facts about four of the most popular datasets on Kaggle. Some datasets also have call-to-actions, tasks, inspiration, and prizes. Of course, in these unprecedented times, the top dataset is pertaining to COVID-19." }, { "code": null, "e": 2222, "s": 2167, "text": "COVID-19 Open Research Dataset Challenge (CORD-19) [3]" }, { "code": null, "e": 2236, "s": 2222, "text": "Description —" }, { "code": null, "e": 2835, "s": 2236, "text": "This dataset has around 7,900 votes. The main purpose of the dataset is to be utilized as an artificial intelligence (AI) challenge with AI2, CZI, MSR, Georgetown, as well as NIH & The White House. This open dataset is in response to the COVID-19 pandemic consisting of nearly 15 GB of data. There are about 17 tasks associated with this dataset. An example of a task would be ‘What do we know about COVID-19 risk factors?’. It is recommended that data scientists use this dataset with natural language processing and AI techniques to ultimately serve as support in fighting this prevalent disease." }, { "code": null, "e": 3009, "s": 2835, "text": "This reason alone is what separates Kaggle from other dataset websites — the website encourages people from different backgrounds to come together to fight a pressing cause." }, { "code": null, "e": 3127, "s": 3009, "text": "As with the description, there are also other key features of a dataset, including the ‘Call to Action’ and ‘Prizes’." }, { "code": null, "e": 3144, "s": 3127, "text": "Call to Action —" }, { "code": null, "e": 3243, "s": 3144, "text": "Creating text and data mining tools from posing scientific questions with the use of data science." }, { "code": null, "e": 3252, "s": 3243, "text": "Prizes —" }, { "code": null, "e": 3275, "s": 3252, "text": "$1,000 per task award." }, { "code": null, "e": 3323, "s": 3275, "text": "Daily Power Generation in India (2017–2020) [4]" }, { "code": null, "e": 3337, "s": 3323, "text": "Description —" }, { "code": null, "e": 3862, "s": 3337, "text": "This dataset describes the electricity of India from the years 2017–2020. It consists of 265 KB. The dataset context mentions that India has been apart of rapid growth in electricity from nearly 35 years ago, and in turn, has shown an increase in the economy, exports, infrastructure, and household incomes. The main tags include computing, education, news, energy, renewable energy, and research. The inspiration of the dataset is to discover how data science can impact renewable and non-renewable energy sources in India." }, { "code": null, "e": 3900, "s": 3862, "text": "World Happiness Report up to 2020 [5]" }, { "code": null, "e": 3914, "s": 3900, "text": "Description —" }, { "code": null, "e": 4049, "s": 3914, "text": "This unique dataset includes features over financial matters, brain research, national insights, and wellbeing. The exact factors are:" }, { "code": null, "e": 4174, "s": 4049, "text": "GDP per capitaHealth Life Expectancy Social supportFreedom to make life choicesGenerosityCorruption PerceptionResidual error" }, { "code": null, "e": 4546, "s": 4174, "text": "Composed of about 116 KB, this dataset has six separate CSVs including respective years of 2015, 2016, 2017, 2018, 2019, and 2020. There is one task associated with this dataset: ‘Compare countries by happiness and other human metrics’. The goal of this dataset can ultimately be up to you, as with any dataset. It serves as a different approach to quantifying happiness." }, { "code": null, "e": 4566, "s": 4546, "text": "Malaria Dataset [6]" }, { "code": null, "e": 5138, "s": 4566, "text": "Similar to the COVID-19 dataset, this data can serve to provide support to a pressing health topic that is inhibiting in several countries. The good news, according to the context of this dataset, is that Malaria is preventable and curable. The features in this 212 KB sized dataset include, but are not limited to: country, year, and the number of cases. There are three CSVs including: reported_numbers.csv, estiamted_numbers.csv, and incidenceper100popat_risk.csv. The one task of this dataset is to ‘Explore whether the no. of cases of malaria increases every year?’." }, { "code": null, "e": 5666, "s": 5138, "text": "All in all, these datasets are just some of the most popular datasets on the prominent platform, Kaggle. There are thousands more, but these are some of the most voted and relevant datasets right now. The datasets surround topics of health mainly with COVID-19, power/electricity, happiness, and Malaria. To find out more information with detailed features/columns, source of data, as well as examples of how to use the dataset with code and visualizations, check out the respective links attached to each title of the dataset." }, { "code": null, "e": 5743, "s": 5666, "text": "I hope you found this article interesting and useful. Thank you for reading!" }, { "code": null, "e": 5802, "s": 5743, "text": "[1] Photo by Patrick Assalé on Unsplash, (March 19, 2020)" }, { "code": null, "e": 5838, "s": 5802, "text": "[2] Kaggle, Kaggle Datasets, (2020)" }, { "code": null, "e": 5909, "s": 5838, "text": "[3] Kaggle, COVID-19 Open Research Dataset Challenge (CORD-19), (2020)" }, { "code": null, "e": 5973, "s": 5909, "text": "[4] Kaggle, Daily Power Generation in India (2017–2020), (2020)" }, { "code": null, "e": 6027, "s": 5973, "text": "[5] Kaggle, World Happiness Report up to 2020, (2020)" }, { "code": null, "e": 6062, "s": 6027, "text": "[6] Kagle, Malaria Dataset, (2020)" } ]
Split Space Delimited String and Trim Extra Commas and Spaces in JavaScript?
Let’s say the following is our string − var sentence = "My,,,,,,, Name,,,, is John ,,, Smith"; Use regular expression along with split() and join() to remove extra spaces and commas. Following is the code − var sentence = "My,,,,,,, Name,,,, is John ,,, Smith"; console.log("Before removing extra comma and space="+sentence); sentence = sentence.split(/[\s,]+/).join(); console.log("After removing extra comma and space="); console.log(sentence) To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo133.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo133.js Before removing extra comma and space=My,,,,,,, Name,,,, is John ,,, Smith After removing extra comma and space= My,Name,is,John,Smith
[ { "code": null, "e": 1102, "s": 1062, "text": "Let’s say the following is our string −" }, { "code": null, "e": 1157, "s": 1102, "text": "var sentence = \"My,,,,,,, Name,,,, is John ,,, Smith\";" }, { "code": null, "e": 1269, "s": 1157, "text": "Use regular expression along with split() and join() to remove extra spaces and commas.\nFollowing is the code −" }, { "code": null, "e": 1508, "s": 1269, "text": "var sentence = \"My,,,,,,, Name,,,, is John ,,, Smith\";\nconsole.log(\"Before removing extra comma and space=\"+sentence);\nsentence = sentence.split(/[\\s,]+/).join();\nconsole.log(\"After removing extra comma and space=\");\nconsole.log(sentence)" }, { "code": null, "e": 1574, "s": 1508, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1592, "s": 1574, "text": "node fileName.js." }, { "code": null, "e": 1667, "s": 1592, "text": "Here, my file name is demo133.js. This will produce the following output −" }, { "code": null, "e": 1852, "s": 1667, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo133.js\nBefore removing extra comma and space=My,,,,,,, Name,,,, is John ,,, Smith\nAfter removing extra comma and space=\nMy,Name,is,John,Smith" } ]
GATE | Gate IT 2005 | Question 78 - GeeksforGeeks
03 Sep, 2021 Consider the following message M = 1010001101. The cyclic redundancy check (CRC) for this message using the divisor polynomial x5 + x4 + x2 + 1 is : (A) 01110(B) 01011(C) 10101(D) 10110Answer: (A)Explanation: M = 1010001101 Divisor polynomial: 1.x5 +1.x4+0.x3+1.x2+0.x2+1.x0 Divisor polynomial bit= 110101 Bits to be appended to message= (divisor polynomial bits – 1) = 5 Append 5 zeros to message bits, modified message: 101000110100000 Now, divide and XOR the message with divisor polynomial bits. Make resultant reminder to 5 bit again and that is the CRC send along with the message. This explanation has been contributed by Sandeep Pandey. Please visit the following links to learn more on CRC and its calculation: Wikipedia article: Cyclic Redundancy CheckGeeksforGeeks article: Error Detection | Computer NetworksQuiz of this Question ruhelaa48 Gate IT 2005 GATE-Gate IT 2005 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25791, "s": 25763, "text": "\n03 Sep, 2021" }, { "code": null, "e": 25940, "s": 25791, "text": "Consider the following message M = 1010001101. The cyclic redundancy check (CRC) for this message using the divisor polynomial x5 + x4 + x2 + 1 is :" }, { "code": null, "e": 26001, "s": 25940, "text": " (A) 01110(B) 01011(C) 10101(D) 10110Answer: (A)Explanation:" }, { "code": null, "e": 26234, "s": 26001, "text": "M = 1010001101\nDivisor polynomial: 1.x5 +1.x4+0.x3+1.x2+0.x2+1.x0 \nDivisor polynomial bit= 110101\nBits to be appended to message= (divisor polynomial bits – 1) = 5\nAppend 5 zeros to message bits, modified message: 101000110100000\n" }, { "code": null, "e": 26384, "s": 26234, "text": "Now, divide and XOR the message with divisor polynomial bits. Make resultant reminder to 5 bit again and that is the CRC send along with the message." }, { "code": null, "e": 26441, "s": 26384, "text": "This explanation has been contributed by Sandeep Pandey." }, { "code": null, "e": 26516, "s": 26441, "text": "Please visit the following links to learn more on CRC and its calculation:" }, { "code": null, "e": 26638, "s": 26516, "text": "Wikipedia article: Cyclic Redundancy CheckGeeksforGeeks article: Error Detection | Computer NetworksQuiz of this Question" }, { "code": null, "e": 26648, "s": 26638, "text": "ruhelaa48" }, { "code": null, "e": 26661, "s": 26648, "text": "Gate IT 2005" }, { "code": null, "e": 26679, "s": 26661, "text": "GATE-Gate IT 2005" }, { "code": null, "e": 26684, "s": 26679, "text": "GATE" }, { "code": null, "e": 26782, "s": 26684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26816, "s": 26782, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26850, "s": 26816, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26884, "s": 26850, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26917, "s": 26884, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26953, "s": 26917, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26987, "s": 26953, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27023, "s": 26987, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27057, "s": 27023, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27091, "s": 27057, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Python - Poisson Discrete Distribution in Statistics - GeeksforGeeks
10 Jan, 2020 scipy.stats.poisson() is a poisson discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution. Parameters : x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : poisson discrete random variable Code #1 : Creating poisson discrete random variable # importing library from scipy.stats import poisson numargs = poisson .numargs a, b = 0.2, 0.8rv = poisson (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4D865848 Code #2 : poisson discrete variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = poisson .rvs(a, b, size = 10) print ("Random Variates : \n", R) # PDF x = np.linspace(poisson.ppf(0.01, a, b), poisson.ppf(0.99, a, b), 10)R = poisson.ppf(x, 1, 3)print ("\nProbability Distribution : \n", R) Output : Random Variates : [0 0 1 0 1 0 0 1 0 0] Probability Distribution : [ 5. nan nan nan nan nan nan nan nan nan] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.ppf(distribution)) Output : Distribution : [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735 1.95918367 2. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = poisson.ppf(x, a, b) y2 = poisson.pmf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26181, "s": 26153, "text": "\n10 Jan, 2020" }, { "code": null, "e": 26408, "s": 26181, "text": "scipy.stats.poisson() is a poisson discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 26421, "s": 26408, "text": "Parameters :" }, { "code": null, "e": 26673, "s": 26421, "text": "x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 26716, "s": 26673, "text": "Results : poisson discrete random variable" }, { "code": null, "e": 26768, "s": 26716, "text": "Code #1 : Creating poisson discrete random variable" }, { "code": "# importing library from scipy.stats import poisson numargs = poisson .numargs a, b = 0.2, 0.8rv = poisson (a, b) print (\"RV : \\n\", rv) ", "e": 26915, "s": 26768, "text": null }, { "code": null, "e": 26924, "s": 26915, "text": "Output :" }, { "code": null, "e": 27005, "s": 26924, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4D865848\n" }, { "code": null, "e": 27070, "s": 27005, "text": "Code #2 : poisson discrete variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = poisson .rvs(a, b, size = 10) print (\"Random Variates : \\n\", R) # PDF x = np.linspace(poisson.ppf(0.01, a, b), poisson.ppf(0.99, a, b), 10)R = poisson.ppf(x, 1, 3)print (\"\\nProbability Distribution : \\n\", R) ", "e": 27375, "s": 27070, "text": null }, { "code": null, "e": 27384, "s": 27375, "text": "Output :" }, { "code": null, "e": 27500, "s": 27384, "text": "Random Variates : \n [0 0 1 0 1 0 0 1 0 0]\n\nProbability Distribution : \n [ 5. nan nan nan nan nan nan nan nan nan]\n\n" }, { "code": null, "e": 27536, "s": 27500, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.ppf(distribution)) ", "e": 27747, "s": 27536, "text": null }, { "code": null, "e": 27756, "s": 27747, "text": "Output :" }, { "code": null, "e": 28336, "s": 27756, "text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n " }, { "code": null, "e": 28375, "s": 28336, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = poisson.ppf(x, a, b) y2 = poisson.pmf(x, a, b) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 28579, "s": 28375, "text": null }, { "code": null, "e": 28588, "s": 28579, "text": "Output :" }, { "code": null, "e": 28617, "s": 28588, "text": "Python scipy-stats-functions" }, { "code": null, "e": 28630, "s": 28617, "text": "Python-scipy" }, { "code": null, "e": 28637, "s": 28630, "text": "Python" }, { "code": null, "e": 28735, "s": 28637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28753, "s": 28735, "text": "Python Dictionary" }, { "code": null, "e": 28788, "s": 28753, "text": "Read a file line by line in Python" }, { "code": null, "e": 28820, "s": 28788, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28842, "s": 28820, "text": "Enumerate() in Python" }, { "code": null, "e": 28884, "s": 28842, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28914, "s": 28884, "text": "Iterate over a list in Python" }, { "code": null, "e": 28940, "s": 28914, "text": "Python String | replace()" }, { "code": null, "e": 28984, "s": 28940, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29013, "s": 28984, "text": "*args and **kwargs in Python" } ]
C - Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); } The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc. The following example calculates the factorial of a given number using a recursive function − #include <stdio.h> unsigned long long int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; } When the above code is compiled and executed, it produces the following result − Factorial of 12 is 479001600 The following example generates the Fibonacci series for a given number using a recursive function − #include <stdio.h> int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i)); } return 0; } When the above code is compiled and executed, it produces the following result − 0 1 1 2 3 5 8 13 21 34 Print Add Notes Bookmark this page
[ { "code": null, "e": 2298, "s": 2084, "text": "Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function." }, { "code": null, "e": 2395, "s": 2298, "text": "void recursion() {\n recursion(); /* function calls itself */\n}\n\nint main() {\n recursion();\n}" }, { "code": null, "e": 2624, "s": 2395, "text": "The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop." }, { "code": null, "e": 2778, "s": 2624, "text": "Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc." }, { "code": null, "e": 2872, "s": 2778, "text": "The following example calculates the factorial of a given number using a recursive function −" }, { "code": null, "e": 3115, "s": 2872, "text": "#include <stdio.h>\n\nunsigned long long int factorial(unsigned int i) {\n\n if(i <= 1) {\n return 1;\n }\n return i * factorial(i - 1);\n}\n\nint main() {\n int i = 12;\n printf(\"Factorial of %d is %d\\n\", i, factorial(i));\n return 0;\n}" }, { "code": null, "e": 3196, "s": 3115, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3226, "s": 3196, "text": "Factorial of 12 is 479001600\n" }, { "code": null, "e": 3327, "s": 3226, "text": "The following example generates the Fibonacci series for a given number using a recursive function −" }, { "code": null, "e": 3610, "s": 3327, "text": "#include <stdio.h>\n\nint fibonacci(int i) {\n\n if(i == 0) {\n return 0;\n }\n\t\n if(i == 1) {\n return 1;\n }\n return fibonacci(i-1) + fibonacci(i-2);\n}\n\nint main() {\n\n int i;\n\t\n for (i = 0; i < 10; i++) {\n printf(\"%d\\t\\n\", fibonacci(i));\n }\n\t\n return 0;\n}" }, { "code": null, "e": 3691, "s": 3610, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3724, "s": 3691, "text": "0\t\n1\t\n1\t\n2\t\n3\t\n5\t\n8\t\n13\t\n21\t\n34\n" }, { "code": null, "e": 3731, "s": 3724, "text": " Print" }, { "code": null, "e": 3742, "s": 3731, "text": " Add Notes" } ]
Algorithmic Trading using Sentiment Analysis on News Articles | by Jason Yip | Towards Data Science
Well I was supposed to study for my exams but I was very tempted to explore this while I was taking breaks. I realized that I could use elements from my previous projects to work on this. I previously wrote about Automating Social Media Contests with Web Scraping which is relevant to news scraping and I also wrote about Generating Singlish Text Messages where I worked with text data. Isn’t it interesting how it could all overlap? Algo trading automates the trading process in financial markets by rapidly and precisely executing orders based on a set of defined rules. They remove human error (provided the algorithms were developed without them) and they also remove the dangers of acting on emotion. The algorithms that are used in production can be fairly complex and heavily optimized with low-latency systems. I’ll be implementing a very basic strategy (based on trend) on a single stock. Trend-following strategies are generally easy and straightforward to implement using simple technical indicators such as moving averages. The interesting thing that we are going to include in our algo is the qualitative element from news related to the company (ironically acting on emotion). Sentiment Analysis or Opinion Mining refers to the use of NLP, text analysis and computational linguistics to determine subjective information or the emotional state of the writer/subject/topic. It is commonly used in reviews which save businesses a lot of time from manually reading comments. Just like Algorithmic Trading, Sentiment Analysis could also go very deep as a field. Besides just giving a positive/negative sentiment, we could understand how subjective a text is, the intensities of different emotions (excitement, frustration, etc.), how Shakespearean or Trump-like a text could be, and much more. Facebook has recently been facing a lot of backlash and I thought it would be interesting to see how the stock moves with its news sentiment. The idea is pretty straightforward. We crawl the Business Times for any article related to Facebook, mine the texts, get the overall sentiment for each day, and buy 10 shares of its stock if the sentiment increases by 0.5 or sell if it decreases by 0.5. Bear in mind that the sentiment ranges from -1 to 1 with 0 being neutral and we are using the previous day’s sentiment to trade in the current day. Similar to my previous post on web scraping, I used the same idea of extracting URLs from the search page and visiting each article to mine its sentiment for the previous day. The sentiment is stored in a dictionary e.g. {datetime.date(2018,7,5):-0.59,...,} VADER (Valence Aware Dictionary for sEntiment Reasoning) is a pre-built sentiment analysis model included in the NLTK package. It can give both positive/negative (polarity) as well as the strength of the emotion (intensity) of a text. It is rule-based and relies heavily on humans rating texts via Amazon Mechanical Turk — a crowd-sourcing e-platform which utilizes human intelligence to perform tasks that computers are currently unable to do. This literally means that other people have already done the dirty work of building a sentiment lexicon for us. These are words or any textual form of communication generally labelled according to their semantic orientation as either positive or negative) for us. The sentiment score of a text can be obtained by summing up the intensity of each word in the text and then normalizing it. The human raters of Vader used 5 heuristics to analyze the sentiment: Punctuation — I love pizza vs I love pizza!!Capitalization — I’m hungry!! vs I’M HUNGRY!!Degree modifiers (use of intensifiers)— I WANT TO EAT!! VS I REALLY WANT TO EAT!!Conjunctions (shift in sentiment polarity, with later dictating polarity) — I love pizza, but I really hate Pizza Hut (bad review)Preceding Tri-gram (identifying reverse polarity by examining the tri-gram before the lexical feature— Canadian Pizza is not really all that great. Punctuation — I love pizza vs I love pizza!! Capitalization — I’m hungry!! vs I’M HUNGRY!! Degree modifiers (use of intensifiers)— I WANT TO EAT!! VS I REALLY WANT TO EAT!! Conjunctions (shift in sentiment polarity, with later dictating polarity) — I love pizza, but I really hate Pizza Hut (bad review) Preceding Tri-gram (identifying reverse polarity by examining the tri-gram before the lexical feature— Canadian Pizza is not really all that great. VADER however is focused on social media and short texts unlike Financial News which are almost the opposite. I included a chunk in my notebook to update the VADER lexicon with words+sentiments from other sources/lexicons such as the Loughran-McDonald Financial Sentiment Word Lists. With a simple code like this, we could easily get the sentiment from a passage. from nltk.sentiment.vader import SentimentIntensityAnalyzernltk.download('vader_lexicon')sia = SentimentIntensityAnalyzer()polarity_scores(passage)['compound'] Finally, with the use of the backtrader package, we have a convenient framework to backtest and write our trading strategy. I used the Quickstart code in the docs as a base and modified it to include our sentiment scores. I specified the “FB” stock feeds to be pulled from Yahoo Finance, set an initial amount of $100,000, a fixed size of 10 lots per trade, a commission of 0.1%, as well as a simple strategy to buy if the previous day’s sentiment score increases by 0.5 from the last day and sell if it decreases by 0.5. I started out with $100,000 and ended up with $99,742. Haha. Not gonna say anything about that. Okay, well the results were sorta expected because reality is so much more complex than our model. Notice how the trades were executed as the sentiment score swings. The model / I was definitely very stupid actually, we were always behind and executed trades right after the “hype” moments. But you can see where this goes, we could definitely build on the strategy by including more technical indicators or even improve the sentiment analysis by training our own model (could use NLTK) on more relevant Financial News. I hope you all enjoyed this, I was definitely more cautious of the readability and conciseness this time. Please leave comments, feedback and ideas if you have any. I would really appreciate it. Till next time! Link to project repo Discuss further with me on LinkedIn or via [email protected]!
[ { "code": null, "e": 606, "s": 172, "text": "Well I was supposed to study for my exams but I was very tempted to explore this while I was taking breaks. I realized that I could use elements from my previous projects to work on this. I previously wrote about Automating Social Media Contests with Web Scraping which is relevant to news scraping and I also wrote about Generating Singlish Text Messages where I worked with text data. Isn’t it interesting how it could all overlap?" }, { "code": null, "e": 991, "s": 606, "text": "Algo trading automates the trading process in financial markets by rapidly and precisely executing orders based on a set of defined rules. They remove human error (provided the algorithms were developed without them) and they also remove the dangers of acting on emotion. The algorithms that are used in production can be fairly complex and heavily optimized with low-latency systems." }, { "code": null, "e": 1363, "s": 991, "text": "I’ll be implementing a very basic strategy (based on trend) on a single stock. Trend-following strategies are generally easy and straightforward to implement using simple technical indicators such as moving averages. The interesting thing that we are going to include in our algo is the qualitative element from news related to the company (ironically acting on emotion)." }, { "code": null, "e": 1657, "s": 1363, "text": "Sentiment Analysis or Opinion Mining refers to the use of NLP, text analysis and computational linguistics to determine subjective information or the emotional state of the writer/subject/topic. It is commonly used in reviews which save businesses a lot of time from manually reading comments." }, { "code": null, "e": 1975, "s": 1657, "text": "Just like Algorithmic Trading, Sentiment Analysis could also go very deep as a field. Besides just giving a positive/negative sentiment, we could understand how subjective a text is, the intensities of different emotions (excitement, frustration, etc.), how Shakespearean or Trump-like a text could be, and much more." }, { "code": null, "e": 2117, "s": 1975, "text": "Facebook has recently been facing a lot of backlash and I thought it would be interesting to see how the stock moves with its news sentiment." }, { "code": null, "e": 2519, "s": 2117, "text": "The idea is pretty straightforward. We crawl the Business Times for any article related to Facebook, mine the texts, get the overall sentiment for each day, and buy 10 shares of its stock if the sentiment increases by 0.5 or sell if it decreases by 0.5. Bear in mind that the sentiment ranges from -1 to 1 with 0 being neutral and we are using the previous day’s sentiment to trade in the current day." }, { "code": null, "e": 2695, "s": 2519, "text": "Similar to my previous post on web scraping, I used the same idea of extracting URLs from the search page and visiting each article to mine its sentiment for the previous day." }, { "code": null, "e": 2777, "s": 2695, "text": "The sentiment is stored in a dictionary e.g. {datetime.date(2018,7,5):-0.59,...,}" }, { "code": null, "e": 3486, "s": 2777, "text": "VADER (Valence Aware Dictionary for sEntiment Reasoning) is a pre-built sentiment analysis model included in the NLTK package. It can give both positive/negative (polarity) as well as the strength of the emotion (intensity) of a text. It is rule-based and relies heavily on humans rating texts via Amazon Mechanical Turk — a crowd-sourcing e-platform which utilizes human intelligence to perform tasks that computers are currently unable to do. This literally means that other people have already done the dirty work of building a sentiment lexicon for us. These are words or any textual form of communication generally labelled according to their semantic orientation as either positive or negative) for us." }, { "code": null, "e": 3680, "s": 3486, "text": "The sentiment score of a text can be obtained by summing up the intensity of each word in the text and then normalizing it. The human raters of Vader used 5 heuristics to analyze the sentiment:" }, { "code": null, "e": 4128, "s": 3680, "text": "Punctuation — I love pizza vs I love pizza!!Capitalization — I’m hungry!! vs I’M HUNGRY!!Degree modifiers (use of intensifiers)— I WANT TO EAT!! VS I REALLY WANT TO EAT!!Conjunctions (shift in sentiment polarity, with later dictating polarity) — I love pizza, but I really hate Pizza Hut (bad review)Preceding Tri-gram (identifying reverse polarity by examining the tri-gram before the lexical feature— Canadian Pizza is not really all that great." }, { "code": null, "e": 4173, "s": 4128, "text": "Punctuation — I love pizza vs I love pizza!!" }, { "code": null, "e": 4219, "s": 4173, "text": "Capitalization — I’m hungry!! vs I’M HUNGRY!!" }, { "code": null, "e": 4301, "s": 4219, "text": "Degree modifiers (use of intensifiers)— I WANT TO EAT!! VS I REALLY WANT TO EAT!!" }, { "code": null, "e": 4432, "s": 4301, "text": "Conjunctions (shift in sentiment polarity, with later dictating polarity) — I love pizza, but I really hate Pizza Hut (bad review)" }, { "code": null, "e": 4580, "s": 4432, "text": "Preceding Tri-gram (identifying reverse polarity by examining the tri-gram before the lexical feature— Canadian Pizza is not really all that great." }, { "code": null, "e": 4864, "s": 4580, "text": "VADER however is focused on social media and short texts unlike Financial News which are almost the opposite. I included a chunk in my notebook to update the VADER lexicon with words+sentiments from other sources/lexicons such as the Loughran-McDonald Financial Sentiment Word Lists." }, { "code": null, "e": 4944, "s": 4864, "text": "With a simple code like this, we could easily get the sentiment from a passage." }, { "code": null, "e": 5104, "s": 4944, "text": "from nltk.sentiment.vader import SentimentIntensityAnalyzernltk.download('vader_lexicon')sia = SentimentIntensityAnalyzer()polarity_scores(passage)['compound']" }, { "code": null, "e": 5326, "s": 5104, "text": "Finally, with the use of the backtrader package, we have a convenient framework to backtest and write our trading strategy. I used the Quickstart code in the docs as a base and modified it to include our sentiment scores." }, { "code": null, "e": 5626, "s": 5326, "text": "I specified the “FB” stock feeds to be pulled from Yahoo Finance, set an initial amount of $100,000, a fixed size of 10 lots per trade, a commission of 0.1%, as well as a simple strategy to buy if the previous day’s sentiment score increases by 0.5 from the last day and sell if it decreases by 0.5." }, { "code": null, "e": 5722, "s": 5626, "text": "I started out with $100,000 and ended up with $99,742. Haha. Not gonna say anything about that." }, { "code": null, "e": 6242, "s": 5722, "text": "Okay, well the results were sorta expected because reality is so much more complex than our model. Notice how the trades were executed as the sentiment score swings. The model / I was definitely very stupid actually, we were always behind and executed trades right after the “hype” moments. But you can see where this goes, we could definitely build on the strategy by including more technical indicators or even improve the sentiment analysis by training our own model (could use NLTK) on more relevant Financial News." }, { "code": null, "e": 6453, "s": 6242, "text": "I hope you all enjoyed this, I was definitely more cautious of the readability and conciseness this time. Please leave comments, feedback and ideas if you have any. I would really appreciate it. Till next time!" }, { "code": null, "e": 6474, "s": 6453, "text": "Link to project repo" } ]
Difference between prefix and postfix operators in C#?
The increment operator ++ if used as prefix on a variable, the value of variable gets incremented by 1. After that the value is returned unlike Postfix operator. It is called Prefix increment operator. In the same way the prefix decrement operator works but it decrements by 1. For example, an example of prefix operator − ++a; The following is an example demonstrating Prefix increment operator − Live Demo using System; class Program { static void Main() { int a, b; a = 50; Console.WriteLine(++a); b = a; Console.WriteLine(a); Console.WriteLine(b); } } 51 51 51 The increment operator ++ if used as postfix on a variable, the value of variable is first returned and then gets incremented by 1. It is called Postfix increment operator. In the same way the decrement operator works but it decrements by 1. An example of Postfix operator. a++; The following is an example showing how to work with postfix operator − Live Demo using System; class Program { static void Main() { int a, b; a = 10; Console.WriteLine(a++); b = a; Console.WriteLine(a); Console.WriteLine(b); } } 10 11 11
[ { "code": null, "e": 1340, "s": 1062, "text": "The increment operator ++ if used as prefix on a variable, the value of variable gets incremented by 1. After that the value is returned unlike Postfix operator. It is called Prefix increment operator. In the same way the prefix decrement operator works but it decrements by 1." }, { "code": null, "e": 1385, "s": 1340, "text": "For example, an example of prefix operator −" }, { "code": null, "e": 1390, "s": 1385, "text": "++a;" }, { "code": null, "e": 1460, "s": 1390, "text": "The following is an example demonstrating Prefix increment operator −" }, { "code": null, "e": 1471, "s": 1460, "text": " Live Demo" }, { "code": null, "e": 1663, "s": 1471, "text": "using System;\nclass Program {\n static void Main() {\n\n int a, b;\n a = 50;\n Console.WriteLine(++a);\n\n b = a;\n Console.WriteLine(a);\n Console.WriteLine(b);\n }\n}" }, { "code": null, "e": 1672, "s": 1663, "text": "51\n51\n51" }, { "code": null, "e": 1914, "s": 1672, "text": "The increment operator ++ if used as postfix on a variable, the value of variable is first returned and then gets incremented by 1. It is called Postfix increment operator. In the same way the decrement operator works but it decrements by 1." }, { "code": null, "e": 1946, "s": 1914, "text": "An example of Postfix operator." }, { "code": null, "e": 1951, "s": 1946, "text": "a++;" }, { "code": null, "e": 2023, "s": 1951, "text": "The following is an example showing how to work with postfix operator −" }, { "code": null, "e": 2034, "s": 2023, "text": " Live Demo" }, { "code": null, "e": 2226, "s": 2034, "text": "using System;\nclass Program {\n static void Main() {\n\n int a, b;\n a = 10;\n Console.WriteLine(a++);\n\n b = a;\n Console.WriteLine(a);\n Console.WriteLine(b);\n }\n}" }, { "code": null, "e": 2235, "s": 2226, "text": "10\n11\n11" } ]
Matplotlib.artist.Artist.set_picker() in Python - GeeksforGeeks
10 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Artist class contains Abstract base class for objects that render into a FigureCanvas. All visible elements in a figure are subclasses of Artist. The set_picker() method in artist module of matplotlib library is used to define the picking behavior of the artist. Syntax: Artist.set_picker(self, picker) Parameters: This method accept the following parameters as discussed below: picker : This parameter is used to set picking behavior. This can be None or bool or float or function. Returns: This method the picking behavior of the artist. Below examples illustrate the matplotlib.artist.Artist.set_picker() function in matplotlib: Example 1: # Implementation of matplotlib functionfrom matplotlib.artist import Artistimport numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) volume = np.random.rayleigh(27, size = 40) amount = np.random.poisson(7, size = 40) ranking = np.random.normal(size = 40) price = np.random.uniform(1, 7, size = 40) fig, ax = plt.subplots() scatter = ax.scatter(volume * 2, amount**3, c = ranking**3, s = price**3, vmin = -3, vmax = 3, cmap ="Spectral") Artist.set_picker(ax, picker = 4) fig.suptitle('matplotlib.artist.Artist.set_picker()\function Example', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionfrom matplotlib.artist import Artistimport numpy as np import matplotlib.pyplot as plt X = np.random.rand(10, 200) xs = np.mean(X, axis = 1) ys = np.std(X, axis = 1) fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot(xs, ys, 'go-') Artist.set_picker(ax, picker = True) fig.suptitle('matplotlib.artist.Artist.set_picker()\ function Example', fontweight ="bold") plt.show() Output: Matplotlib Artist-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24312, "s": 24284, "text": "\n10 May, 2020" }, { "code": null, "e": 24560, "s": 24312, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Artist class contains Abstract base class for objects that render into a FigureCanvas. All visible elements in a figure are subclasses of Artist." }, { "code": null, "e": 24677, "s": 24560, "text": "The set_picker() method in artist module of matplotlib library is used to define the picking behavior of the artist." }, { "code": null, "e": 24717, "s": 24677, "text": "Syntax: Artist.set_picker(self, picker)" }, { "code": null, "e": 24793, "s": 24717, "text": "Parameters: This method accept the following parameters as discussed below:" }, { "code": null, "e": 24897, "s": 24793, "text": "picker : This parameter is used to set picking behavior. This can be None or bool or float or function." }, { "code": null, "e": 24954, "s": 24897, "text": "Returns: This method the picking behavior of the artist." }, { "code": null, "e": 25046, "s": 24954, "text": "Below examples illustrate the matplotlib.artist.Artist.set_picker() function in matplotlib:" }, { "code": null, "e": 25057, "s": 25046, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionfrom matplotlib.artist import Artistimport numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) volume = np.random.rayleigh(27, size = 40) amount = np.random.poisson(7, size = 40) ranking = np.random.normal(size = 40) price = np.random.uniform(1, 7, size = 40) fig, ax = plt.subplots() scatter = ax.scatter(volume * 2, amount**3, c = ranking**3, s = price**3, vmin = -3, vmax = 3, cmap =\"Spectral\") Artist.set_picker(ax, picker = 4) fig.suptitle('matplotlib.artist.Artist.set_picker()\\function Example', fontweight =\"bold\") plt.show()", "e": 25815, "s": 25057, "text": null }, { "code": null, "e": 25823, "s": 25815, "text": "Output:" }, { "code": null, "e": 25834, "s": 25823, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionfrom matplotlib.artist import Artistimport numpy as np import matplotlib.pyplot as plt X = np.random.rand(10, 200) xs = np.mean(X, axis = 1) ys = np.std(X, axis = 1) fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot(xs, ys, 'go-') Artist.set_picker(ax, picker = True) fig.suptitle('matplotlib.artist.Artist.set_picker()\\ function Example', fontweight =\"bold\") plt.show()", "e": 26281, "s": 25834, "text": null }, { "code": null, "e": 26289, "s": 26281, "text": "Output:" }, { "code": null, "e": 26313, "s": 26289, "text": "Matplotlib Artist-class" }, { "code": null, "e": 26331, "s": 26313, "text": "Python-matplotlib" }, { "code": null, "e": 26338, "s": 26331, "text": "Python" }, { "code": null, "e": 26436, "s": 26338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26445, "s": 26436, "text": "Comments" }, { "code": null, "e": 26458, "s": 26445, "text": "Old Comments" }, { "code": null, "e": 26476, "s": 26458, "text": "Python Dictionary" }, { "code": null, "e": 26508, "s": 26476, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26543, "s": 26508, "text": "Read a file line by line in Python" }, { "code": null, "e": 26565, "s": 26543, "text": "Enumerate() in Python" }, { "code": null, "e": 26595, "s": 26565, "text": "Iterate over a list in Python" }, { "code": null, "e": 26637, "s": 26595, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26680, "s": 26637, "text": "Python program to convert a list to string" }, { "code": null, "e": 26717, "s": 26680, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26743, "s": 26717, "text": "Python String | replace()" } ]
DAX Statistical - STDEVX.P function
Evaluates the given expression for each row of the given table and returns the standard deviation of expression assuming that the table refers to the entire population. STDEVX.P (<table>, <expression>) table A table or any DAX expression that returns a table of data. expression Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context). A real number. DAX STDEVX.P function evaluates an expression for each row of table and returns the standard deviation of an expression assuming that the table refers to the entire population. If the data in the table represents a sample of the population, you should use DAX STDEVX.S function instead. STDEVX.P uses the following formula − $$\sqrt{\sum\frac{(x\:-\:\bar{x})^{2}}{N}}$$ Where, $\bar{x}$ the average value of $x$ for the entire population, and N is the population size Blank rows are filtered out from columnName and not considered in the calculation. An error is returned if columnName contains less than 2 non-blank rows. = STDEVX.P (Sales,[Sales Amount]) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2001, "text": "Evaluates the given expression for each row of the given table and returns the standard deviation of expression assuming that the table refers to the entire population." }, { "code": null, "e": 2205, "s": 2170, "text": "STDEVX.P (<table>, <expression>) \n" }, { "code": null, "e": 2211, "s": 2205, "text": "table" }, { "code": null, "e": 2271, "s": 2211, "text": "A table or any DAX expression that returns a table of data." }, { "code": null, "e": 2282, "s": 2271, "text": "expression" }, { "code": null, "e": 2416, "s": 2282, "text": "Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context)." }, { "code": null, "e": 2431, "s": 2416, "text": "A real number." }, { "code": null, "e": 2718, "s": 2431, "text": "DAX STDEVX.P function evaluates an expression for each row of table and returns the standard deviation of an expression assuming that the table refers to the entire population. If the data in the table represents a sample of the population, you should use DAX STDEVX.S function instead." }, { "code": null, "e": 2756, "s": 2718, "text": "STDEVX.P uses the following formula −" }, { "code": null, "e": 2801, "s": 2756, "text": "$$\\sqrt{\\sum\\frac{(x\\:-\\:\\bar{x})^{2}}{N}}$$" }, { "code": null, "e": 2875, "s": 2801, "text": "Where, $\\bar{x}$ the average value of $x$ for the entire population, and" }, { "code": null, "e": 2900, "s": 2875, "text": "N is the population size" }, { "code": null, "e": 2983, "s": 2900, "text": "Blank rows are filtered out from columnName and not considered in the calculation." }, { "code": null, "e": 3055, "s": 2983, "text": "An error is returned if columnName contains less than 2 non-blank rows." }, { "code": null, "e": 3090, "s": 3055, "text": "= STDEVX.P (Sales,[Sales Amount]) " }, { "code": null, "e": 3125, "s": 3090, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3139, "s": 3125, "text": " Abhay Gadiya" }, { "code": null, "e": 3172, "s": 3139, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3186, "s": 3172, "text": " Randy Minder" }, { "code": null, "e": 3221, "s": 3186, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3235, "s": 3221, "text": " Randy Minder" }, { "code": null, "e": 3242, "s": 3235, "text": " Print" }, { "code": null, "e": 3253, "s": 3242, "text": " Add Notes" } ]
Reading from and Writing into Binary files
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file. The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor. The following table describes commonly used methods of the BinaryReader class. public override void Close() It closes the BinaryReader object and the underlying stream. public virtual int Read() Reads the characters from the underlying stream and advances the current position of the stream. public virtual bool ReadBoolean() Reads a Boolean value from the current stream and advances the current position of the stream by one byte. public virtual byte ReadByte() Reads the next byte from the current stream and advances the current position of the stream by one byte. public virtual byte[] ReadBytes(int count) Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes. public virtual char ReadChar() Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream. public virtual char[] ReadChars(int count) Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream. public virtual double ReadDouble() Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes. public virtual int ReadInt32() Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes. public virtual string ReadString() Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time. The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor. The following table describes commonly used methods of the BinaryWriter class. public override void Close() It closes the BinaryWriter object and the underlying stream. public virtual void Flush() Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. public virtual long Seek(int offset, SeekOrigin origin) Sets the position within the current stream. public virtual void Write(bool value) Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true. public virtual void Write(byte value) Writes an unsigned byte to the current stream and advances the stream position by one byte. public virtual void Write(byte[] buffer) Writes a byte array to the underlying stream. public virtual void Write(char ch) Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream. public virtual void Write(char[] chars) Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream. public virtual void Write(double value) Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes. public virtual void Write(int value) Writes a four-byte signed integer to the current stream and advances the stream position by four bytes. public virtual void Write(string value) Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream. For a complete list of methods, please visit Microsoft C# documentation. The following example demonstrates reading and writing binary data − using System; using System.IO; namespace BinaryFileApplication { class Program { static void Main(string[] args) { BinaryWriter bw; BinaryReader br; int i = 25; double d = 3.14157; bool b = true; string s = "I am happy"; //create the file try { bw = new BinaryWriter(new FileStream("mydata", FileMode.Create)); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot create file."); return; } //writing into the file try { bw.Write(i); bw.Write(d); bw.Write(b); bw.Write(s); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot write to file."); return; } bw.Close(); //reading from the file try { br = new BinaryReader(new FileStream("mydata", FileMode.Open)); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot open file."); return; } try { i = br.ReadInt32(); Console.WriteLine("Integer data: {0}", i); d = br.ReadDouble(); Console.WriteLine("Double data: {0}", d); b = br.ReadBoolean(); Console.WriteLine("Boolean data: {0}", b); s = br.ReadString(); Console.WriteLine("String data: {0}", s); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot read from file."); return; } br.Close(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Integer data: 25 Double data: 3.14157 Boolean data: True String data: I am happy 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2368, "s": 2270, "text": "The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file." }, { "code": null, "e": 2516, "s": 2368, "text": "The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor." }, { "code": null, "e": 2595, "s": 2516, "text": "The following table describes commonly used methods of the BinaryReader class." }, { "code": null, "e": 2624, "s": 2595, "text": "public override void Close()" }, { "code": null, "e": 2685, "s": 2624, "text": "It closes the BinaryReader object and the underlying stream." }, { "code": null, "e": 2711, "s": 2685, "text": "public virtual int Read()" }, { "code": null, "e": 2808, "s": 2711, "text": "Reads the characters from the underlying stream and advances the current position of the stream." }, { "code": null, "e": 2842, "s": 2808, "text": "public virtual bool ReadBoolean()" }, { "code": null, "e": 2949, "s": 2842, "text": "Reads a Boolean value from the current stream and advances the current position of the stream by one byte." }, { "code": null, "e": 2980, "s": 2949, "text": "public virtual byte ReadByte()" }, { "code": null, "e": 3085, "s": 2980, "text": "Reads the next byte from the current stream and advances the current position of the stream by one byte." }, { "code": null, "e": 3128, "s": 3085, "text": "public virtual byte[] ReadBytes(int count)" }, { "code": null, "e": 3265, "s": 3128, "text": "Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes." }, { "code": null, "e": 3296, "s": 3265, "text": "public virtual char ReadChar()" }, { "code": null, "e": 3485, "s": 3296, "text": "Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream." }, { "code": null, "e": 3528, "s": 3485, "text": "public virtual char[] ReadChars(int count)" }, { "code": null, "e": 3759, "s": 3528, "text": "Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream." }, { "code": null, "e": 3794, "s": 3759, "text": "public virtual double ReadDouble()" }, { "code": null, "e": 3919, "s": 3794, "text": "Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes." }, { "code": null, "e": 3950, "s": 3919, "text": "public virtual int ReadInt32()" }, { "code": null, "e": 4067, "s": 3950, "text": "Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes." }, { "code": null, "e": 4102, "s": 4067, "text": "public virtual string ReadString()" }, { "code": null, "e": 4226, "s": 4102, "text": "Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time." }, { "code": null, "e": 4375, "s": 4226, "text": "The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor." }, { "code": null, "e": 4454, "s": 4375, "text": "The following table describes commonly used methods of the BinaryWriter class." }, { "code": null, "e": 4483, "s": 4454, "text": "public override void Close()" }, { "code": null, "e": 4544, "s": 4483, "text": "It closes the BinaryWriter object and the underlying stream." }, { "code": null, "e": 4572, "s": 4544, "text": "public virtual void Flush()" }, { "code": null, "e": 4683, "s": 4572, "text": "Clears all buffers for the current writer and causes any buffered data to be written to the underlying device." }, { "code": null, "e": 4739, "s": 4683, "text": "public virtual long Seek(int offset, SeekOrigin origin)" }, { "code": null, "e": 4784, "s": 4739, "text": "Sets the position within the current stream." }, { "code": null, "e": 4822, "s": 4784, "text": "public virtual void Write(bool value)" }, { "code": null, "e": 4928, "s": 4822, "text": "Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true." }, { "code": null, "e": 4966, "s": 4928, "text": "public virtual void Write(byte value)" }, { "code": null, "e": 5058, "s": 4966, "text": "Writes an unsigned byte to the current stream and advances the stream position by one byte." }, { "code": null, "e": 5099, "s": 5058, "text": "public virtual void Write(byte[] buffer)" }, { "code": null, "e": 5145, "s": 5099, "text": "Writes a byte array to the underlying stream." }, { "code": null, "e": 5180, "s": 5145, "text": "public virtual void Write(char ch)" }, { "code": null, "e": 5371, "s": 5180, "text": "Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream." }, { "code": null, "e": 5411, "s": 5371, "text": "public virtual void Write(char[] chars)" }, { "code": null, "e": 5600, "s": 5411, "text": "Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream." }, { "code": null, "e": 5640, "s": 5600, "text": "public virtual void Write(double value)" }, { "code": null, "e": 5753, "s": 5640, "text": "Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes." }, { "code": null, "e": 5790, "s": 5753, "text": "public virtual void Write(int value)" }, { "code": null, "e": 5894, "s": 5790, "text": "Writes a four-byte signed integer to the current stream and advances the stream position by four bytes." }, { "code": null, "e": 5934, "s": 5894, "text": "public virtual void Write(string value)" }, { "code": null, "e": 6168, "s": 5934, "text": "Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream." }, { "code": null, "e": 6241, "s": 6168, "text": "For a complete list of methods, please visit Microsoft C# documentation." }, { "code": null, "e": 6310, "s": 6241, "text": "The following example demonstrates reading and writing binary data −" }, { "code": null, "e": 8030, "s": 6310, "text": "using System;\nusing System.IO;\n\nnamespace BinaryFileApplication {\n class Program {\n static void Main(string[] args) {\n BinaryWriter bw;\n BinaryReader br;\n \n int i = 25;\n double d = 3.14157;\n bool b = true;\n string s = \"I am happy\";\n \n //create the file\n try {\n bw = new BinaryWriter(new FileStream(\"mydata\", FileMode.Create));\n } catch (IOException e) {\n Console.WriteLine(e.Message + \"\\n Cannot create file.\");\n return;\n }\n \n //writing into the file\n try {\n bw.Write(i);\n bw.Write(d);\n bw.Write(b);\n bw.Write(s);\n } catch (IOException e) {\n Console.WriteLine(e.Message + \"\\n Cannot write to file.\");\n return;\n }\n bw.Close();\n \n //reading from the file\n try {\n br = new BinaryReader(new FileStream(\"mydata\", FileMode.Open));\n } catch (IOException e) {\n Console.WriteLine(e.Message + \"\\n Cannot open file.\");\n return;\n }\n \n try {\n i = br.ReadInt32();\n Console.WriteLine(\"Integer data: {0}\", i);\n d = br.ReadDouble();\n Console.WriteLine(\"Double data: {0}\", d);\n b = br.ReadBoolean();\n Console.WriteLine(\"Boolean data: {0}\", b);\n s = br.ReadString();\n Console.WriteLine(\"String data: {0}\", s);\n } catch (IOException e) {\n Console.WriteLine(e.Message + \"\\n Cannot read from file.\");\n return;\n }\n br.Close();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 8111, "s": 8030, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 8193, "s": 8111, "text": "Integer data: 25\nDouble data: 3.14157\nBoolean data: True\nString data: I am happy\n" }, { "code": null, "e": 8230, "s": 8193, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 8243, "s": 8230, "text": " Raja Biswas" }, { "code": null, "e": 8277, "s": 8243, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 8295, "s": 8277, "text": " Trevoir Williams" }, { "code": null, "e": 8328, "s": 8295, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8342, "s": 8328, "text": " Peter Jepson" }, { "code": null, "e": 8379, "s": 8342, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 8394, "s": 8379, "text": " Ebenezer Ogbu" }, { "code": null, "e": 8429, "s": 8394, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 8444, "s": 8429, "text": " Arnold Higuit" }, { "code": null, "e": 8479, "s": 8444, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8491, "s": 8479, "text": " Eric Frick" }, { "code": null, "e": 8498, "s": 8491, "text": " Print" }, { "code": null, "e": 8509, "s": 8498, "text": " Add Notes" } ]
C++ Program to Compute Combinations using Recurrence Relation for nCr
This is a C++ program to compute Combinations using Recurrence Relation for nCr. Begin function CalCombination(): Arguments: n, r. Body of the function: Calculate combination by using the formula: n! / (r! * (n-r)!. End #include<iostream> using namespace std; float CalCombination(float n, float r) { int i; if(r > 0) return (n/r)*CalCombination(n-1,r-1); else return 1; } int main() { float n, r; int res; cout<<"Enter the value of n: "; cin>>n; cout<<"Enter the value of r: "; cin>>r; res = CalCombination(n,r); cout<<"\nThe number of possible combinations are: nCr = "<<res; } Enter the value of n: 7 Enter the value of r: 6 The number of possible combinations are: nCr = 2
[ { "code": null, "e": 1143, "s": 1062, "text": "This is a C++ program to compute Combinations using Recurrence Relation for nCr." }, { "code": null, "e": 1309, "s": 1143, "text": "Begin\n function CalCombination():\n Arguments: n, r.\n Body of the function:\n Calculate combination by using\n the formula: n! / (r! * (n-r)!.\nEnd" }, { "code": null, "e": 1720, "s": 1309, "text": "#include<iostream>\nusing namespace std;\nfloat CalCombination(float n, float r) {\n int i;\n if(r > 0)\n return (n/r)*CalCombination(n-1,r-1);\n else\n return 1;\n}\nint main() {\n float n, r;\n int res;\n cout<<\"Enter the value of n: \";\n cin>>n;\n cout<<\"Enter the value of r: \";\n cin>>r;\n res = CalCombination(n,r);\n cout<<\"\\nThe number of possible combinations are: nCr = \"<<res;\n}" }, { "code": null, "e": 1817, "s": 1720, "text": "Enter the value of n: 7\nEnter the value of r: 6\nThe number of possible combinations are: nCr = 2" } ]
Biopython - Installation
This section explains how to install Biopython on your machine. It is very easy to install and it will not take more than five minutes. Step 1 − Verifying Python Installation Biopython is designed to work with Python 2.5 or higher versions. So, it is mandatory that python be installed first. Run the below command in your command prompt − > python --version It is defined below − It shows the version of python, if installed properly. Otherwise, download the latest version of the python, install it and then run the command again. Step 2 − Installing Biopython using pip It is easy to install Biopython using pip from the command line on all platforms. Type the below command − > pip install biopython The following response will be seen on your screen − For updating an older version of Biopython − > pip install biopython –-upgrade The following response will be seen on your screen − After executing this command, the older versions of Biopython and NumPy (Biopython depends on it) will be removed before installing the recent versions. Step 3 − Verifying Biopython Installation Now, you have successfully installed Biopython on your machine. To verify that Biopython is installed properly, type the below command on your python console − It shows the version of Biopython. Alternate Way − Installing Biopython using Source To install Biopython using source code, follow the below instructions − Download the recent release of Biopython from the following link − https://biopython.org/wiki/Download As of now, the latest version is biopython-1.72. Download the file and unpack the compressed archive file, move into the source code folder and type the below command − > python setup.py build This will build Biopython from the source code as given below − Now, test the code using the below command − > python setup.py test Finally, install using the below command − > python setup.py install Print Add Notes Bookmark this page
[ { "code": null, "e": 2242, "s": 2106, "text": "This section explains how to install Biopython on your machine. It is very easy to install and it will not take more than five minutes." }, { "code": null, "e": 2281, "s": 2242, "text": "Step 1 − Verifying Python Installation" }, { "code": null, "e": 2446, "s": 2281, "text": "Biopython is designed to work with Python 2.5 or higher versions. So, it is mandatory that python be installed first. Run the below command in your command prompt −" }, { "code": null, "e": 2466, "s": 2446, "text": "> python --version\n" }, { "code": null, "e": 2488, "s": 2466, "text": "It is defined below −" }, { "code": null, "e": 2640, "s": 2488, "text": "It shows the version of python, if installed properly. Otherwise, download the latest version of the python, install it and then run the command again." }, { "code": null, "e": 2680, "s": 2640, "text": "Step 2 − Installing Biopython using pip" }, { "code": null, "e": 2787, "s": 2680, "text": "It is easy to install Biopython using pip from the command line on all platforms. Type the below command −" }, { "code": null, "e": 2812, "s": 2787, "text": "> pip install biopython\n" }, { "code": null, "e": 2865, "s": 2812, "text": "The following response will be seen on your screen −" }, { "code": null, "e": 2910, "s": 2865, "text": "For updating an older version of Biopython −" }, { "code": null, "e": 2945, "s": 2910, "text": "> pip install biopython –-upgrade\n" }, { "code": null, "e": 2998, "s": 2945, "text": "The following response will be seen on your screen −" }, { "code": null, "e": 3151, "s": 2998, "text": "After executing this command, the older versions of Biopython and NumPy (Biopython depends on it) will be removed before installing the recent versions." }, { "code": null, "e": 3193, "s": 3151, "text": "Step 3 − Verifying Biopython Installation" }, { "code": null, "e": 3353, "s": 3193, "text": "Now, you have successfully installed Biopython on your machine. To verify that Biopython is installed properly, type the below command on your python console −" }, { "code": null, "e": 3388, "s": 3353, "text": "It shows the version of Biopython." }, { "code": null, "e": 3438, "s": 3388, "text": "Alternate Way − Installing Biopython using Source" }, { "code": null, "e": 3510, "s": 3438, "text": "To install Biopython using source code, follow the below instructions −" }, { "code": null, "e": 3613, "s": 3510, "text": "Download the recent release of Biopython from the following link − https://biopython.org/wiki/Download" }, { "code": null, "e": 3662, "s": 3613, "text": "As of now, the latest version is biopython-1.72." }, { "code": null, "e": 3782, "s": 3662, "text": "Download the file and unpack the compressed archive file, move into the source code folder and type the below command −" }, { "code": null, "e": 3807, "s": 3782, "text": "> python setup.py build\n" }, { "code": null, "e": 3871, "s": 3807, "text": "This will build Biopython from the source code as given below −" }, { "code": null, "e": 3916, "s": 3871, "text": "Now, test the code using the below command −" }, { "code": null, "e": 3940, "s": 3916, "text": "> python setup.py test\n" }, { "code": null, "e": 3983, "s": 3940, "text": "Finally, install using the below command −" }, { "code": null, "e": 4010, "s": 3983, "text": "> python setup.py install\n" }, { "code": null, "e": 4017, "s": 4010, "text": " Print" }, { "code": null, "e": 4028, "s": 4017, "text": " Add Notes" } ]
Commonly asked Interview Questions for Front End Developers - GeeksforGeeks
05 Dec, 2016 1) CSS, JS best practices? Strict mode, etc. 2) Mention some IE CSS issues faced by developers. 3) How to defer an element’s event handler if it depends on an external script that takes some time to load? 4) Optimal strategy for winning a game where let’s say, I start with 1, opponent can cite a number X within the range [2, 11]. Then I have to say a number in the range [X + 1, X + 10], then opponent, then me, and so on. Whoever says 100 in the end wins and the game ends. 5) Why would you use the prototype in JS? 6) How would you design the 2 way binding feature in Angular? 7) What is the meaning of ‘this’ in JS? 8) Namespaces in JS 9) Difference between null and undefined in JS. A function that returns nothing has a return value of undefined. 10) Closures in JS with example of statements in loop 11) JS event loop, promise, etc. 12) AngularJS memory management 13) Hoisting in JS? 14) In the code snippet below, var request = new XMLHttpRequest(); request.addEventListener('load', function(e) { console.log(this.responseText); var obj; try { obj = JSON.parse(this.responseText); } catch(ex) { } }); request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=delhi&APPID=0d84d993b430de4bebaa89bf7513676e'); request.send(); 15) What is the difference between this and e in the callback in the above code? In general, event could be anything, not just the load event. Interviewee is expected to know the syntax for sending AJAX request using bare JS. 16) Data types in JS? 17) typeof([]) is object.var b = []; b.v = 10; b.push(11); What are the contents of b? length of b? 18) Different ways to create objects in JS? Explain Object.defineProperty(). 19) Scope and execution context in JS? 20) How to implement inheritance in JS? 21) Create private members in JS objects? 22) Function.prototype.call(), bind() and apply()? 23) How are $apply(), $watch(), $digest() different in AngularJS? 24) AngularJS scope life cycle, ng-init, etc.? 25) How does scope bind the model and the view together, internally? 26) Experience with any other JS framework? 27) Sequence in which the browser parses the page? 28) Sequence of steps that happen when a URL is entered in the address bar of the browser? 29) How does JS manage multiple events in parallel, like click, input, etc. when it is interpreted & single threaded? 30) REST concepts. GET, POST, PUT, DELETE 31) Interviewee should be able to add & remove elements in DOM without a library or framework 32) Must use JavaScript Arrays functions 33) Questions on function inside function, related to scope. Difference between var m = 0; & m = 0; 34) Object Oriented JS and JS patterns by Addy Osmani. This one is an advanced topic. 35) Describe the M, V and C in MVC framework. *AngularJS questions are relevant for those who have used it. This article is contributed by Dhruv Singhal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures Difference between Class and Object SQL | Date functions Difference between Min Heap and Max Heap Iterative Letter Combinations of a Phone Number Static and Dynamic Scoping Implementation of LinkedList in Javascript Deploy Python Flask App on Heroku
[ { "code": null, "e": 25751, "s": 25723, "text": "\n05 Dec, 2016" }, { "code": null, "e": 25796, "s": 25751, "text": "1) CSS, JS best practices? Strict mode, etc." }, { "code": null, "e": 25847, "s": 25796, "text": "2) Mention some IE CSS issues faced by developers." }, { "code": null, "e": 25956, "s": 25847, "text": "3) How to defer an element’s event handler if it depends on an external script that takes some time to load?" }, { "code": null, "e": 26228, "s": 25956, "text": "4) Optimal strategy for winning a game where let’s say, I start with 1, opponent can cite a number X within the range [2, 11]. Then I have to say a number in the range [X + 1, X + 10], then opponent, then me, and so on. Whoever says 100 in the end wins and the game ends." }, { "code": null, "e": 26270, "s": 26228, "text": "5) Why would you use the prototype in JS?" }, { "code": null, "e": 26332, "s": 26270, "text": "6) How would you design the 2 way binding feature in Angular?" }, { "code": null, "e": 26372, "s": 26332, "text": "7) What is the meaning of ‘this’ in JS?" }, { "code": null, "e": 26392, "s": 26372, "text": "8) Namespaces in JS" }, { "code": null, "e": 26505, "s": 26392, "text": "9) Difference between null and undefined in JS. A function that returns nothing has a return value of undefined." }, { "code": null, "e": 26559, "s": 26505, "text": "10) Closures in JS with example of statements in loop" }, { "code": null, "e": 26592, "s": 26559, "text": "11) JS event loop, promise, etc." }, { "code": null, "e": 26624, "s": 26592, "text": "12) AngularJS memory management" }, { "code": null, "e": 26644, "s": 26624, "text": "13) Hoisting in JS?" }, { "code": null, "e": 26675, "s": 26644, "text": "14) In the code snippet below," }, { "code": null, "e": 27044, "s": 26675, "text": "var request = new XMLHttpRequest();\nrequest.addEventListener('load', function(e) {\n console.log(this.responseText);\n var obj;\n try {\n obj = JSON.parse(this.responseText);\n } \n catch(ex) { \n }\n }); \nrequest.open('GET', \n'http://api.openweathermap.org/data/2.5/weather?q=delhi&APPID=0d84d993b430de4bebaa89bf7513676e');\nrequest.send(); " }, { "code": null, "e": 27270, "s": 27044, "text": "15) What is the difference between this and e in the callback in the above code? In general, event could be anything, not just the load event. Interviewee is expected to know the syntax for sending AJAX request using bare JS." }, { "code": null, "e": 27292, "s": 27270, "text": "16) Data types in JS?" }, { "code": null, "e": 27392, "s": 27292, "text": "17) typeof([]) is object.var b = []; b.v = 10; b.push(11); What are the contents of b? length of b?" }, { "code": null, "e": 27469, "s": 27392, "text": "18) Different ways to create objects in JS? Explain Object.defineProperty()." }, { "code": null, "e": 27508, "s": 27469, "text": "19) Scope and execution context in JS?" }, { "code": null, "e": 27548, "s": 27508, "text": "20) How to implement inheritance in JS?" }, { "code": null, "e": 27590, "s": 27548, "text": "21) Create private members in JS objects?" }, { "code": null, "e": 27641, "s": 27590, "text": "22) Function.prototype.call(), bind() and apply()?" }, { "code": null, "e": 27707, "s": 27641, "text": "23) How are $apply(), $watch(), $digest() different in AngularJS?" }, { "code": null, "e": 27754, "s": 27707, "text": "24) AngularJS scope life cycle, ng-init, etc.?" }, { "code": null, "e": 27823, "s": 27754, "text": "25) How does scope bind the model and the view together, internally?" }, { "code": null, "e": 27867, "s": 27823, "text": "26) Experience with any other JS framework?" }, { "code": null, "e": 27918, "s": 27867, "text": "27) Sequence in which the browser parses the page?" }, { "code": null, "e": 28009, "s": 27918, "text": "28) Sequence of steps that happen when a URL is entered in the address bar of the browser?" }, { "code": null, "e": 28127, "s": 28009, "text": "29) How does JS manage multiple events in parallel, like click, input, etc. when it is interpreted & single threaded?" }, { "code": null, "e": 28169, "s": 28127, "text": "30) REST concepts. GET, POST, PUT, DELETE" }, { "code": null, "e": 28263, "s": 28169, "text": "31) Interviewee should be able to add & remove elements in DOM without a library or framework" }, { "code": null, "e": 28304, "s": 28263, "text": "32) Must use JavaScript Arrays functions" }, { "code": null, "e": 28404, "s": 28304, "text": "33) Questions on function inside function, related to scope. Difference between var m = 0; & m = 0;" }, { "code": null, "e": 28490, "s": 28404, "text": "34) Object Oriented JS and JS patterns by Addy Osmani. This one is an advanced topic." }, { "code": null, "e": 28536, "s": 28490, "text": "35) Describe the M, V and C in MVC framework." }, { "code": null, "e": 28598, "s": 28536, "text": "*AngularJS questions are relevant for those who have used it." }, { "code": null, "e": 28865, "s": 28598, "text": "This article is contributed by Dhruv Singhal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28874, "s": 28865, "text": "Articles" }, { "code": null, "e": 28972, "s": 28874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29009, "s": 28972, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 29035, "s": 29009, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29082, "s": 29035, "text": "Time complexities of different data structures" }, { "code": null, "e": 29118, "s": 29082, "text": "Difference between Class and Object" }, { "code": null, "e": 29139, "s": 29118, "text": "SQL | Date functions" }, { "code": null, "e": 29180, "s": 29139, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 29228, "s": 29180, "text": "Iterative Letter Combinations of a Phone Number" }, { "code": null, "e": 29255, "s": 29228, "text": "Static and Dynamic Scoping" }, { "code": null, "e": 29298, "s": 29255, "text": "Implementation of LinkedList in Javascript" } ]
How to Build Your First Python Package | by Shaked Zychlinski | Towards Data Science
This blogpost is now available in Polish too, read it on BulldogJob.pl About two years ago I published my very first data-science related blogpost. It was about Categorical Correlations, and I honestly thought no-one will find it useful. It was just experimental, and for myself. 1.7K claps later, I’ve learned that I cannot determine what other people will find useful, and I’m quite happy I can assist others on the web like others on the web assist me. I was also quite new to Python and Github at that time, so I also experimented with writing the code to these categorical-correlations that I wrote about, and publishing it on Github. I gave that piece of code a name: Dython, as in Data tools for pYTHON. But this isn’t what this blogpost is about — it’s about the last experimental thing I did after everything I just mentioned: I created a Python library and uploaded it to PyPI — which you might know as pip install. Again, this all began just as a learning exercise — but with around 1.5K installs per month, I realized again that I underestimated my code ability to be useful to others. But why am I telling you all this? Because almost everyone has some cool code lying somewhere on their laptop or on their Github account. This cool code might be very helpful to others — though most us think that’s probably not true, and “what value can others find in my tiny piece of code”. I thought so too, and I found out that I was wrong. You might be wrong too, and I’m here to persuade you — and assist you — to make your nifty piece of code into a full grown Python package in just a few steps — so you can save others hours of programming with a single pip install. Be the person that assists other programmers — and let me show you how to accomplish this in just six steps. Let’s do this. I believe it quite goes without saying, but still — I’d like to make sure we’re on the same page. Programmers are divided into two types: the ones which write readable code, and the ones which use variables named x, x1, x2, yx, etc. If you belong to the first type, you can skip ahead. If you’re the second type — it’s time to switch to the other side. Remember that other people will read your code, so make sure it’s readable. Give things meaningful names, break long functions to short-coded one-purpose methods, etc. You know, like they teach in all those coding courses. Another thing I assume is that you’re using some source-control, probably GitHub. While this isn’t really required, it is more than recommended. If you’ve never used GitHub before, this is a good point to take a few minutes and learn how — check out the official tutorial, or this blog-post, and get started. The first real step into turning your code into a package, is deciding how users should use it — and make it importable. We’ll split this into two actions: Your code is probably made of several functions and methods, but not all are meant to be used by the users — some are internal functions, supposed to be used only by your code. While Python doesn’t support private methods, the convention is to mark private methods with an underscore prefix: def _private_function(). Rename all your internal functions like so, so users will easily understand what is supposed to be exposed to them and what isn’t. Pro tip: You can use the special variable __all__ to define exactly which functions to expose and which not when the users use from your_package import *. Check out this thread on StackOverflow for more information. If your code is made out of several modules (files), looking like this: your_package |-- module1.py |-- module2.py You’ll need to add another file, __init__.py to your package in order to make Python interpret the your_package directory as a Python package. This means now it should look like this: your_package |-- __init__.py |-- module1.py |-- module2.py You can leave the file empty as a starting point, but it has to be there in order to allow from your_package import module1. Pro tip: The code in __init__.py is executed once your package is being imported, and this allows you to do all sorts of cool stuff. For example, you can use __init__.py to shorten your API. Let’s say that the most important method of your code, imp_func, is found in module1 . You can allow the users to import it as from your_package import imp_func instead of from your_package.module1 import imp_func, by simply adding: from .module1 import imp_func to your __init__.py file. Documentation is like lining up in a queue — we wish everyone would simply do it, but we tend to cut ourselves some slack whenever we can. Step 2 here relates to the previous Before We Begin section, as it meant to allow other people to understand what does your code do. There are two types of documentations you’ll need to add: Each function in your library should have a doc-string, which summarizes what the function is all about. It should contain: Summary: Explain in a simple language what the function suppose to do Parameters: Explain what are the parameters and parameter-types which the function expects Return value: Explain what the function returns Example: While not a must, it is always useful to add a usage example Here’s an example: You can learn more about doc-string formats in this super cool article on DataCamp. A Read-Me file is a summary of what your package is all about. When placed in the top directory of your package, GitHub uses it as your package “landing-page”, being displayed to visitors as the first thing they see. A good Read-Me file will have an overview of the package, installation information (such as requirements) and some Quick-Start examples, describing basic usage of your package. Read-Me files are usually written in a format known as MarkDown, which you can learn more about here. This is why they’re usually named README.md. As your code is about to get public, you should attach a license to it, explaining others how they should use your code. You’ll probably want to use a common one like the MIT License or Apache 2.0 License. GitHub will assist you choosing one by clicking the License option, and it will add a new file named LICENSE to your package. If you insist on not using GitHub, you can add the file manually. At this point, your package is supposed to look like this: your_package |-- README.md |-- LICENSE |-- __init__.py |-- module1.py |-- module2.py Now we’ll add the file that builds an installable Python package out of your code. For this, you’ll have to add a new file named setup.py, and rearrange your files in the following way: your_package |-- setup.py |-- README.md |-- LICENSE |-- your_package |-- __init__.py |-- module1.py |-- module2.py The setup file dictates everything Python installer needs to know when installing your package. A very basic one which you can simply copy-paste, looks like this: Except for editing your personal info, there are two things you’ll have to keep track of: Version: Each time you’ll release a new build to PyPI (which we’ll discuss in a second), you’ll have to bump your version number Install requires: This is a list of all the external dependencies of your package. Be sure to list everything here, so Python will install them along with your package We’re almost there! Next up: go to pypi.org and create an account. You’ll need it to upload your new library. We are pretty much done. All that’s left is running some commands which will build an installable Python package out of your code — and deploy it to PyPI. Before we begin, we’ll need to install twine, which will allow us to deploy to PyPI. It is as simple as: pip install twine Next, we’ll create an installable package. Go to the directory where the setup.py file is, and run: python setup.py sdist bdist_wheel This will create several new directories, such as dist, build and your_package.egg-info. It’s dist which we care about now, as it contains the installation files we want to deploy to PyPI. You’ll find two files in there: a compressed tar file and a wheel file. And in a second, they’ll be available to the whole world. Pro tip: Add these directories to your .gitignore file, to prevent pushing installation files to your repo. (Never heard of .gitignore? Read this) Next up, verify the distribution files you just created are okay by running: twine check dist/* Time to upload your package to PyPI. I recommend deploying first to the PyPI test domain, so you can verify everything looks as you intended. Do this using: twine upload --repository-url https://test.pypi.org/legacy/ dist/* Go to test.pypi.org and check your new library. Satisfied? Great, let’s push it to the real PyPI: twine upload dist/* That’s it. From now on everyone can install your package using pip install. Great job! Pro tip: You can make your life easier with a Bash script, which will build, check and deploy your package with a single command. Create a new file named build_deploy.sh in the same directory as setup.py. Copy-paste the following code into this file: Now all you need to do is run: ./build_deploy.sh From the directory where the file is at, and that’s it. You can also run: ./build_deploy.sh --test to upload to the test domain. (Note you’ll have to make the script executable before running it the first time. Simply run chmod +x build_deploy.sh in the directory where the file is located.) Your awesome code is now available for everyone to use — but people are still unaware of your awesome code which is now available to them. How can you let them know? Write a blog-post, and tell why you build this code in the first place, and what are its use-cases. Share your story, so others will know how much effort you just saved them with your awesome code. Taking your code into the next level — publishing it to the world — might seem frightening when doing it for the first time, both for personal reasons (“who will want to use it?”) and for technical reasons (“how can I do it?”). I hope that in this post, I assisted you to overcome both these setbacks, and now you too can assist thousands of other programmers worldwide. Well done, and welcome to the open-source community!
[ { "code": null, "e": 117, "s": 46, "text": "This blogpost is now available in Polish too, read it on BulldogJob.pl" }, { "code": null, "e": 502, "s": 117, "text": "About two years ago I published my very first data-science related blogpost. It was about Categorical Correlations, and I honestly thought no-one will find it useful. It was just experimental, and for myself. 1.7K claps later, I’ve learned that I cannot determine what other people will find useful, and I’m quite happy I can assist others on the web like others on the web assist me." }, { "code": null, "e": 757, "s": 502, "text": "I was also quite new to Python and Github at that time, so I also experimented with writing the code to these categorical-correlations that I wrote about, and publishing it on Github. I gave that piece of code a name: Dython, as in Data tools for pYTHON." }, { "code": null, "e": 1144, "s": 757, "text": "But this isn’t what this blogpost is about — it’s about the last experimental thing I did after everything I just mentioned: I created a Python library and uploaded it to PyPI — which you might know as pip install. Again, this all began just as a learning exercise — but with around 1.5K installs per month, I realized again that I underestimated my code ability to be useful to others." }, { "code": null, "e": 1844, "s": 1144, "text": "But why am I telling you all this? Because almost everyone has some cool code lying somewhere on their laptop or on their Github account. This cool code might be very helpful to others — though most us think that’s probably not true, and “what value can others find in my tiny piece of code”. I thought so too, and I found out that I was wrong. You might be wrong too, and I’m here to persuade you — and assist you — to make your nifty piece of code into a full grown Python package in just a few steps — so you can save others hours of programming with a single pip install. Be the person that assists other programmers — and let me show you how to accomplish this in just six steps. Let’s do this." }, { "code": null, "e": 2420, "s": 1844, "text": "I believe it quite goes without saying, but still — I’d like to make sure we’re on the same page. Programmers are divided into two types: the ones which write readable code, and the ones which use variables named x, x1, x2, yx, etc. If you belong to the first type, you can skip ahead. If you’re the second type — it’s time to switch to the other side. Remember that other people will read your code, so make sure it’s readable. Give things meaningful names, break long functions to short-coded one-purpose methods, etc. You know, like they teach in all those coding courses." }, { "code": null, "e": 2729, "s": 2420, "text": "Another thing I assume is that you’re using some source-control, probably GitHub. While this isn’t really required, it is more than recommended. If you’ve never used GitHub before, this is a good point to take a few minutes and learn how — check out the official tutorial, or this blog-post, and get started." }, { "code": null, "e": 2885, "s": 2729, "text": "The first real step into turning your code into a package, is deciding how users should use it — and make it importable. We’ll split this into two actions:" }, { "code": null, "e": 3333, "s": 2885, "text": "Your code is probably made of several functions and methods, but not all are meant to be used by the users — some are internal functions, supposed to be used only by your code. While Python doesn’t support private methods, the convention is to mark private methods with an underscore prefix: def _private_function(). Rename all your internal functions like so, so users will easily understand what is supposed to be exposed to them and what isn’t." }, { "code": null, "e": 3549, "s": 3333, "text": "Pro tip: You can use the special variable __all__ to define exactly which functions to expose and which not when the users use from your_package import *. Check out this thread on StackOverflow for more information." }, { "code": null, "e": 3621, "s": 3549, "text": "If your code is made out of several modules (files), looking like this:" }, { "code": null, "e": 3666, "s": 3621, "text": "your_package |-- module1.py |-- module2.py" }, { "code": null, "e": 3850, "s": 3666, "text": "You’ll need to add another file, __init__.py to your package in order to make Python interpret the your_package directory as a Python package. This means now it should look like this:" }, { "code": null, "e": 3912, "s": 3850, "text": "your_package |-- __init__.py |-- module1.py |-- module2.py" }, { "code": null, "e": 4037, "s": 3912, "text": "You can leave the file empty as a starting point, but it has to be there in order to allow from your_package import module1." }, { "code": null, "e": 4461, "s": 4037, "text": "Pro tip: The code in __init__.py is executed once your package is being imported, and this allows you to do all sorts of cool stuff. For example, you can use __init__.py to shorten your API. Let’s say that the most important method of your code, imp_func, is found in module1 . You can allow the users to import it as from your_package import imp_func instead of from your_package.module1 import imp_func, by simply adding:" }, { "code": null, "e": 4491, "s": 4461, "text": "from .module1 import imp_func" }, { "code": null, "e": 4517, "s": 4491, "text": "to your __init__.py file." }, { "code": null, "e": 4847, "s": 4517, "text": "Documentation is like lining up in a queue — we wish everyone would simply do it, but we tend to cut ourselves some slack whenever we can. Step 2 here relates to the previous Before We Begin section, as it meant to allow other people to understand what does your code do. There are two types of documentations you’ll need to add:" }, { "code": null, "e": 4971, "s": 4847, "text": "Each function in your library should have a doc-string, which summarizes what the function is all about. It should contain:" }, { "code": null, "e": 5041, "s": 4971, "text": "Summary: Explain in a simple language what the function suppose to do" }, { "code": null, "e": 5132, "s": 5041, "text": "Parameters: Explain what are the parameters and parameter-types which the function expects" }, { "code": null, "e": 5180, "s": 5132, "text": "Return value: Explain what the function returns" }, { "code": null, "e": 5250, "s": 5180, "text": "Example: While not a must, it is always useful to add a usage example" }, { "code": null, "e": 5269, "s": 5250, "text": "Here’s an example:" }, { "code": null, "e": 5353, "s": 5269, "text": "You can learn more about doc-string formats in this super cool article on DataCamp." }, { "code": null, "e": 5570, "s": 5353, "text": "A Read-Me file is a summary of what your package is all about. When placed in the top directory of your package, GitHub uses it as your package “landing-page”, being displayed to visitors as the first thing they see." }, { "code": null, "e": 5747, "s": 5570, "text": "A good Read-Me file will have an overview of the package, installation information (such as requirements) and some Quick-Start examples, describing basic usage of your package." }, { "code": null, "e": 5894, "s": 5747, "text": "Read-Me files are usually written in a format known as MarkDown, which you can learn more about here. This is why they’re usually named README.md." }, { "code": null, "e": 6292, "s": 5894, "text": "As your code is about to get public, you should attach a license to it, explaining others how they should use your code. You’ll probably want to use a common one like the MIT License or Apache 2.0 License. GitHub will assist you choosing one by clicking the License option, and it will add a new file named LICENSE to your package. If you insist on not using GitHub, you can add the file manually." }, { "code": null, "e": 6351, "s": 6292, "text": "At this point, your package is supposed to look like this:" }, { "code": null, "e": 6444, "s": 6351, "text": "your_package |-- README.md |-- LICENSE |-- __init__.py |-- module1.py |-- module2.py" }, { "code": null, "e": 6630, "s": 6444, "text": "Now we’ll add the file that builds an installable Python package out of your code. For this, you’ll have to add a new file named setup.py, and rearrange your files in the following way:" }, { "code": null, "e": 6773, "s": 6630, "text": "your_package |-- setup.py |-- README.md |-- LICENSE |-- your_package |-- __init__.py |-- module1.py |-- module2.py" }, { "code": null, "e": 6936, "s": 6773, "text": "The setup file dictates everything Python installer needs to know when installing your package. A very basic one which you can simply copy-paste, looks like this:" }, { "code": null, "e": 7026, "s": 6936, "text": "Except for editing your personal info, there are two things you’ll have to keep track of:" }, { "code": null, "e": 7155, "s": 7026, "text": "Version: Each time you’ll release a new build to PyPI (which we’ll discuss in a second), you’ll have to bump your version number" }, { "code": null, "e": 7323, "s": 7155, "text": "Install requires: This is a list of all the external dependencies of your package. Be sure to list everything here, so Python will install them along with your package" }, { "code": null, "e": 7433, "s": 7323, "text": "We’re almost there! Next up: go to pypi.org and create an account. You’ll need it to upload your new library." }, { "code": null, "e": 7588, "s": 7433, "text": "We are pretty much done. All that’s left is running some commands which will build an installable Python package out of your code — and deploy it to PyPI." }, { "code": null, "e": 7693, "s": 7588, "text": "Before we begin, we’ll need to install twine, which will allow us to deploy to PyPI. It is as simple as:" }, { "code": null, "e": 7711, "s": 7693, "text": "pip install twine" }, { "code": null, "e": 7811, "s": 7711, "text": "Next, we’ll create an installable package. Go to the directory where the setup.py file is, and run:" }, { "code": null, "e": 7845, "s": 7811, "text": "python setup.py sdist bdist_wheel" }, { "code": null, "e": 8164, "s": 7845, "text": "This will create several new directories, such as dist, build and your_package.egg-info. It’s dist which we care about now, as it contains the installation files we want to deploy to PyPI. You’ll find two files in there: a compressed tar file and a wheel file. And in a second, they’ll be available to the whole world." }, { "code": null, "e": 8311, "s": 8164, "text": "Pro tip: Add these directories to your .gitignore file, to prevent pushing installation files to your repo. (Never heard of .gitignore? Read this)" }, { "code": null, "e": 8388, "s": 8311, "text": "Next up, verify the distribution files you just created are okay by running:" }, { "code": null, "e": 8407, "s": 8388, "text": "twine check dist/*" }, { "code": null, "e": 8564, "s": 8407, "text": "Time to upload your package to PyPI. I recommend deploying first to the PyPI test domain, so you can verify everything looks as you intended. Do this using:" }, { "code": null, "e": 8631, "s": 8564, "text": "twine upload --repository-url https://test.pypi.org/legacy/ dist/*" }, { "code": null, "e": 8729, "s": 8631, "text": "Go to test.pypi.org and check your new library. Satisfied? Great, let’s push it to the real PyPI:" }, { "code": null, "e": 8749, "s": 8729, "text": "twine upload dist/*" }, { "code": null, "e": 8836, "s": 8749, "text": "That’s it. From now on everyone can install your package using pip install. Great job!" }, { "code": null, "e": 9087, "s": 8836, "text": "Pro tip: You can make your life easier with a Bash script, which will build, check and deploy your package with a single command. Create a new file named build_deploy.sh in the same directory as setup.py. Copy-paste the following code into this file:" }, { "code": null, "e": 9118, "s": 9087, "text": "Now all you need to do is run:" }, { "code": null, "e": 9136, "s": 9118, "text": "./build_deploy.sh" }, { "code": null, "e": 9210, "s": 9136, "text": "From the directory where the file is at, and that’s it. You can also run:" }, { "code": null, "e": 9235, "s": 9210, "text": "./build_deploy.sh --test" }, { "code": null, "e": 9428, "s": 9235, "text": "to upload to the test domain. (Note you’ll have to make the script executable before running it the first time. Simply run chmod +x build_deploy.sh in the directory where the file is located.)" }, { "code": null, "e": 9792, "s": 9428, "text": "Your awesome code is now available for everyone to use — but people are still unaware of your awesome code which is now available to them. How can you let them know? Write a blog-post, and tell why you build this code in the first place, and what are its use-cases. Share your story, so others will know how much effort you just saved them with your awesome code." } ]
Decision Tree Classifier explained in real-life: picking a vacation destination | by Carolina Bento | Towards Data Science
This is article number one in a series dedicated to Tree Based Algorithms, a group of widely used Supervised Machine Learning Algorithms. Stay tuned if you’d like to see Decision Trees, Random Forests and Gradient Boosting Decision Trees, explained with real-life examples and some Python code. Decision Tree is a Supervised Machine Learning Algorithm that uses a set of rules to make decisions, similarly to how humans make decisions. One way to think of a Machine Learning classification algorithm is that it is built to make decisions. You usually say the model predicts the class of the new, never-seen-before input but, behind the scenes, the algorithm has to decide which class to assign. Some classification algorithms are probabilistic, like Naive Bayes, but there’s also a rule-based approach. We humans, also make rule-based decisions all the time. When you’re planning your next vacation, you use a rule-based approach. You might pick a different destination based on how long you’re going to be on vacation, the budget available or if your extended family is coming along. The answer to these questions informs the final decision. And if you continually narrow down the available vacation destinations based on how you answer each question, you can visualize this decision process as a (decision) tree. Decision trees can perform both classification and regression tasks, so you’ll see authors refer to them as CART algorithm: Classification and Regression Tree. This is an umbrella term, applicable to all tree-based algorithms, not just decision trees. But let’s focus on decision trees for classification. The intuition behind Decision Trees is that you use the dataset features to create yes/no questions and continually split the dataset until you isolate all data points belonging to each class. With this process you’re organizing the data in a tree structure. Every time you ask a question you’re adding a node to the tree. And the first node is called the root node. The result of asking a question splits the dataset based on the value of a feature, and creates new nodes. If you decide to stop the process after a split, the last nodes created are called leaf nodes. Every time you answer a question, you’re also creating branches and segmenting the feature space into disjoint regions[1]. One branch of the tree has all data points corresponding to answering Yes to the question the rule in the previous node implied. The other branch has a node with the remaining data points. This way you narrow down the feature space with each split or branch in the tree, and each data point will only belong to one region. The goal is to continue to splitting the feature space, and applying rules, until you don’t have any more rules to apply or no data points left. Then, it’s time to assign a class to all data points in each leaf node. The algorithm tries to completely separate the dataset such that all leaf nodes, i.e., the nodes that don’t split the data further, belong to a single class. These are called pure leaf nodes. But most times you end up with mixed leaf nodes, where not all data points have to the same class. In the end, the algorithm can only assign one class to the data points in each leaf node. With pure leaf nodes that already taken care of, because all data points in that node have the same class. But with mixed leaf nodes the algorithm assigns the most common class among all data points in that node. The ideal tree is the smallest tree possible, i.e. with fewer splits, that can accurately classify all data points. This sounds simple, but it’s actually a NP hard problem. Building the ideal tree would take polynomial time, which increases exponentially as the dataset grows. For example, for a dataset with only 10 data points and an algorithm with quadratic complexity, O(n2), the algorithm executes 10*10 = 100 iterations to build the tree. Expand that dataset a bit more to have 100 data points, and the number of iterations the algorithm will execute jumps to 10,000. Finding the best tree is ideal in theory, but as the dataset grows, it becomes computationally unfeasible! To turn this NP-hard problem into something computationally feasible the algorithm uses a greedy approach to build the next best tree. A greedy approach makes locally optimal decisions to pick the feature used in each split, instead of trying to make the best overall decision[2]. Since it optimizes for local decisions, it focuses only on the node at hand, and what’s best for that node in particular. So it doesn’t need to explore all possible splits for that node and beyond. On every split, the algorithm tries to divide the dataset into the smallest subset possible[2]. So, like any other Machine Learning algorithm, the goal is to minimize the loss function as much as possible. A popular loss function for classification algorithms is Stochastic Gradient Descent but, it requires the loss function to be differentiable. So, it’s not an option in this case. But since you’re separating data points that belong to different classes, the loss function should evaluate a split based on the proportion of data points belonging to each class before and after the split. Decision Tree use loss functions that evaluate the split based on the purity of the resulting nodes. n order words, you’d want a loss function that evaluates the split based on the purity of the resulting nodes. A loss function that compares the class distribution before and after the split[2], like Gini Impurity and Entropy. Gini Impurity is measure of variance across the different classes[1]. Similarly to Gini Impurity, Entropy is a measure of chaos within the node. And chaos, in the context of decision trees, is having a node where all classes are equally present in the data. Using Entropy as loss function, a split is only performed if the Entropy of each the resulting nodes is lower than the Entropy of the parent node. Otherwise, the split is not locally optimal. Even though Decision trees is a simple algorithm, it has several advantages: Interpretability you can visualize the decision tree. No preprocessing required you don’t need to prepare the data before building the model. Data robustness the algorithm handles all types of data nicely. One of the biggest advantages of tree-based algorithms it that you can actually visualize the model. You can see the decisions the algorithm made, and how it classified the different data points. This is a major advantage, because most algorithms work like blackboxes, and it’s hard to clearly pinpoint what made the algorithm predict a specific result. Several machine learning algorithms require feature values to be as similar as possible, so the algorithm can best interpret how the changes in those features impact the target. The most common preprocessing requirement is feature normalization, so all features in the same scale and any change in those values has the same proportional weight. The rules in tree-based algorithms are built around each individual feature, instead of considering the entire feature set. Each decision is made looking at one feature at a time, so their values don’t need to be normalized. Tree-based algorithms are great at handling different data types. Your dataset can have a mix of numerical and categorical data, and you won’t need to encode any of the categorial features. This is an item on the pre-processing checklist that tree-based algorithms handle on their own. Planning the next vacation can be challenging. Vacations are never long enough, there are budget constraints, and sometimes the extended family wants to come along, which makes logistics more complicated. You like the idea of asking for a second opinion, from an algorithm, when it’s time to make a decision that involves way too many variables to keep track of. Picking a vacation destination is a perfect example! Whenever you start planning a vacation, you always take into account: Duration of the vacation, Personal budget, Weather forecast, If your extended family is joining, If you’re feeling adventurous and want to explore new places. Since Decision Trees are said to mimic how humans make decisions, that’s the algorithm you’re using. The bonus piece it that, in the end, you’ll be able to visualize the decision tree and see how the algorithm picked the destination. Thinking through your decision process for previous vacations and the criteria you always take into consideration, you put together a dataset. Even though the Decision Tree algorithm can handle different data types, ScikitLearn’s current implementation doesn’t support categorical data. To use the Decision Tree classifier from ScikitLearn, you can’t skip the pre-processing step and need to encode all categorical features and targets before training the model. import numpy as npfrom sklearn import preprocessingdef encode_feature(array): """ Encode a categorical array into a number array :param array: array to be encoded :return: numerical array """ encoder = preprocessing.LabelEncoder() encoder.fit(array) return encoder.transform(array)feature_names = ['number_days', 'family_joining', 'personal_budget', 'weather_forecast', 'explore_new_places']class_names = ['Countryside', 'Beach']features = np.array([[10, 'Yes', 950, 75, 'Yes'], [10, 'Yes', 250, 78, 'Yes'], [7, 'Yes', 600, 80, 'No'], [8, 'Yes', 750, 67, 'Yes'], [10, 'Yes', 800, 73, 'Yes'], [8, 'Yes', 850, 64, 'Yes'], [15, 'No', 350, 78, 'No'], [8, 'Yes', 850, 81, 'Yes'], [6, 'No', 750, 59, 'Yes'], [12, 'Yes', 1050, 54, 'Yes'], [10, 'No', 230, 74, 'No'], [3, 'Yes', 630, 74, 'Yes'], [10, 'Yes', 830, 74, 'No'], [12, 'No', 730, 52, 'Yes']])# Encoding categorical featuresfeatures[:, 1] = encode_feature(features[:, 1])features[:, 4] = encode_feature(features[:, 4])targets = np.array(['Countryside','Beach','Beach','Countryside', 'Beach', 'Countryside', 'Beach','Countryside', 'Beach', 'Beach', 'Countryside','Countryside', 'Beach', 'Beach'])targets = encode_feature(targets) Pre-processing: Done ✅ Now it’s time to build and visualize the Decision Tree. import pandas as pdfrom sklearn import treeimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitdef print_feature_importance(names_array, importances_array): """ Prints out a feature importance array as a dataframe. """ importances = pd.DataFrame(data=names_array) importances[1] = importances_array importances = importances.T importances.drop(0, axis=0, inplace=True) importances.columns = feature_names print(str(importances.reset_index(drop=True)))def build_tree(features, targets, feature_names, class_names): """ Builds a decision tree. Prints out the decision tree 1) as a plot, 2) as text. Also outputs: 1) feature importance, 2) training set and test set mean accuracy of tree :param features: model features :param targets: model targets :param feature_names: names of the dataset features """ train_features, test_features, train_targets, test_targets = train_test_split(features, targets, test_size=0.2, random_state=123) decision_tree = tree.DecisionTreeClassifier(random_state=456) decision_tree = decision_tree.fit(train_features, train_targets) # Visualizing the decision tree # 1. Saving the image of the decision as a png plt.subplots(figsize=(17, 12)) tree.plot_tree(decision_tree, feature_names=feature_names, filled=True, rounded=True, class_names=class_names) plt.savefig("decision_tree.png") # 2. Output the tree as text in the console tree_as_text = tree.export_text(decision_tree, feature_names=feature_names) print(tree_as_text) # Feature Importance # Turns the feature importance array into a dataframe, so it has a table-like output format print_feature_importance(feature_names, decision_tree.feature_importances_) # Training and test mean accuracy train_error = np.round(decision_tree.score(train_features, train_targets), 2) test_error = np.round(decision_tree.score(test_features, test_targets), 2) print("Training Set Mean Accuracy = " + str(train_error)) print("Test Set Mean Accuracy = " + str(test_error))build_tree(features, targets, feature_names, class_names) This code does lots of things at once, so let’s unpack it. It starts by splitting the dataset into training and test with the train_test_split function, so you can test model accuracy with data points that were not used to train the model. By default ScikitLearn uses Gini Impurity as a loss function. But you can also use Entropy as the loss function and tune other parameters in the DecisionTreeClassifier. With the model trained, you can visualize the resulting decision tree with the plot_tree method, and save as decision_tree.png. You can also visualize the tree in the output console, you can use the export_text method. But there’s something wrong with that decision tree! You noticed the feature explore_new_places doesn’t show up anywhere. Even though you’re sure it’s an important part of your decision process. To get to the bottom of this and understand why explore_new_places is not used in the model you lookup the feature_importances_ property in the decision tree model. This will tell you how much each features contributes to the accuracy of the model. The feature_importances_ property is simply an array of values, with each value corresponding to a feature of the model, with the same order as the input dataset. So, for better readability, you can decided to create the function print_feature_importance and transform the value array from feature_importances_ property into a dataframe and use the feature names as headers. explore_new_places has a feature importance of 0, which means it’s not used at all in the prediction. At first glance you might be thinking, I can just get rid of this feature. But feature importance doesn’t necessarily mean the feature is never going to be used in the model. It only means it was not used in this tree, which as a specific training-test split. So you can’t eliminate this feature right away. To confirm that explore_new_places is not relevant to the model, you can build several trees with different train-test splits f the dataset and check if explore_new_places still has zero importance. Finally, to evaluate the algorithm’s performance you calculate the mean accuracy of the predictions on both the training and test sets, using the score method. As you can see, this model is overfit and memorized the training set. And with a 67% of mean accuracy for the test set, it doesn’t generalize very well to observations it has never seen before. Despite their advantages, Decision Trees don’t provide the same level of accuracy as other classification and regression algorithms. Decision trees are prone to overfitting. If you build a very tall tree, splitting the feature set until you get pure leaf nodes, you’re likely overfitting the training set. The resulting tree is so complex that it’s also hard to read and interpret. On the other hand, if your decision tree is very small it underfits the data, resulting in high bias. Decision trees are robust in terms of the data types they can handle, but the algorithm itself is not very robust. A slight change in the data can drastically change the tree and, consequently the final results[1]. A single Decision Tree by itself has subpar accuracy, when compared to other machine learning algorithms. One tree alone typically doesn’t generate the best predictions, but the tree structure makes it easy to control the bias-variance trade-off. A single Decision Tree is not powerful enough, but an entire forest is! In algorithms that combine multiple trees and control for bias or variance, like Random Forests, the model has a much better performance when compared to a single decision tree. Stay tuned for the next articles in this series, because they’re about Boosting and Bagging. These techniques are applied to tree-based algorithms and tackle, respectively, the issues with bias and variance. Decision trees are a rule-based approach to classification and regression problems. They use the values in each feature to split the dataset to a point where all data points that have the same class are grouped together. However, there’s a clear trade-off between interpretability and performance. You can easily visualize and interpret a small tree, but it has high variance. A small change in the training set, may result in a completely different tree, and completely different predictions. On the other hand, a tall tree with multiple splits generates better classifications. But it’s likely memorizing the training dataset. So it not good at classifying data it has never seen before. Hope you enjoyed learning about Decision Trees! Stay tuned for the next articles in this series! The next articles explore Tree-based Ensemble algorithms that use Boosting and Bagging techniques to control bias and variance. Thanks for reading! Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. (2013). An introduction to statistical learning : with applications in R. New York :SpringerP. Tan, M. Steinbach, and V. Kumar. (2005) Introduction to Data Mining. Addison Wesley Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. (2013). An introduction to statistical learning : with applications in R. New York :Springer P. Tan, M. Steinbach, and V. Kumar. (2005) Introduction to Data Mining. Addison Wesley
[ { "code": null, "e": 310, "s": 172, "text": "This is article number one in a series dedicated to Tree Based Algorithms, a group of widely used Supervised Machine Learning Algorithms." }, { "code": null, "e": 467, "s": 310, "text": "Stay tuned if you’d like to see Decision Trees, Random Forests and Gradient Boosting Decision Trees, explained with real-life examples and some Python code." }, { "code": null, "e": 608, "s": 467, "text": "Decision Tree is a Supervised Machine Learning Algorithm that uses a set of rules to make decisions, similarly to how humans make decisions." }, { "code": null, "e": 711, "s": 608, "text": "One way to think of a Machine Learning classification algorithm is that it is built to make decisions." }, { "code": null, "e": 867, "s": 711, "text": "You usually say the model predicts the class of the new, never-seen-before input but, behind the scenes, the algorithm has to decide which class to assign." }, { "code": null, "e": 975, "s": 867, "text": "Some classification algorithms are probabilistic, like Naive Bayes, but there’s also a rule-based approach." }, { "code": null, "e": 1031, "s": 975, "text": "We humans, also make rule-based decisions all the time." }, { "code": null, "e": 1257, "s": 1031, "text": "When you’re planning your next vacation, you use a rule-based approach. You might pick a different destination based on how long you’re going to be on vacation, the budget available or if your extended family is coming along." }, { "code": null, "e": 1487, "s": 1257, "text": "The answer to these questions informs the final decision. And if you continually narrow down the available vacation destinations based on how you answer each question, you can visualize this decision process as a (decision) tree." }, { "code": null, "e": 1739, "s": 1487, "text": "Decision trees can perform both classification and regression tasks, so you’ll see authors refer to them as CART algorithm: Classification and Regression Tree. This is an umbrella term, applicable to all tree-based algorithms, not just decision trees." }, { "code": null, "e": 1793, "s": 1739, "text": "But let’s focus on decision trees for classification." }, { "code": null, "e": 1986, "s": 1793, "text": "The intuition behind Decision Trees is that you use the dataset features to create yes/no questions and continually split the dataset until you isolate all data points belonging to each class." }, { "code": null, "e": 2052, "s": 1986, "text": "With this process you’re organizing the data in a tree structure." }, { "code": null, "e": 2160, "s": 2052, "text": "Every time you ask a question you’re adding a node to the tree. And the first node is called the root node." }, { "code": null, "e": 2267, "s": 2160, "text": "The result of asking a question splits the dataset based on the value of a feature, and creates new nodes." }, { "code": null, "e": 2362, "s": 2267, "text": "If you decide to stop the process after a split, the last nodes created are called leaf nodes." }, { "code": null, "e": 2485, "s": 2362, "text": "Every time you answer a question, you’re also creating branches and segmenting the feature space into disjoint regions[1]." }, { "code": null, "e": 2674, "s": 2485, "text": "One branch of the tree has all data points corresponding to answering Yes to the question the rule in the previous node implied. The other branch has a node with the remaining data points." }, { "code": null, "e": 2808, "s": 2674, "text": "This way you narrow down the feature space with each split or branch in the tree, and each data point will only belong to one region." }, { "code": null, "e": 2953, "s": 2808, "text": "The goal is to continue to splitting the feature space, and applying rules, until you don’t have any more rules to apply or no data points left." }, { "code": null, "e": 3025, "s": 2953, "text": "Then, it’s time to assign a class to all data points in each leaf node." }, { "code": null, "e": 3217, "s": 3025, "text": "The algorithm tries to completely separate the dataset such that all leaf nodes, i.e., the nodes that don’t split the data further, belong to a single class. These are called pure leaf nodes." }, { "code": null, "e": 3316, "s": 3217, "text": "But most times you end up with mixed leaf nodes, where not all data points have to the same class." }, { "code": null, "e": 3406, "s": 3316, "text": "In the end, the algorithm can only assign one class to the data points in each leaf node." }, { "code": null, "e": 3513, "s": 3406, "text": "With pure leaf nodes that already taken care of, because all data points in that node have the same class." }, { "code": null, "e": 3619, "s": 3513, "text": "But with mixed leaf nodes the algorithm assigns the most common class among all data points in that node." }, { "code": null, "e": 3735, "s": 3619, "text": "The ideal tree is the smallest tree possible, i.e. with fewer splits, that can accurately classify all data points." }, { "code": null, "e": 3896, "s": 3735, "text": "This sounds simple, but it’s actually a NP hard problem. Building the ideal tree would take polynomial time, which increases exponentially as the dataset grows." }, { "code": null, "e": 4193, "s": 3896, "text": "For example, for a dataset with only 10 data points and an algorithm with quadratic complexity, O(n2), the algorithm executes 10*10 = 100 iterations to build the tree. Expand that dataset a bit more to have 100 data points, and the number of iterations the algorithm will execute jumps to 10,000." }, { "code": null, "e": 4300, "s": 4193, "text": "Finding the best tree is ideal in theory, but as the dataset grows, it becomes computationally unfeasible!" }, { "code": null, "e": 4435, "s": 4300, "text": "To turn this NP-hard problem into something computationally feasible the algorithm uses a greedy approach to build the next best tree." }, { "code": null, "e": 4581, "s": 4435, "text": "A greedy approach makes locally optimal decisions to pick the feature used in each split, instead of trying to make the best overall decision[2]." }, { "code": null, "e": 4779, "s": 4581, "text": "Since it optimizes for local decisions, it focuses only on the node at hand, and what’s best for that node in particular. So it doesn’t need to explore all possible splits for that node and beyond." }, { "code": null, "e": 4985, "s": 4779, "text": "On every split, the algorithm tries to divide the dataset into the smallest subset possible[2]. So, like any other Machine Learning algorithm, the goal is to minimize the loss function as much as possible." }, { "code": null, "e": 5164, "s": 4985, "text": "A popular loss function for classification algorithms is Stochastic Gradient Descent but, it requires the loss function to be differentiable. So, it’s not an option in this case." }, { "code": null, "e": 5371, "s": 5164, "text": "But since you’re separating data points that belong to different classes, the loss function should evaluate a split based on the proportion of data points belonging to each class before and after the split." }, { "code": null, "e": 5472, "s": 5371, "text": "Decision Tree use loss functions that evaluate the split based on the purity of the resulting nodes." }, { "code": null, "e": 5699, "s": 5472, "text": "n order words, you’d want a loss function that evaluates the split based on the purity of the resulting nodes. A loss function that compares the class distribution before and after the split[2], like Gini Impurity and Entropy." }, { "code": null, "e": 5769, "s": 5699, "text": "Gini Impurity is measure of variance across the different classes[1]." }, { "code": null, "e": 5957, "s": 5769, "text": "Similarly to Gini Impurity, Entropy is a measure of chaos within the node. And chaos, in the context of decision trees, is having a node where all classes are equally present in the data." }, { "code": null, "e": 6149, "s": 5957, "text": "Using Entropy as loss function, a split is only performed if the Entropy of each the resulting nodes is lower than the Entropy of the parent node. Otherwise, the split is not locally optimal." }, { "code": null, "e": 6226, "s": 6149, "text": "Even though Decision trees is a simple algorithm, it has several advantages:" }, { "code": null, "e": 6280, "s": 6226, "text": "Interpretability you can visualize the decision tree." }, { "code": null, "e": 6368, "s": 6280, "text": "No preprocessing required you don’t need to prepare the data before building the model." }, { "code": null, "e": 6432, "s": 6368, "text": "Data robustness the algorithm handles all types of data nicely." }, { "code": null, "e": 6533, "s": 6432, "text": "One of the biggest advantages of tree-based algorithms it that you can actually visualize the model." }, { "code": null, "e": 6628, "s": 6533, "text": "You can see the decisions the algorithm made, and how it classified the different data points." }, { "code": null, "e": 6786, "s": 6628, "text": "This is a major advantage, because most algorithms work like blackboxes, and it’s hard to clearly pinpoint what made the algorithm predict a specific result." }, { "code": null, "e": 6964, "s": 6786, "text": "Several machine learning algorithms require feature values to be as similar as possible, so the algorithm can best interpret how the changes in those features impact the target." }, { "code": null, "e": 7131, "s": 6964, "text": "The most common preprocessing requirement is feature normalization, so all features in the same scale and any change in those values has the same proportional weight." }, { "code": null, "e": 7356, "s": 7131, "text": "The rules in tree-based algorithms are built around each individual feature, instead of considering the entire feature set. Each decision is made looking at one feature at a time, so their values don’t need to be normalized." }, { "code": null, "e": 7546, "s": 7356, "text": "Tree-based algorithms are great at handling different data types. Your dataset can have a mix of numerical and categorical data, and you won’t need to encode any of the categorial features." }, { "code": null, "e": 7642, "s": 7546, "text": "This is an item on the pre-processing checklist that tree-based algorithms handle on their own." }, { "code": null, "e": 7847, "s": 7642, "text": "Planning the next vacation can be challenging. Vacations are never long enough, there are budget constraints, and sometimes the extended family wants to come along, which makes logistics more complicated." }, { "code": null, "e": 8058, "s": 7847, "text": "You like the idea of asking for a second opinion, from an algorithm, when it’s time to make a decision that involves way too many variables to keep track of. Picking a vacation destination is a perfect example!" }, { "code": null, "e": 8128, "s": 8058, "text": "Whenever you start planning a vacation, you always take into account:" }, { "code": null, "e": 8154, "s": 8128, "text": "Duration of the vacation," }, { "code": null, "e": 8171, "s": 8154, "text": "Personal budget," }, { "code": null, "e": 8189, "s": 8171, "text": "Weather forecast," }, { "code": null, "e": 8225, "s": 8189, "text": "If your extended family is joining," }, { "code": null, "e": 8287, "s": 8225, "text": "If you’re feeling adventurous and want to explore new places." }, { "code": null, "e": 8388, "s": 8287, "text": "Since Decision Trees are said to mimic how humans make decisions, that’s the algorithm you’re using." }, { "code": null, "e": 8521, "s": 8388, "text": "The bonus piece it that, in the end, you’ll be able to visualize the decision tree and see how the algorithm picked the destination." }, { "code": null, "e": 8664, "s": 8521, "text": "Thinking through your decision process for previous vacations and the criteria you always take into consideration, you put together a dataset." }, { "code": null, "e": 8808, "s": 8664, "text": "Even though the Decision Tree algorithm can handle different data types, ScikitLearn’s current implementation doesn’t support categorical data." }, { "code": null, "e": 8984, "s": 8808, "text": "To use the Decision Tree classifier from ScikitLearn, you can’t skip the pre-processing step and need to encode all categorical features and targets before training the model." }, { "code": null, "e": 10507, "s": 8984, "text": "import numpy as npfrom sklearn import preprocessingdef encode_feature(array): \"\"\" Encode a categorical array into a number array :param array: array to be encoded :return: numerical array \"\"\" encoder = preprocessing.LabelEncoder() encoder.fit(array) return encoder.transform(array)feature_names = ['number_days', 'family_joining', 'personal_budget', 'weather_forecast', 'explore_new_places']class_names = ['Countryside', 'Beach']features = np.array([[10, 'Yes', 950, 75, 'Yes'], [10, 'Yes', 250, 78, 'Yes'], [7, 'Yes', 600, 80, 'No'], [8, 'Yes', 750, 67, 'Yes'], [10, 'Yes', 800, 73, 'Yes'], [8, 'Yes', 850, 64, 'Yes'], [15, 'No', 350, 78, 'No'], [8, 'Yes', 850, 81, 'Yes'], [6, 'No', 750, 59, 'Yes'], [12, 'Yes', 1050, 54, 'Yes'], [10, 'No', 230, 74, 'No'], [3, 'Yes', 630, 74, 'Yes'], [10, 'Yes', 830, 74, 'No'], [12, 'No', 730, 52, 'Yes']])# Encoding categorical featuresfeatures[:, 1] = encode_feature(features[:, 1])features[:, 4] = encode_feature(features[:, 4])targets = np.array(['Countryside','Beach','Beach','Countryside', 'Beach', 'Countryside', 'Beach','Countryside', 'Beach', 'Beach', 'Countryside','Countryside', 'Beach', 'Beach'])targets = encode_feature(targets)" }, { "code": null, "e": 10530, "s": 10507, "text": "Pre-processing: Done ✅" }, { "code": null, "e": 10586, "s": 10530, "text": "Now it’s time to build and visualize the Decision Tree." }, { "code": null, "e": 12755, "s": 10586, "text": "import pandas as pdfrom sklearn import treeimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitdef print_feature_importance(names_array, importances_array): \"\"\" Prints out a feature importance array as a dataframe. \"\"\" importances = pd.DataFrame(data=names_array) importances[1] = importances_array importances = importances.T importances.drop(0, axis=0, inplace=True) importances.columns = feature_names print(str(importances.reset_index(drop=True)))def build_tree(features, targets, feature_names, class_names): \"\"\" Builds a decision tree. Prints out the decision tree 1) as a plot, 2) as text. Also outputs: 1) feature importance, 2) training set and test set mean accuracy of tree :param features: model features :param targets: model targets :param feature_names: names of the dataset features \"\"\" train_features, test_features, train_targets, test_targets = train_test_split(features, targets, test_size=0.2, random_state=123) decision_tree = tree.DecisionTreeClassifier(random_state=456) decision_tree = decision_tree.fit(train_features, train_targets) # Visualizing the decision tree # 1. Saving the image of the decision as a png plt.subplots(figsize=(17, 12)) tree.plot_tree(decision_tree, feature_names=feature_names, filled=True, rounded=True, class_names=class_names) plt.savefig(\"decision_tree.png\") # 2. Output the tree as text in the console tree_as_text = tree.export_text(decision_tree, feature_names=feature_names) print(tree_as_text) # Feature Importance # Turns the feature importance array into a dataframe, so it has a table-like output format print_feature_importance(feature_names, decision_tree.feature_importances_) # Training and test mean accuracy train_error = np.round(decision_tree.score(train_features, train_targets), 2) test_error = np.round(decision_tree.score(test_features, test_targets), 2) print(\"Training Set Mean Accuracy = \" + str(train_error)) print(\"Test Set Mean Accuracy = \" + str(test_error))build_tree(features, targets, feature_names, class_names)" }, { "code": null, "e": 12814, "s": 12755, "text": "This code does lots of things at once, so let’s unpack it." }, { "code": null, "e": 12995, "s": 12814, "text": "It starts by splitting the dataset into training and test with the train_test_split function, so you can test model accuracy with data points that were not used to train the model." }, { "code": null, "e": 13164, "s": 12995, "text": "By default ScikitLearn uses Gini Impurity as a loss function. But you can also use Entropy as the loss function and tune other parameters in the DecisionTreeClassifier." }, { "code": null, "e": 13292, "s": 13164, "text": "With the model trained, you can visualize the resulting decision tree with the plot_tree method, and save as decision_tree.png." }, { "code": null, "e": 13383, "s": 13292, "text": "You can also visualize the tree in the output console, you can use the export_text method." }, { "code": null, "e": 13436, "s": 13383, "text": "But there’s something wrong with that decision tree!" }, { "code": null, "e": 13578, "s": 13436, "text": "You noticed the feature explore_new_places doesn’t show up anywhere. Even though you’re sure it’s an important part of your decision process." }, { "code": null, "e": 13827, "s": 13578, "text": "To get to the bottom of this and understand why explore_new_places is not used in the model you lookup the feature_importances_ property in the decision tree model. This will tell you how much each features contributes to the accuracy of the model." }, { "code": null, "e": 13990, "s": 13827, "text": "The feature_importances_ property is simply an array of values, with each value corresponding to a feature of the model, with the same order as the input dataset." }, { "code": null, "e": 14202, "s": 13990, "text": "So, for better readability, you can decided to create the function print_feature_importance and transform the value array from feature_importances_ property into a dataframe and use the feature names as headers." }, { "code": null, "e": 14304, "s": 14202, "text": "explore_new_places has a feature importance of 0, which means it’s not used at all in the prediction." }, { "code": null, "e": 14379, "s": 14304, "text": "At first glance you might be thinking, I can just get rid of this feature." }, { "code": null, "e": 14564, "s": 14379, "text": "But feature importance doesn’t necessarily mean the feature is never going to be used in the model. It only means it was not used in this tree, which as a specific training-test split." }, { "code": null, "e": 14612, "s": 14564, "text": "So you can’t eliminate this feature right away." }, { "code": null, "e": 14811, "s": 14612, "text": "To confirm that explore_new_places is not relevant to the model, you can build several trees with different train-test splits f the dataset and check if explore_new_places still has zero importance." }, { "code": null, "e": 14971, "s": 14811, "text": "Finally, to evaluate the algorithm’s performance you calculate the mean accuracy of the predictions on both the training and test sets, using the score method." }, { "code": null, "e": 15165, "s": 14971, "text": "As you can see, this model is overfit and memorized the training set. And with a 67% of mean accuracy for the test set, it doesn’t generalize very well to observations it has never seen before." }, { "code": null, "e": 15298, "s": 15165, "text": "Despite their advantages, Decision Trees don’t provide the same level of accuracy as other classification and regression algorithms." }, { "code": null, "e": 15547, "s": 15298, "text": "Decision trees are prone to overfitting. If you build a very tall tree, splitting the feature set until you get pure leaf nodes, you’re likely overfitting the training set. The resulting tree is so complex that it’s also hard to read and interpret." }, { "code": null, "e": 15649, "s": 15547, "text": "On the other hand, if your decision tree is very small it underfits the data, resulting in high bias." }, { "code": null, "e": 15864, "s": 15649, "text": "Decision trees are robust in terms of the data types they can handle, but the algorithm itself is not very robust. A slight change in the data can drastically change the tree and, consequently the final results[1]." }, { "code": null, "e": 16111, "s": 15864, "text": "A single Decision Tree by itself has subpar accuracy, when compared to other machine learning algorithms. One tree alone typically doesn’t generate the best predictions, but the tree structure makes it easy to control the bias-variance trade-off." }, { "code": null, "e": 16183, "s": 16111, "text": "A single Decision Tree is not powerful enough, but an entire forest is!" }, { "code": null, "e": 16361, "s": 16183, "text": "In algorithms that combine multiple trees and control for bias or variance, like Random Forests, the model has a much better performance when compared to a single decision tree." }, { "code": null, "e": 16569, "s": 16361, "text": "Stay tuned for the next articles in this series, because they’re about Boosting and Bagging. These techniques are applied to tree-based algorithms and tackle, respectively, the issues with bias and variance." }, { "code": null, "e": 16790, "s": 16569, "text": "Decision trees are a rule-based approach to classification and regression problems. They use the values in each feature to split the dataset to a point where all data points that have the same class are grouped together." }, { "code": null, "e": 16867, "s": 16790, "text": "However, there’s a clear trade-off between interpretability and performance." }, { "code": null, "e": 17063, "s": 16867, "text": "You can easily visualize and interpret a small tree, but it has high variance. A small change in the training set, may result in a completely different tree, and completely different predictions." }, { "code": null, "e": 17259, "s": 17063, "text": "On the other hand, a tall tree with multiple splits generates better classifications. But it’s likely memorizing the training dataset. So it not good at classifying data it has never seen before." }, { "code": null, "e": 17307, "s": 17259, "text": "Hope you enjoyed learning about Decision Trees!" }, { "code": null, "e": 17484, "s": 17307, "text": "Stay tuned for the next articles in this series! The next articles explore Tree-based Ensemble algorithms that use Boosting and Bagging techniques to control bias and variance." }, { "code": null, "e": 17504, "s": 17484, "text": "Thanks for reading!" }, { "code": null, "e": 17747, "s": 17504, "text": "Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. (2013). An introduction to statistical learning : with applications in R. New York :SpringerP. Tan, M. Steinbach, and V. Kumar. (2005) Introduction to Data Mining. Addison Wesley" }, { "code": null, "e": 17904, "s": 17747, "text": "Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. (2013). An introduction to statistical learning : with applications in R. New York :Springer" } ]
Java | Functions | Question 11 - GeeksforGeeks
24 May, 2019 Predict the output of the following program. class Test{ public static void main(String[] args) { String str = "geeks"; str.toUpperCase(); str += "forgeeks"; String string = str.substring(2,13); string = string + str.charAt(4);; System.out.println(string); }} (A) eksforgeekss(B) eksforgeeks(C) EKSforgeekss(D) EKSforgeeksAnswer: (A)Explanation: str.toUpperCase() returns ‘str’ in upper case. But,it does not change the original string ‘str’.str.substring(x, y) returns a string from position ‘x'(inclusive) to position ‘y'(exclusive).str.charAt(x) returns a character at position ‘x’ in the string ‘str’.Quiz of this Question Vijay Sirra Functions Java-Functions Java Quiz Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Constructors | Question 3 Java | Constructors | Question 5 Java | final keyword | Question 1 Java | Exception Handling | Question 2 Java | Abstract Class and Interface | Question 2 Java | Class and Object | Question 1 Java | Exception Handling | Question 3 Java | Exception Handling | Question 7 Java | Inheritance | Question 8 Java | Exception Handling | Question 8
[ { "code": null, "e": 25799, "s": 25771, "text": "\n24 May, 2019" }, { "code": null, "e": 25844, "s": 25799, "text": "Predict the output of the following program." }, { "code": "class Test{ public static void main(String[] args) { String str = \"geeks\"; str.toUpperCase(); str += \"forgeeks\"; String string = str.substring(2,13); string = string + str.charAt(4);; System.out.println(string); }}", "e": 26110, "s": 25844, "text": null }, { "code": null, "e": 26477, "s": 26110, "text": "(A) eksforgeekss(B) eksforgeeks(C) EKSforgeekss(D) EKSforgeeksAnswer: (A)Explanation: str.toUpperCase() returns ‘str’ in upper case. But,it does not change the original string ‘str’.str.substring(x, y) returns a string from position ‘x'(inclusive) to position ‘y'(exclusive).str.charAt(x) returns a character at position ‘x’ in the string ‘str’.Quiz of this Question" }, { "code": null, "e": 26489, "s": 26477, "text": "Vijay Sirra" }, { "code": null, "e": 26499, "s": 26489, "text": "Functions" }, { "code": null, "e": 26514, "s": 26499, "text": "Java-Functions" }, { "code": null, "e": 26524, "s": 26514, "text": "Java Quiz" }, { "code": null, "e": 26534, "s": 26524, "text": "Functions" }, { "code": null, "e": 26632, "s": 26534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26665, "s": 26632, "text": "Java | Constructors | Question 3" }, { "code": null, "e": 26698, "s": 26665, "text": "Java | Constructors | Question 5" }, { "code": null, "e": 26732, "s": 26698, "text": "Java | final keyword | Question 1" }, { "code": null, "e": 26771, "s": 26732, "text": "Java | Exception Handling | Question 2" }, { "code": null, "e": 26820, "s": 26771, "text": "Java | Abstract Class and Interface | Question 2" }, { "code": null, "e": 26857, "s": 26820, "text": "Java | Class and Object | Question 1" }, { "code": null, "e": 26896, "s": 26857, "text": "Java | Exception Handling | Question 3" }, { "code": null, "e": 26935, "s": 26896, "text": "Java | Exception Handling | Question 7" }, { "code": null, "e": 26967, "s": 26935, "text": "Java | Inheritance | Question 8" } ]
Batch Script - VOL
This batch command displays the volume labels. VOL @echo off VOL The output will display the current volume label. For example, Volume in drive C is Windows8_OS Volume Serial Number is E41C-6F43 Print Add Notes Bookmark this page
[ { "code": null, "e": 2216, "s": 2169, "text": "This batch command displays the volume labels." }, { "code": null, "e": 2221, "s": 2216, "text": "VOL\n" }, { "code": null, "e": 2236, "s": 2221, "text": "@echo off \nVOL" }, { "code": null, "e": 2299, "s": 2236, "text": "The output will display the current volume label. For example," }, { "code": null, "e": 2368, "s": 2299, "text": "Volume in drive C is Windows8_OS \nVolume Serial Number is E41C-6F43\n" }, { "code": null, "e": 2375, "s": 2368, "text": " Print" }, { "code": null, "e": 2386, "s": 2375, "text": " Add Notes" } ]
Python | Aggregate values by tuple keys - GeeksforGeeks
29 Oct, 2019 Sometimes, while working with records, we can have a problem in which we need to group the like keys and aggregate the values of like keys. This can have application in any kind of scoring. Let’s discuss certain ways in which this task can be performed. Method #1 : Using Counter() + generator expressionThe combination of above functions can be used to perform this particular task. In this, we need to first combine the like key elements and task of aggregation is performed by Counter(). # Python3 code to demonstrate working of# Aggregate values by tuple keys# using Counter() + generator expressionfrom collections import Counter # initialize listtest_list = [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)] # printing original listprint("The original list is : " + str(test_list)) # Aggregate values by tuple keys# using Counter() + generator expressionres = list(Counter(key for key, num in test_list for idx in range(num)).items()) # printing resultprint("List after grouping : " + str(res)) The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)] List after grouping : [('best', 150), ('gfg', 70), ('is', 30)] Method #2 : Using groupby() + map() + itemgetter() + sum()The combination of above functions can also be used to perform this particular task. In this, we group the elements using groupby(), decision of key’s index is given by itemgetter. Task of addition(aggregation) is performed by sum() and extension of logic to all tuples is handled by map(). # Python3 code to demonstrate working of# Aggregate values by tuple keys# using groupby() + map() + itemgetter() + sum()from itertools import groupbyfrom operator import itemgetter # initialize listtest_list = [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)] # printing original listprint("The original list is : " + str(test_list)) # Aggregate values by tuple keys# using groupby() + map() + itemgetter() + sum()res = [(key, sum(map(itemgetter(1), ele))) for key, ele in groupby(sorted(test_list, key = itemgetter(0)), key = itemgetter(0))] # printing resultprint("List after grouping : " + str(res)) The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)] List after grouping : [('best', 150), ('gfg', 70), ('is', 30)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24410, "s": 24382, "text": "\n29 Oct, 2019" }, { "code": null, "e": 24664, "s": 24410, "text": "Sometimes, while working with records, we can have a problem in which we need to group the like keys and aggregate the values of like keys. This can have application in any kind of scoring. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24901, "s": 24664, "text": "Method #1 : Using Counter() + generator expressionThe combination of above functions can be used to perform this particular task. In this, we need to first combine the like key elements and task of aggregation is performed by Counter()." }, { "code": "# Python3 code to demonstrate working of# Aggregate values by tuple keys# using Counter() + generator expressionfrom collections import Counter # initialize listtest_list = [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)] # printing original listprint(\"The original list is : \" + str(test_list)) # Aggregate values by tuple keys# using Counter() + generator expressionres = list(Counter(key for key, num in test_list for idx in range(num)).items()) # printing resultprint(\"List after grouping : \" + str(res))", "e": 25477, "s": 24901, "text": null }, { "code": null, "e": 25632, "s": 25477, "text": "The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]\nList after grouping : [('best', 150), ('gfg', 70), ('is', 30)]\n" }, { "code": null, "e": 25983, "s": 25634, "text": "Method #2 : Using groupby() + map() + itemgetter() + sum()The combination of above functions can also be used to perform this particular task. In this, we group the elements using groupby(), decision of key’s index is given by itemgetter. Task of addition(aggregation) is performed by sum() and extension of logic to all tuples is handled by map()." }, { "code": "# Python3 code to demonstrate working of# Aggregate values by tuple keys# using groupby() + map() + itemgetter() + sum()from itertools import groupbyfrom operator import itemgetter # initialize listtest_list = [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)] # printing original listprint(\"The original list is : \" + str(test_list)) # Aggregate values by tuple keys# using groupby() + map() + itemgetter() + sum()res = [(key, sum(map(itemgetter(1), ele))) for key, ele in groupby(sorted(test_list, key = itemgetter(0)), key = itemgetter(0))] # printing resultprint(\"List after grouping : \" + str(res))", "e": 26687, "s": 25983, "text": null }, { "code": null, "e": 26842, "s": 26687, "text": "The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]\nList after grouping : [('best', 150), ('gfg', 70), ('is', 30)]\n" }, { "code": null, "e": 26863, "s": 26842, "text": "Python list-programs" }, { "code": null, "e": 26870, "s": 26863, "text": "Python" }, { "code": null, "e": 26886, "s": 26870, "text": "Python Programs" }, { "code": null, "e": 26984, "s": 26886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27002, "s": 26984, "text": "Python Dictionary" }, { "code": null, "e": 27037, "s": 27002, "text": "Read a file line by line in Python" }, { "code": null, "e": 27069, "s": 27037, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27111, "s": 27069, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27137, "s": 27111, "text": "Python String | replace()" }, { "code": null, "e": 27180, "s": 27137, "text": "Python program to convert a list to string" }, { "code": null, "e": 27202, "s": 27180, "text": "Defaultdict in Python" }, { "code": null, "e": 27248, "s": 27202, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27287, "s": 27248, "text": "Python | Get dictionary keys as a list" } ]
JSTL - fn:toUpperCase() Function
The fn:toUpperCase() function converts all the characters of a string to uppercase. The fn:toUpperCase() function has the following syntax − java.lang.String tolowercase(java.lang.String) Following example explains the functionality of the fn:toUpperCase() function − <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "string1" value = "This is first String."/> <c:set var = "string2" value = "${fn:toUpperCase(string1)}" /> <p>Final string : ${string2}</p> </body> </html> You will receive the following result − Final string : THIS IS FIRST STRING. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2323, "s": 2239, "text": "The fn:toUpperCase() function converts all the characters of a string to uppercase." }, { "code": null, "e": 2380, "s": 2323, "text": "The fn:toUpperCase() function has the following syntax −" }, { "code": null, "e": 2428, "s": 2380, "text": "java.lang.String tolowercase(java.lang.String)\n" }, { "code": null, "e": 2508, "s": 2428, "text": "Following example explains the functionality of the fn:toUpperCase() function −" }, { "code": null, "e": 2925, "s": 2508, "text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"string1\" value = \"This is first String.\"/>\n <c:set var = \"string2\" value = \"${fn:toUpperCase(string1)}\" />\n\n <p>Final string : ${string2}</p>\n </body>\n</html>" }, { "code": null, "e": 2965, "s": 2925, "text": "You will receive the following result −" }, { "code": null, "e": 3003, "s": 2965, "text": "Final string : THIS IS FIRST STRING.\n" }, { "code": null, "e": 3038, "s": 3003, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3053, "s": 3038, "text": " Chaand Sheikh" }, { "code": null, "e": 3088, "s": 3053, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3103, "s": 3088, "text": " Chaand Sheikh" }, { "code": null, "e": 3138, "s": 3103, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3152, "s": 3138, "text": " Karthikeya T" }, { "code": null, "e": 3187, "s": 3152, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3203, "s": 3187, "text": " TELCOMA Global" }, { "code": null, "e": 3236, "s": 3203, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3252, "s": 3236, "text": " TELCOMA Global" }, { "code": null, "e": 3286, "s": 3252, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3294, "s": 3286, "text": " Uplatz" }, { "code": null, "e": 3301, "s": 3294, "text": " Print" }, { "code": null, "e": 3312, "s": 3301, "text": " Add Notes" } ]
Make Your Data Science Life Easy With Docker | by Fahad Akbar | Towards Data Science
One of the preliminary steps that you take when you embark on your data science journey is dealing with the installation of different software such as Python, Jyupter Notebook, some IDEs and countless libraries. Once you successfully pass through this, you often encounter situations where your code seems to work fine on your computer, but when you share it with others, it collapses seemingly for no reason. Well, you are not alone! The good news is that there are some impressive solutions available that range differently on the scale of convenience, accessibility and ease of use. Google Colab is one of them. It is ready to start, comes loaded with lots of useful libraries and has GPU support. It has its limitations too. But it’s not the topic of today’s article. You can learn and experience Google Colab here. research.google.com In this article, we are going to take a different approach. We will do hands-on first, and the explanation will come later. This approach will demonstrate how easy it is and why you should learn more about it to be a well-versed data scientist. Below is a list of key concepts & tasks we will be going through today: 1️⃣ What is Docker? 2️⃣ Install Docker Desktop 3️⃣ Run Data Science loaded Jupyter Notebook 4️⃣ Understanding Containers 5️⃣ What is an Image & Dockerfile? 6️⃣ Create a customized Docker Image 7️⃣ Save & share your Image ➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖ Let’s start discussing them one by one. Docker is a company that provides solutions (the name of the solution is Docker as well !) to the problems we described above. In fact it does more than that and is an excellent tool in the developer’s toolbox, but we will stick to its relevance to our data science-related issues. It is a software that helps us build “images” and run “containers” to support and better deliver data science projects. We will explain the concepts of “images” & “containers” later in this article. As mentioned above, we will do hands-on first, and the explanation will come later. You can read more about Docker here. www.docker.com Before we begin, I would also recommend creating an account on Docker (free version is fine) to save your projects on Docker Hub. Visit this link and install Docker Desktop. It is no different than any other software installation. You can choose the Windows version or Mac Version. For our demonstration, we will use the Windows version. The procedure for Mac is almost identical. Once downloaded, click the downloaded file to install and follow the instructions. The process is straight forward and should go smoothly. If you want to see the process in action before installing, I found a nice 11-minute video on YouTube, that walks you through the installation process. Once the installation is complete, you can perform a little check to see if everything is working. Open up your command prompt/terminal and write this code and hit enter: docker -v This should confirm if the installation were successful by providing you with the version of Docker we installed. It’s time for the magic. Open up your command prompt/terminal and write down the following code: docker run -p 8888:8888 jupyter/minimal-notebook I will explain this code later, for now just follow these steps. We are doing this for the first time, so it will take some time to get it ready. The next time, rerunning this command won’t take any longer as all the necessary files are already downloaded. Additionally, you will not require any internet connectivity (unlike Google’s Colab) either. Once the process is over, this is how the output should look like: Copy any of the last three lines (these are the addresses) and paste them into any of your browsers (save the token for later use, provided in the address after the word “token”). That will open up a Jupyter Notebook in your browser. You will notice that the notebook comes loaded with Python3, Julia & R. Not only that, but many popular data science libraries are already installed and ready to be imported! The 😯😲 😯 part is that NONE of these programs are actually installed on your machine! So if you try to find Python/Julia/R or Jupyter Notebook on your computer, good luck! Even if you had these programs installed previously on your computer, these “dockerized” installations are stand-alone installations that have nothing to do with the applications already installed (or not installed) on your computer. This implies that if you create a program or write a code using the Jupyter Notebook we just created, test it, and share (all these things coming later in the article) it with your friend or colleague, it is guaranteed to work as long as your friend or colleague has fired up their Jupyter Notebook the same way we did. The story starts with the idea of containers. The idea is not new, though; you might be familiar with the “environment” concept already. It’s almost the same thing. In due course, a data scientist will create and develop many models that will depend upon many libraries or on many other data scientist’s work (we call them dependencies). This will inevitably lead to “contradictions” between all these models as dependencies evolve and grow. Let’s start with a very generalized example. Imagine you have a lot of 💰💰💰 and decide to build a plant to produce something for commercial use. You build a factory(which is, for now, is just one big hall), and install all sorts of different machines and workplaces. You then hire skilled workers to do the job. When your business is new and is not at scale things are not complicated, and they go smoothly. But as your business grows and competition increases, you decided to add more sophisticated technologies and advanced processes. Here comes the problem; as you adapt to these new technologies, you realize that some of these processes simply can not work under one roof, e.g. one technology requires a dry environment and in contrast, another one works within a more humid one. Same goes with the people, some need a quiet environment, whereas others need to work with loud and noisy machines (or for many other random reasons) So what is the most intuitive solution that comes to your mind ? Obviously, you will simply build separate rooms (as opposed to construct separate buildings )and halls to make sure that every process and department gets the environment it needs. This solution, is akin to the concept of a “Container”. Continuing with our example, now you want to build the same facility in another country or geographical area with the exact same settings. Imagine a technology that can somehow clone your existing production setup, and you can simply port it to the required location. That is akin to “sharing the Container”. A more data science related example would be a model you created using version x of sklearn for use-case A. Five months later, sklearn has a new, improved version x+1. You update your library and create another model using the new version ,for another use-case B. Everyone is happy until you run your model for use-case A, which collapses and doesn’t run. It turns out that the old model is not supported anymore by the newer sklearn version. As a result, you can only run the old model (if you go back to install the older sklearn version) or the new model, not both at the same time. Again, try to think of a possible solution. A straightforward one will be to have another computer and install the new sklearn version on it. This will, for sure, solve the problem. ❌Please don’t suggest this to anyone!❌ , because for how long can you keep this up? Buying new computers every time you update your sklearn library, not to mention hundreds of other libraries, is definitely not a practical solution. What if we install all the software and libraries required for a specific project, “quarantined” in their own space, within one computer or operating system? This way, your model will only stay within its boundaries and will not interfere with whatever is outside of it. This is what you call a container; projects and all its dependencies containerized/ isolated /quarantined within one operating system. We can go one step ahead and share that container with others, who can then add and run the container on their machine and execute the same experiment without having to worry about all the dependencies involved. At this point, we are ready to introduce two more concepts to get a complete picture; Image & Dockerfile. The Image is a seed for the container. It is a “snapshot” of a project at some point in time. It only becomes a container when we “run” it. Think of it as a picture you took of your friend’s beautiful room and later on you plan to arrange your room the same way. The beauty of it all is that we can alter the Image before running and converting it into a container. That alteration comes through a Dockerfile. Dockerfile is a poker face file (it does not have any extension like csv, txt etc.) that contains instructions for the Docker. In our demonstration, Jupyter took a snapshot of its project, made an image, and published it on Docker Hub with the name “jupyter/datascience-notebook.” We pulled and ran the Image, making it into a container. We did not alter the Image, though; we just ran it as is. That’s why there was no Dockerfile involved. In the next session, we will show an example where we will alter the notebook and add the Tensorflow and a data pre-processing library called preprocess1 before running the container. This time to keep things lighter and faster, I will use another image of Jupyter notebook (called jupyter/minimal-notebook). You can keep the same Image as we used previously, if you want to. Let’s move ahead with our previous example, in which we “pulled” the data science loaded Jupyter Notebook from Docker Hub. Only this time, we will add the Tensorflow & preprocess1 library to it through Dockerfile. But first, let’s see what the process will look like. 📔 If you have and know how to operate MS Visual Studio Code, the process becomes so much easier. For now, we will do the steps assuming we don’t have VS Code. 1️⃣ Create Project Folder: On your computer, create an empty folder where you want to save your project’s files. 2️⃣ Create Dockerfile: Inside the folder, create a text file. Open the file and write down the following code (lines starting with # are mere comments) # import pre-built image from data science notebookFROM jupyter/minimal-notebook# Install required librariesRUN pip install tensorflowRUN pip install preprocess1 As you can see, the code so far is easy to read and understand. We did nothing more than importing the Jupyter Notebook and installing the libraries we wanted by using “FROM” & “RUN” commands. 3️⃣ Save the Dockerfile: Close the file, right-click to rename it as “Dockerfile” (make sure to follow the exact spellings and case) , remove the extension (.txt) and save it. Your Docker file is ready! ➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖ ➕ Bonus: Usually, we do all these library installations through a text file called “requirements” (although the name doesn’t matter). You just put the library names along with any specific versions you want and save the file under the same folder where your Dockerfile is. Library requirements in the file go like this: tensorflow==2.2.0preprocess1==0.0.38 Here is the code to “add” this text file to your Jupyter Image. jupyter-docker-stacks.readthedocs.io ➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖ 4️⃣ Fire up your command prompt, and ‘cd’ to the folder where we created the docker file. Once there, we run the following command to build our Image. docker build -t notebook_demo . Again, code is pretty intuitive; it is a docker command to build an image named notebook_demo. “-t” is a flag word used to name/tag the image. In the end, the “dot” means that the Dockerfile we are using is inside the active directory. Hit enter to execute the command line. It should look like this: 5️⃣ Run the Image: we are now ready to run the Image we just created. Run the following command in the command prompt / terminal: docker run -p 8888:8888 notebook_demo This command means it is a docker command to run an Image named notebook_demo. Flag word “-p” means to map it to ports 8888 between the container and the host. Once done, copy any of the three addresses provided and past it in your browser to open and access your Jupyter Notebook (save the token for later use). Import tensorflow & preprocess1 libraries to make sure we have them correctly. We successfully loaded a minimal Jupyter Library, pre-installed with some custom libraries like TensorFlow and preprocess1. What good is it if we cant port our work to other computers or share it with other users ? That is out last step! It is worth noting that once you build an image on your computer, it is automatically saved. You can use the run command to access it any time, without needing any internet connection. ▶️ One option is to save it to the Docker Hub. That makes it public, and anybody can access it just the way we accessed minimal and data science Jupyter Notebook from Docker Hub. One of the issues with this approach is image size when you upload it to Docker Hub as it increases rather quickly. we will need to use the following commands to save to Docker Hub in command prompt/terminal: #log into Docker Hubdocker login — username= your_Docker_username#Enter your password when prompted# Push your Image by name, in our case "notebook_demo"docker push your_Docker_username/your_image_name That’s it! your Image is available to use publicly. Anyone who has docker installed , can easily access the same image, with the exact dependencies that you added (tensorflow & preprocess1) with the command we are already familiar with: docker run -p 8888:8888 notebook_demo ▶️The other option is to save it as a tar file , we need to run the following command in command prompt/ terminal. You need to be in the same directory where you want to save the tar file. # save it under the active directory docker save notebook_demo > notebook_demo.tar# you can load it this waydocker load — input notebook_demo.tar Congratulations! If you have made so far, you deserve a big round of applause! 👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏 👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏 In this session we learnt and applied the following ✅ What is Docker? ✅ Installed Docker Desktop ✅ Ran Data Science loaded Jupyter Notebook through Docker ✅ Understood the Concept of Containers ✅ Learnt about Docker Image & Dockerfile ✅ Created a Customized Docker Image✅ Saved & shared Docker Image Remember, we just scratched the surface. There is so much more learning and explosive material. Images are not only of Jupyter Notebooks. They can be entire operating systems, programming languages and so on. I highly encourage you to take a look at use-cases and references at Docker’s website www.docker.com Please feel free to give me feedback. After all, that’s how we learn and improve!
[ { "code": null, "e": 607, "s": 172, "text": "One of the preliminary steps that you take when you embark on your data science journey is dealing with the installation of different software such as Python, Jyupter Notebook, some IDEs and countless libraries. Once you successfully pass through this, you often encounter situations where your code seems to work fine on your computer, but when you share it with others, it collapses seemingly for no reason. Well, you are not alone!" }, { "code": null, "e": 992, "s": 607, "text": "The good news is that there are some impressive solutions available that range differently on the scale of convenience, accessibility and ease of use. Google Colab is one of them. It is ready to start, comes loaded with lots of useful libraries and has GPU support. It has its limitations too. But it’s not the topic of today’s article. You can learn and experience Google Colab here." }, { "code": null, "e": 1012, "s": 992, "text": "research.google.com" }, { "code": null, "e": 1257, "s": 1012, "text": "In this article, we are going to take a different approach. We will do hands-on first, and the explanation will come later. This approach will demonstrate how easy it is and why you should learn more about it to be a well-versed data scientist." }, { "code": null, "e": 1329, "s": 1257, "text": "Below is a list of key concepts & tasks we will be going through today:" }, { "code": null, "e": 1349, "s": 1329, "text": "1️⃣ What is Docker?" }, { "code": null, "e": 1376, "s": 1349, "text": "2️⃣ Install Docker Desktop" }, { "code": null, "e": 1421, "s": 1376, "text": "3️⃣ Run Data Science loaded Jupyter Notebook" }, { "code": null, "e": 1450, "s": 1421, "text": "4️⃣ Understanding Containers" }, { "code": null, "e": 1485, "s": 1450, "text": "5️⃣ What is an Image & Dockerfile?" }, { "code": null, "e": 1522, "s": 1485, "text": "6️⃣ Create a customized Docker Image" }, { "code": null, "e": 1550, "s": 1522, "text": "7️⃣ Save & share your Image" }, { "code": null, "e": 1575, "s": 1550, "text": "➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖" }, { "code": null, "e": 1615, "s": 1575, "text": "Let’s start discussing them one by one." }, { "code": null, "e": 2217, "s": 1615, "text": "Docker is a company that provides solutions (the name of the solution is Docker as well !) to the problems we described above. In fact it does more than that and is an excellent tool in the developer’s toolbox, but we will stick to its relevance to our data science-related issues. It is a software that helps us build “images” and run “containers” to support and better deliver data science projects. We will explain the concepts of “images” & “containers” later in this article. As mentioned above, we will do hands-on first, and the explanation will come later. You can read more about Docker here." }, { "code": null, "e": 2232, "s": 2217, "text": "www.docker.com" }, { "code": null, "e": 2362, "s": 2232, "text": "Before we begin, I would also recommend creating an account on Docker (free version is fine) to save your projects on Docker Hub." }, { "code": null, "e": 2904, "s": 2362, "text": "Visit this link and install Docker Desktop. It is no different than any other software installation. You can choose the Windows version or Mac Version. For our demonstration, we will use the Windows version. The procedure for Mac is almost identical. Once downloaded, click the downloaded file to install and follow the instructions. The process is straight forward and should go smoothly. If you want to see the process in action before installing, I found a nice 11-minute video on YouTube, that walks you through the installation process." }, { "code": null, "e": 3075, "s": 2904, "text": "Once the installation is complete, you can perform a little check to see if everything is working. Open up your command prompt/terminal and write this code and hit enter:" }, { "code": null, "e": 3085, "s": 3075, "text": "docker -v" }, { "code": null, "e": 3199, "s": 3085, "text": "This should confirm if the installation were successful by providing you with the version of Docker we installed." }, { "code": null, "e": 3296, "s": 3199, "text": "It’s time for the magic. Open up your command prompt/terminal and write down the following code:" }, { "code": null, "e": 3345, "s": 3296, "text": "docker run -p 8888:8888 jupyter/minimal-notebook" }, { "code": null, "e": 3762, "s": 3345, "text": "I will explain this code later, for now just follow these steps. We are doing this for the first time, so it will take some time to get it ready. The next time, rerunning this command won’t take any longer as all the necessary files are already downloaded. Additionally, you will not require any internet connectivity (unlike Google’s Colab) either. Once the process is over, this is how the output should look like:" }, { "code": null, "e": 3996, "s": 3762, "text": "Copy any of the last three lines (these are the addresses) and paste them into any of your browsers (save the token for later use, provided in the address after the word “token”). That will open up a Jupyter Notebook in your browser." }, { "code": null, "e": 4171, "s": 3996, "text": "You will notice that the notebook comes loaded with Python3, Julia & R. Not only that, but many popular data science libraries are already installed and ready to be imported!" }, { "code": null, "e": 4256, "s": 4171, "text": "The 😯😲 😯 part is that NONE of these programs are actually installed on your machine!" }, { "code": null, "e": 4576, "s": 4256, "text": "So if you try to find Python/Julia/R or Jupyter Notebook on your computer, good luck! Even if you had these programs installed previously on your computer, these “dockerized” installations are stand-alone installations that have nothing to do with the applications already installed (or not installed) on your computer." }, { "code": null, "e": 4896, "s": 4576, "text": "This implies that if you create a program or write a code using the Jupyter Notebook we just created, test it, and share (all these things coming later in the article) it with your friend or colleague, it is guaranteed to work as long as your friend or colleague has fired up their Jupyter Notebook the same way we did." }, { "code": null, "e": 5338, "s": 4896, "text": "The story starts with the idea of containers. The idea is not new, though; you might be familiar with the “environment” concept already. It’s almost the same thing. In due course, a data scientist will create and develop many models that will depend upon many libraries or on many other data scientist’s work (we call them dependencies). This will inevitably lead to “contradictions” between all these models as dependencies evolve and grow." }, { "code": null, "e": 6272, "s": 5338, "text": "Let’s start with a very generalized example. Imagine you have a lot of 💰💰💰 and decide to build a plant to produce something for commercial use. You build a factory(which is, for now, is just one big hall), and install all sorts of different machines and workplaces. You then hire skilled workers to do the job. When your business is new and is not at scale things are not complicated, and they go smoothly. But as your business grows and competition increases, you decided to add more sophisticated technologies and advanced processes. Here comes the problem; as you adapt to these new technologies, you realize that some of these processes simply can not work under one roof, e.g. one technology requires a dry environment and in contrast, another one works within a more humid one. Same goes with the people, some need a quiet environment, whereas others need to work with loud and noisy machines (or for many other random reasons)" }, { "code": null, "e": 6337, "s": 6272, "text": "So what is the most intuitive solution that comes to your mind ?" }, { "code": null, "e": 6574, "s": 6337, "text": "Obviously, you will simply build separate rooms (as opposed to construct separate buildings )and halls to make sure that every process and department gets the environment it needs. This solution, is akin to the concept of a “Container”." }, { "code": null, "e": 6883, "s": 6574, "text": "Continuing with our example, now you want to build the same facility in another country or geographical area with the exact same settings. Imagine a technology that can somehow clone your existing production setup, and you can simply port it to the required location. That is akin to “sharing the Container”." }, { "code": null, "e": 7469, "s": 6883, "text": "A more data science related example would be a model you created using version x of sklearn for use-case A. Five months later, sklearn has a new, improved version x+1. You update your library and create another model using the new version ,for another use-case B. Everyone is happy until you run your model for use-case A, which collapses and doesn’t run. It turns out that the old model is not supported anymore by the newer sklearn version. As a result, you can only run the old model (if you go back to install the older sklearn version) or the new model, not both at the same time." }, { "code": null, "e": 7884, "s": 7469, "text": "Again, try to think of a possible solution. A straightforward one will be to have another computer and install the new sklearn version on it. This will, for sure, solve the problem. ❌Please don’t suggest this to anyone!❌ , because for how long can you keep this up? Buying new computers every time you update your sklearn library, not to mention hundreds of other libraries, is definitely not a practical solution." }, { "code": null, "e": 8155, "s": 7884, "text": "What if we install all the software and libraries required for a specific project, “quarantined” in their own space, within one computer or operating system? This way, your model will only stay within its boundaries and will not interfere with whatever is outside of it." }, { "code": null, "e": 8502, "s": 8155, "text": "This is what you call a container; projects and all its dependencies containerized/ isolated /quarantined within one operating system. We can go one step ahead and share that container with others, who can then add and run the container on their machine and execute the same experiment without having to worry about all the dependencies involved." }, { "code": null, "e": 8608, "s": 8502, "text": "At this point, we are ready to introduce two more concepts to get a complete picture; Image & Dockerfile." }, { "code": null, "e": 9145, "s": 8608, "text": "The Image is a seed for the container. It is a “snapshot” of a project at some point in time. It only becomes a container when we “run” it. Think of it as a picture you took of your friend’s beautiful room and later on you plan to arrange your room the same way. The beauty of it all is that we can alter the Image before running and converting it into a container. That alteration comes through a Dockerfile. Dockerfile is a poker face file (it does not have any extension like csv, txt etc.) that contains instructions for the Docker." }, { "code": null, "e": 9459, "s": 9145, "text": "In our demonstration, Jupyter took a snapshot of its project, made an image, and published it on Docker Hub with the name “jupyter/datascience-notebook.” We pulled and ran the Image, making it into a container. We did not alter the Image, though; we just ran it as is. That’s why there was no Dockerfile involved." }, { "code": null, "e": 9835, "s": 9459, "text": "In the next session, we will show an example where we will alter the notebook and add the Tensorflow and a data pre-processing library called preprocess1 before running the container. This time to keep things lighter and faster, I will use another image of Jupyter notebook (called jupyter/minimal-notebook). You can keep the same Image as we used previously, if you want to." }, { "code": null, "e": 10103, "s": 9835, "text": "Let’s move ahead with our previous example, in which we “pulled” the data science loaded Jupyter Notebook from Docker Hub. Only this time, we will add the Tensorflow & preprocess1 library to it through Dockerfile. But first, let’s see what the process will look like." }, { "code": null, "e": 10262, "s": 10103, "text": "📔 If you have and know how to operate MS Visual Studio Code, the process becomes so much easier. For now, we will do the steps assuming we don’t have VS Code." }, { "code": null, "e": 10375, "s": 10262, "text": "1️⃣ Create Project Folder: On your computer, create an empty folder where you want to save your project’s files." }, { "code": null, "e": 10527, "s": 10375, "text": "2️⃣ Create Dockerfile: Inside the folder, create a text file. Open the file and write down the following code (lines starting with # are mere comments)" }, { "code": null, "e": 10689, "s": 10527, "text": "# import pre-built image from data science notebookFROM jupyter/minimal-notebook# Install required librariesRUN pip install tensorflowRUN pip install preprocess1" }, { "code": null, "e": 10882, "s": 10689, "text": "As you can see, the code so far is easy to read and understand. We did nothing more than importing the Jupyter Notebook and installing the libraries we wanted by using “FROM” & “RUN” commands." }, { "code": null, "e": 11085, "s": 10882, "text": "3️⃣ Save the Dockerfile: Close the file, right-click to rename it as “Dockerfile” (make sure to follow the exact spellings and case) , remove the extension (.txt) and save it. Your Docker file is ready!" }, { "code": null, "e": 11110, "s": 11085, "text": "➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖" }, { "code": null, "e": 11430, "s": 11110, "text": "➕ Bonus: Usually, we do all these library installations through a text file called “requirements” (although the name doesn’t matter). You just put the library names along with any specific versions you want and save the file under the same folder where your Dockerfile is. Library requirements in the file go like this:" }, { "code": null, "e": 11467, "s": 11430, "text": "tensorflow==2.2.0preprocess1==0.0.38" }, { "code": null, "e": 11531, "s": 11467, "text": "Here is the code to “add” this text file to your Jupyter Image." }, { "code": null, "e": 11568, "s": 11531, "text": "jupyter-docker-stacks.readthedocs.io" }, { "code": null, "e": 11593, "s": 11568, "text": "➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖" }, { "code": null, "e": 11744, "s": 11593, "text": "4️⃣ Fire up your command prompt, and ‘cd’ to the folder where we created the docker file. Once there, we run the following command to build our Image." }, { "code": null, "e": 11776, "s": 11744, "text": "docker build -t notebook_demo ." }, { "code": null, "e": 12077, "s": 11776, "text": "Again, code is pretty intuitive; it is a docker command to build an image named notebook_demo. “-t” is a flag word used to name/tag the image. In the end, the “dot” means that the Dockerfile we are using is inside the active directory. Hit enter to execute the command line. It should look like this:" }, { "code": null, "e": 12207, "s": 12077, "text": "5️⃣ Run the Image: we are now ready to run the Image we just created. Run the following command in the command prompt / terminal:" }, { "code": null, "e": 12245, "s": 12207, "text": "docker run -p 8888:8888 notebook_demo" }, { "code": null, "e": 12405, "s": 12245, "text": "This command means it is a docker command to run an Image named notebook_demo. Flag word “-p” means to map it to ports 8888 between the container and the host." }, { "code": null, "e": 12637, "s": 12405, "text": "Once done, copy any of the three addresses provided and past it in your browser to open and access your Jupyter Notebook (save the token for later use). Import tensorflow & preprocess1 libraries to make sure we have them correctly." }, { "code": null, "e": 12761, "s": 12637, "text": "We successfully loaded a minimal Jupyter Library, pre-installed with some custom libraries like TensorFlow and preprocess1." }, { "code": null, "e": 13060, "s": 12761, "text": "What good is it if we cant port our work to other computers or share it with other users ? That is out last step! It is worth noting that once you build an image on your computer, it is automatically saved. You can use the run command to access it any time, without needing any internet connection." }, { "code": null, "e": 13355, "s": 13060, "text": "▶️ One option is to save it to the Docker Hub. That makes it public, and anybody can access it just the way we accessed minimal and data science Jupyter Notebook from Docker Hub. One of the issues with this approach is image size when you upload it to Docker Hub as it increases rather quickly." }, { "code": null, "e": 13448, "s": 13355, "text": "we will need to use the following commands to save to Docker Hub in command prompt/terminal:" }, { "code": null, "e": 13650, "s": 13448, "text": "#log into Docker Hubdocker login — username= your_Docker_username#Enter your password when prompted# Push your Image by name, in our case \"notebook_demo\"docker push your_Docker_username/your_image_name" }, { "code": null, "e": 13887, "s": 13650, "text": "That’s it! your Image is available to use publicly. Anyone who has docker installed , can easily access the same image, with the exact dependencies that you added (tensorflow & preprocess1) with the command we are already familiar with:" }, { "code": null, "e": 13925, "s": 13887, "text": "docker run -p 8888:8888 notebook_demo" }, { "code": null, "e": 14114, "s": 13925, "text": "▶️The other option is to save it as a tar file , we need to run the following command in command prompt/ terminal. You need to be in the same directory where you want to save the tar file." }, { "code": null, "e": 14261, "s": 14114, "text": "# save it under the active directory docker save notebook_demo > notebook_demo.tar# you can load it this waydocker load — input notebook_demo.tar" }, { "code": null, "e": 14340, "s": 14261, "text": "Congratulations! If you have made so far, you deserve a big round of applause!" }, { "code": null, "e": 14366, "s": 14340, "text": "👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏" }, { "code": null, "e": 14392, "s": 14366, "text": "👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏👏" }, { "code": null, "e": 14444, "s": 14392, "text": "In this session we learnt and applied the following" }, { "code": null, "e": 14692, "s": 14444, "text": "✅ What is Docker? ✅ Installed Docker Desktop ✅ Ran Data Science loaded Jupyter Notebook through Docker ✅ Understood the Concept of Containers ✅ Learnt about Docker Image & Dockerfile ✅ Created a Customized Docker Image✅ Saved & shared Docker Image" }, { "code": null, "e": 14987, "s": 14692, "text": "Remember, we just scratched the surface. There is so much more learning and explosive material. Images are not only of Jupyter Notebooks. They can be entire operating systems, programming languages and so on. I highly encourage you to take a look at use-cases and references at Docker’s website" }, { "code": null, "e": 15002, "s": 14987, "text": "www.docker.com" } ]