title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java Collections | Set 8 (TreeSet) | Practice | GeeksforGeeks
Given n strings added in a TreeSet and four characters a,b,c,d. Firstly print all the strings which are less than a , then print all the strings which are greater than or equal to b. In the end print all the strings which are greater than or equal to c and less than d i.e between c and d ( excluding d ). Input: The first line of input is T denoting the number of testcases. First line consists of an integer n. Next line contains n spaced strings. Last line of each test case consists of 4 space separated characters. Output: For each test case output will be in three lines: First Line : Print all the strings which are less than a (char variable). Second Line : Print all the strings which are greater than or equal to b (char variable). Third Line : Print all the strings which are greater than or equal to c and less than d i.e between c and d ( excluding d ). Constraints: 1<=T<=100 1<=N<=100 1<=Length of string<=100 Example: Input: 1 3 sa ka da s k c s Output: [da, ka] [ka, sa] [da, ka] 0 hitentandon3 months ago System.out.println(ts.headSet(a+"")); System.out.println(ts.tailSet(b+"")); System.out.println(ts.subSet(c+"",d+"")); +1 rajat25gupta3 months ago Correct Java Solution void task(TreeSet<String> ts,char a,char b,char c,char d) { // Add your code here. Print the output here itself. System.out.println(ts.headSet(Character.toString(a))); System.out.println(ts.tailSet(Character.toString(b))); System.out.println(ts.subSet(Character.toString(c), Character.toString(d))); } 0 rr71951424 months ago Correct AnswerExecution Time:0.3 sec //---CODE IN JAVA--- TreeSet<String> ts1 = new TreeSet<>(); TreeSet<String> ts2 = new TreeSet<>(); TreeSet<String> ts3 = new TreeSet<>(); java.util.Iterator<String> it = ts.iterator(); while(it.hasNext()){ String str = it.next().toString(); char cc = str.charAt(0); if(cc<a){ ts1.add(str); } if(cc>=b){ ts2.add(str); } if(cc>=c && cc<d){ ts3.add(str); } } System.out.println(ts1); System.out.println(ts2); System.out.println(ts3); 0 Aaditya Burujwale1 year ago Aaditya Burujwale Java Solution Execution Time - 0.42 Sec 0 Amir Ansari1 year ago Amir Ansari Correct AnswerExecution Time:0.49 void task(TreeSet<string> ts,char a,char b,char c,char d) { // Add your code here. Print the output here itself. java.util.Set<string> setA = new java.util.TreeSet<>(); java.util.Set<string> setB = new java.util.TreeSet<>(); java.util.Set<string> setC = new java.util.TreeSet<>(); java.util.Iterator it = ts.iterator(); while(it.hasNext()) { String str = it.next().toString(); char ch = str.charAt(0); if(ch < a) setA.add(str); if(ch >= b) setB.add(str); if(ch >= c && ch <d) setc.add(str);="" }="" system.out.println(seta);="" system.out.println(setb);="" system.out.println(setc);="" }=""> 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": 545, "s": 238, "text": "Given n strings added in a TreeSet and four characters a,b,c,d. Firstly print all the strings which are less than a , then print all the strings which are greater than or equal to b. In the end print all the strings which are greater than or equal to c and less than d i.e between c and d ( excluding d ). " }, { "code": null, "e": 552, "s": 545, "text": "Input:" }, { "code": null, "e": 759, "s": 552, "text": "The first line of input is T denoting the number of testcases. First line consists of an integer n. Next line contains n spaced strings. Last line of each test case consists of 4 space separated characters." }, { "code": null, "e": 767, "s": 759, "text": "Output:" }, { "code": null, "e": 1109, "s": 767, "text": "For each test case output will be in three lines:\nFirst Line : Print all the strings which are less than a (char variable).\nSecond Line : Print all the strings which are greater than or equal to b (char variable).\nThird Line : Print all the strings which are greater than or equal to c and less than d i.e between c and d ( excluding d ). " }, { "code": null, "e": 1122, "s": 1109, "text": "Constraints:" }, { "code": null, "e": 1167, "s": 1122, "text": "1<=T<=100\n1<=N<=100\n1<=Length of string<=100" }, { "code": null, "e": 1176, "s": 1167, "text": "Example:" }, { "code": null, "e": 1183, "s": 1176, "text": "Input:" }, { "code": null, "e": 1204, "s": 1183, "text": "1\n3\nsa ka da\ns k c s" }, { "code": null, "e": 1212, "s": 1204, "text": "Output:" }, { "code": null, "e": 1239, "s": 1212, "text": "[da, ka]\n[ka, sa]\n[da, ka]" }, { "code": null, "e": 1241, "s": 1239, "text": "0" }, { "code": null, "e": 1265, "s": 1241, "text": "hitentandon3 months ago" }, { "code": null, "e": 1395, "s": 1265, "text": "System.out.println(ts.headSet(a+\"\"));\n System.out.println(ts.tailSet(b+\"\"));\n System.out.println(ts.subSet(c+\"\",d+\"\"));" }, { "code": null, "e": 1398, "s": 1395, "text": "+1" }, { "code": null, "e": 1423, "s": 1398, "text": "rajat25gupta3 months ago" }, { "code": null, "e": 1445, "s": 1423, "text": "Correct Java Solution" }, { "code": null, "e": 1777, "s": 1447, "text": "void task(TreeSet<String> ts,char a,char b,char c,char d) { // Add your code here. Print the output here itself. System.out.println(ts.headSet(Character.toString(a))); System.out.println(ts.tailSet(Character.toString(b))); System.out.println(ts.subSet(Character.toString(c), Character.toString(d))); }" }, { "code": null, "e": 1779, "s": 1777, "text": "0" }, { "code": null, "e": 1801, "s": 1779, "text": "rr71951424 months ago" }, { "code": null, "e": 1838, "s": 1801, "text": "Correct AnswerExecution Time:0.3 sec" }, { "code": null, "e": 1859, "s": 1838, "text": "//---CODE IN JAVA---" }, { "code": null, "e": 2440, "s": 1859, "text": " TreeSet<String> ts1 = new TreeSet<>(); TreeSet<String> ts2 = new TreeSet<>(); TreeSet<String> ts3 = new TreeSet<>(); java.util.Iterator<String> it = ts.iterator(); while(it.hasNext()){ String str = it.next().toString(); char cc = str.charAt(0); if(cc<a){ ts1.add(str); } if(cc>=b){ ts2.add(str); } if(cc>=c && cc<d){ ts3.add(str); } } System.out.println(ts1); System.out.println(ts2); System.out.println(ts3);" }, { "code": null, "e": 2442, "s": 2440, "text": "0" }, { "code": null, "e": 2470, "s": 2442, "text": "Aaditya Burujwale1 year ago" }, { "code": null, "e": 2488, "s": 2470, "text": "Aaditya Burujwale" }, { "code": null, "e": 2529, "s": 2488, "text": "Java Solution Execution Time - 0.42 Sec " }, { "code": null, "e": 2531, "s": 2529, "text": "0" }, { "code": null, "e": 2553, "s": 2531, "text": "Amir Ansari1 year ago" }, { "code": null, "e": 2565, "s": 2553, "text": "Amir Ansari" }, { "code": null, "e": 2599, "s": 2565, "text": "Correct AnswerExecution Time:0.49" }, { "code": null, "e": 2905, "s": 2599, "text": " void task(TreeSet<string> ts,char a,char b,char c,char d) { // Add your code here. Print the output here itself. java.util.Set<string> setA = new java.util.TreeSet<>(); java.util.Set<string> setB = new java.util.TreeSet<>(); java.util.Set<string> setC = new java.util.TreeSet<>();" }, { "code": null, "e": 2944, "s": 2905, "text": "java.util.Iterator it = ts.iterator();" }, { "code": null, "e": 3072, "s": 2944, "text": "while(it.hasNext()) { String str = it.next().toString(); char ch = str.charAt(0); if(ch < a) setA.add(str);" }, { "code": null, "e": 3111, "s": 3072, "text": " if(ch >= b) setB.add(str);" }, { "code": null, "e": 3254, "s": 3111, "text": " if(ch >= c && ch <d) setc.add(str);=\"\" }=\"\" system.out.println(seta);=\"\" system.out.println(setb);=\"\" system.out.println(setc);=\"\" }=\"\">" }, { "code": null, "e": 3400, "s": 3254, "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": 3436, "s": 3400, "text": " Login to access your submissions. " }, { "code": null, "e": 3446, "s": 3436, "text": "\nProblem\n" }, { "code": null, "e": 3456, "s": 3446, "text": "\nContest\n" }, { "code": null, "e": 3519, "s": 3456, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3667, "s": 3519, "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": 3875, "s": 3667, "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": 3981, "s": 3875, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Dictionary.Clear Method in C#
The Dictionary.Clear() method in C# removes all key/value pairs from the Dictionary<TKey,TValue>. public void Clear(); Let us now see an example to implement the Dictionary.Clear() method − using System; using System.Collections.Generic; public class Demo { public static void Main(){ Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("One", "John"); dict.Add("Two", "Tom"); dict.Add("Three", "Jacob"); dict.Add("Four", "Kevin"); dict.Add("Five", "Nathan"); Console.WriteLine("Count of elements = "+dict.Count); Console.WriteLine("\nKey/value pairs..."); foreach(KeyValuePair<string, string> res in dict){ Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value); } dict.Clear(); Console.WriteLine("Cleared Key/value pairs..."); foreach(KeyValuePair<string, string> res in dict){ Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value); } Console.WriteLine("Count of elements now = "+dict.Count); } } This will produce the following output − Count of elements = 5 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Cleared Key/value pairs... Count of elements now = 0 Let us now see another example to implement the Dictionary.Clear() method − using System; using System.Collections.Generic; public class Demo { public static void Main(){ Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("One", "John"); dict.Add("Two", "Tom"); dict.Add("Three", "Jacob"); dict.Add("Four", "Kevin"); dict.Add("Five", "Nathan"); Console.WriteLine("Count of elements = "+dict.Count); dict.Add("Six", "Anne"); dict.Add("Seven", "Katoe"); Console.WriteLine("Count of elements (updated) = "+dict.Count); Console.WriteLine("Key/value pairs..."); foreach(KeyValuePair<string, string> res in dict){ Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value); } dict.Clear(); Console.WriteLine("Cleared Key/value pairs..."); foreach(KeyValuePair<string, string> res in dict){ Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value); } } } This will produce the following output − Count of elements = 5 Count of elements (updated) = 7 Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan Key = Six, Value = Anne Key = Seven, Value = Katoe Cleared Key/value pairs...
[ { "code": null, "e": 1160, "s": 1062, "text": "The Dictionary.Clear() method in C# removes all key/value pairs from the Dictionary<TKey,TValue>." }, { "code": null, "e": 1181, "s": 1160, "text": "public void Clear();" }, { "code": null, "e": 1252, "s": 1181, "text": "Let us now see an example to implement the Dictionary.Clear() method −" }, { "code": null, "e": 2125, "s": 1252, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Dictionary<string, string> dict =\n new Dictionary<string, string>();\n dict.Add(\"One\", \"John\");\n dict.Add(\"Two\", \"Tom\");\n dict.Add(\"Three\", \"Jacob\");\n dict.Add(\"Four\", \"Kevin\");\n dict.Add(\"Five\", \"Nathan\");\n Console.WriteLine(\"Count of elements = \"+dict.Count);\n Console.WriteLine(\"\\nKey/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n dict.Clear();\n Console.WriteLine(\"Cleared Key/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n Console.WriteLine(\"Count of elements now = \"+dict.Count);\n }\n}" }, { "code": null, "e": 2166, "s": 2125, "text": "This will produce the following output −" }, { "code": null, "e": 2387, "s": 2166, "text": "Count of elements = 5\nKey/value pairs...\nKey = One, Value = John\nKey = Two, Value = Tom\nKey = Three, Value = Jacob\nKey = Four, Value = Kevin\nKey = Five, Value = Nathan\nCleared Key/value pairs...\nCount of elements now = 0" }, { "code": null, "e": 2463, "s": 2387, "text": "Let us now see another example to implement the Dictionary.Clear() method −" }, { "code": null, "e": 3405, "s": 2463, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Dictionary<string, string> dict =\n new Dictionary<string, string>();\n dict.Add(\"One\", \"John\");\n dict.Add(\"Two\", \"Tom\");\n dict.Add(\"Three\", \"Jacob\");\n dict.Add(\"Four\", \"Kevin\");\n dict.Add(\"Five\", \"Nathan\");\n Console.WriteLine(\"Count of elements = \"+dict.Count);\n dict.Add(\"Six\", \"Anne\");\n dict.Add(\"Seven\", \"Katoe\");\n Console.WriteLine(\"Count of elements (updated) = \"+dict.Count);\n Console.WriteLine(\"Key/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n dict.Clear();\n Console.WriteLine(\"Cleared Key/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n }\n}" }, { "code": null, "e": 3446, "s": 3405, "text": "This will produce the following output −" }, { "code": null, "e": 3724, "s": 3446, "text": "Count of elements = 5\nCount of elements (updated) = 7\nKey/value pairs...\nKey = One, Value = John\nKey = Two, Value = Tom\nKey = Three, Value = Jacob\nKey = Four, Value = Kevin\nKey = Five, Value = Nathan\nKey = Six, Value = Anne\nKey = Seven, Value = Katoe\nCleared Key/value pairs..." } ]
Java Program for Count ways to reach the n'th stair - GeeksforGeeks
02 Jan, 2019 There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top. Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles Java class stairs { // A simple recursive program to find n'th fibonacci number static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } // Returns number of ways to reach s'th stair static int countWays(int s) { return fib(s + 1); } /* Driver program to test above function */ public static void main(String args[]) { int s = 4; System.out.println("Number of ways = " + countWays(s)); }} /* This code is contributed by Rajat Mishra */ Number of ways = 5 The time complexity of the above implementation is exponential (golden ratio raised to power n). It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations. Java class stairs { // A recursive function used by countWays static int countWaysUtil(int n, int m) { if (n <= 1) return n; int res = 0; for (int i = 1; i <= m && i <= n; i++) res += countWaysUtil(n - i, m); return res; } // Returns number of ways to reach s'th stair static int countWays(int s, int m) { return countWaysUtil(s + 1, m); } /* Driver program to test above function */ public static void main(String args[]) { int s = 4, m = 2; System.out.println("Number of ways = " + countWays(s, m)); }} /* This code is contributed by Rajat Mishra */ Number of ways = 5 Java // Java program to count number of ways to reach n't stair when// a person can climb 1, 2, ..m stairs at a time class GFG { // A recursive function used by countWays static int countWaysUtil(int n, int m) { int res[] = new int[n]; res[0] = 1; res[1] = 1; for (int i = 2; i < n; i++) { res[i] = 0; for (int j = 1; j <= m && j <= i; j++) res[i] += res[i - j]; } return res[n - 1]; } // Returns number of ways to reach s'th stair static int countWays(int s, int m) { return countWaysUtil(s + 1, m); } // Driver method public static void main(String[] args) { int s = 4, m = 2; System.out.println("Number of ways = " + countWays(s, m)); }} Number of ways = 5 Please refer complete article on Count ways to reach the n’th stair for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Iterate HashMap in Java? Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Modulo or Remainder Operator in Java Java Program to Convert String to String Array Java Program to Find Sum of Array Elements How to Iterate LinkedList in Java? How to convert Date to String in Java How to Replace a Element in Java ArrayList?
[ { "code": null, "e": 24513, "s": 24485, "text": "\n02 Jan, 2019" }, { "code": null, "e": 24704, "s": 24513, "text": "There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top." }, { "code": null, "e": 24850, "s": 24704, "text": "Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles" }, { "code": null, "e": 24855, "s": 24850, "text": "Java" }, { "code": "class stairs { // A simple recursive program to find n'th fibonacci number static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } // Returns number of ways to reach s'th stair static int countWays(int s) { return fib(s + 1); } /* Driver program to test above function */ public static void main(String args[]) { int s = 4; System.out.println(\"Number of ways = \" + countWays(s)); }} /* This code is contributed by Rajat Mishra */", "e": 25395, "s": 24855, "text": null }, { "code": null, "e": 25415, "s": 25395, "text": "Number of ways = 5\n" }, { "code": null, "e": 25621, "s": 25415, "text": "The time complexity of the above implementation is exponential (golden ratio raised to power n). It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations." }, { "code": null, "e": 25626, "s": 25621, "text": "Java" }, { "code": "class stairs { // A recursive function used by countWays static int countWaysUtil(int n, int m) { if (n <= 1) return n; int res = 0; for (int i = 1; i <= m && i <= n; i++) res += countWaysUtil(n - i, m); return res; } // Returns number of ways to reach s'th stair static int countWays(int s, int m) { return countWaysUtil(s + 1, m); } /* Driver program to test above function */ public static void main(String args[]) { int s = 4, m = 2; System.out.println(\"Number of ways = \" + countWays(s, m)); }} /* This code is contributed by Rajat Mishra */", "e": 26284, "s": 25626, "text": null }, { "code": null, "e": 26304, "s": 26284, "text": "Number of ways = 5\n" }, { "code": null, "e": 26309, "s": 26304, "text": "Java" }, { "code": "// Java program to count number of ways to reach n't stair when// a person can climb 1, 2, ..m stairs at a time class GFG { // A recursive function used by countWays static int countWaysUtil(int n, int m) { int res[] = new int[n]; res[0] = 1; res[1] = 1; for (int i = 2; i < n; i++) { res[i] = 0; for (int j = 1; j <= m && j <= i; j++) res[i] += res[i - j]; } return res[n - 1]; } // Returns number of ways to reach s'th stair static int countWays(int s, int m) { return countWaysUtil(s + 1, m); } // Driver method public static void main(String[] args) { int s = 4, m = 2; System.out.println(\"Number of ways = \" + countWays(s, m)); }}", "e": 27086, "s": 26309, "text": null }, { "code": null, "e": 27106, "s": 27086, "text": "Number of ways = 5\n" }, { "code": null, "e": 27192, "s": 27106, "text": "Please refer complete article on Count ways to reach the n’th stair for more details!" }, { "code": null, "e": 27206, "s": 27192, "text": "Java Programs" }, { "code": null, "e": 27304, "s": 27206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27313, "s": 27304, "text": "Comments" }, { "code": null, "e": 27326, "s": 27313, "text": "Old Comments" }, { "code": null, "e": 27358, "s": 27326, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 27406, "s": 27358, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 27457, "s": 27406, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 27491, "s": 27457, "text": "Java Program to Write into a File" }, { "code": null, "e": 27528, "s": 27491, "text": "Modulo or Remainder Operator in Java" }, { "code": null, "e": 27575, "s": 27528, "text": "Java Program to Convert String to String Array" }, { "code": null, "e": 27618, "s": 27575, "text": "Java Program to Find Sum of Array Elements" }, { "code": null, "e": 27653, "s": 27618, "text": "How to Iterate LinkedList in Java?" }, { "code": null, "e": 27691, "s": 27653, "text": "How to convert Date to String in Java" } ]
Benchmark M1 vs Xeon vs Core i5 vs K80 and T4 | by Fabrice Daniel | Towards Data Science
Since their launch in November, Apple Silicon M1 Macs are showing very impressive performances in many benchmarks. These new processors are so fast that many tests compare MacBook Air or Pro to high-end desktop computers instead of staying in the laptop range. It usually does not make sense in benchmark. But here things are different as M1 is faster than most of them for only a fraction of their energy consumption. Apple is working on an Apple Silicon native version of TensorFlow capable to benefit from the full potential of the M1. On November 18th Google has published a benchmark showing performances increase compared to previous versions of TensorFlow on Macs. As a consequence, machine learning engineers now have very high expectations about Apple Silicon. But we should not forget one important fact: M1 Macs starts under $1,000, so is it reasonable to compare them with $5,000 Xeon(R) Platinum processors? or to expect competing with a $2,000 Nvidia GPU? In this article I benchmark my M1 MacBook Air against a set of configurations I use in my day to day work for Machine Learning. On the M1, I installed TensorFlow 2.4 under a Conda environment with many other packages like pandas, scikit-learn, numpy and JupyterLab as explained in my previous article. This benchmark consists of a python program running a sequence of MLP, CNN and LSTM models training on Fashion MNIST1 for three different batch size of 32, 128 and 512 samples. It also uses a validation set to be consistent with the way most of training are performed in real life applications. Then a test set is used to evaluate the model after the training, making sure everything works well. So, the training, validation and test set sizes are respectively 50000, 10000, 10000. Today this alpha version of TensorFlow 2.4 still have some issues and requires workarounds to make it work in some situations. Eager mode can only work on CPU. Training on GPU requires to force the graph mode. This is performed by the following code from tensorflow.python.compiler.mlcompute import mlcomputefrom tensorflow.python.framework.ops import disable_eager_executiondisable_eager_execution()mlcompute.set_mlc_device(device_name='gpu')print(tf.executing_eagerly()) Evaluating a trained model fails in two situations: In graph mode (CPU or GPU), when the batch size is different from the training batch size (raises an exception) In any case, for LSTM when batch size is lower than the training batch size (returns a very low accuracy in eager mode) The solution simply consists to always set the same batch size for training and for evaluation as in the following code. model.evaluate(test_images, test_labels, batch_size=128) The three models are quite simple and summarized below. MLP model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=X_train.shape[1:]), tf.keras.layers.Dense(512,activation='relu'), tf.keras.layers.Dropout(rate=0.2), tf.keras.layers.Dense(64,activation='relu'), tf.keras.layers.Dense(10,activation='softmax')]) CNN model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32,(3,3),activation = 'relu',input_shape=X_train.shape[1:]), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64,activation='relu'), tf.keras.layers.Dense(10,activation='softmax')]) LSTM model = tf.keras.models.Sequential([ tf.keras.layers.LSTM(128,input_shape=X_train.shape[1:]), tf.keras.layers.Dense(10,activation='softmax')]) They are all using the following optimizer and loss function. model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) Fashion MNIST from tf.keras.dataset has integer labels, so instead of converting them to one hot tensors, I directly use a sparse categorical cross entropy loss function. The following plots shows the results for trainings on CPU. In CPU training, the MacBook Air M1 exceed the performances of the 8 cores Intel(R) Xeon(R) Platinum instance and iMac 27" in any situation. The following plot shows how many times other devices are slower than M1 CPU. For MLP and LSTM M1 is about 2 to 4 times faster than iMac 27" Core i5 and 8 cores Xeon(R) Platinum instance. For CNN, M1 is roughly 1.5 times faster. Here are the results for M1 GPU compared to Nvidia Tesla K80 and T4. In GPU training the situation is very different as the M1 is much slower than the two GPUs except in one case for a convnet trained on K80 with a batch size of 32. The following plot shows how many times other devices are faster than M1 CPU (to make it more readable I inverted the representation compared to the similar previous plot for CPU). Here K80 and T4 instances are much faster than M1 GPU in nearly all the situations. The difference even increases with the batch size. K80 is about 2 to 8 times faster than M1 while T4 is 3 to 13 times faster depending on the case. So does the M1 GPU is really used when we force it in graph mode? The answer is Yes. When looking at the GPU usage on M1 while training, the history shows a 70% to 100% GPU load average while CPU never exceeds 20% to 30% on some cores only. Now we should not forget that M1 is an integrated 8 GPU cores with 128 execution units for 2.6 TFlops (FP32) while a T4 has 2 560 Cuda Cores for 8.1 TFlops (FP32). The price is also not the same at all. We should wait for Apple to complete its ML Compute integration to TensorFlow before drawing conclusions but even if we can get some improvements in the near future there is only a very little chance for M1 to compete with such high-end cards. But we can fairly expect the next Apple Silicon processors to reduce this gap. An interesting fact when doing these tests is that training on GPU is nearly always much slower than training on CPU. The following plots shows these differences for each case. As we observe here, training on the CPU is much faster than on GPU for MLP and LSTM while on CNN, starting from 128 samples batch size the GPU is slightly faster. The last two plots compare training on M1 CPU with K80 and T4 GPUs. From these tests it appears that for training MLP, M1 CPU is the best option for training LSTM, M1 CPU is a very good option, beating a K80 and only 2 times slower than a T4, which is not that bad considering the power and price of this high-end card for training CNN, M1 can be used as a descent alternative to a K80 with only a factor 2 to 3 but a T4 is still much faster Of course, these metrics can only be considered for similar neural network types and depths as used in this test. As a machine learning engineer, for my day-to-day personal research, using TensorFlow on my MacBook Air M1 is really a very good option. My research mostly focuses on structured data and time series, so even if I sometimes use CNN 1D units, most of the models I create are based on Dense, GRU or LSTM units so M1 is clearly the best overall option for me. For people working mostly with convnet, Apple Silicon M1 is not convincing at the moment, so a dedicated GPU is still the way to go. Apple is still working on ML Compute integration to TensorFlow. If any new release shows a significant performance increase at some point, I will update this article accordingly. Thank you for reading. After a comment from a reader I double checked the 8 core Xeon(R) instance. It’s using multithreading. Part 2 of this article is available here. [1] Han Xiao and Kashif Rasul and Roland Vollgraf, Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms (2017)
[ { "code": null, "e": 591, "s": 172, "text": "Since their launch in November, Apple Silicon M1 Macs are showing very impressive performances in many benchmarks. These new processors are so fast that many tests compare MacBook Air or Pro to high-end desktop computers instead of staying in the laptop range. It usually does not make sense in benchmark. But here things are different as M1 is faster than most of them for only a fraction of their energy consumption." }, { "code": null, "e": 844, "s": 591, "text": "Apple is working on an Apple Silicon native version of TensorFlow capable to benefit from the full potential of the M1. On November 18th Google has published a benchmark showing performances increase compared to previous versions of TensorFlow on Macs." }, { "code": null, "e": 942, "s": 844, "text": "As a consequence, machine learning engineers now have very high expectations about Apple Silicon." }, { "code": null, "e": 1142, "s": 942, "text": "But we should not forget one important fact: M1 Macs starts under $1,000, so is it reasonable to compare them with $5,000 Xeon(R) Platinum processors? or to expect competing with a $2,000 Nvidia GPU?" }, { "code": null, "e": 1270, "s": 1142, "text": "In this article I benchmark my M1 MacBook Air against a set of configurations I use in my day to day work for Machine Learning." }, { "code": null, "e": 1444, "s": 1270, "text": "On the M1, I installed TensorFlow 2.4 under a Conda environment with many other packages like pandas, scikit-learn, numpy and JupyterLab as explained in my previous article." }, { "code": null, "e": 1621, "s": 1444, "text": "This benchmark consists of a python program running a sequence of MLP, CNN and LSTM models training on Fashion MNIST1 for three different batch size of 32, 128 and 512 samples." }, { "code": null, "e": 1926, "s": 1621, "text": "It also uses a validation set to be consistent with the way most of training are performed in real life applications. Then a test set is used to evaluate the model after the training, making sure everything works well. So, the training, validation and test set sizes are respectively 50000, 10000, 10000." }, { "code": null, "e": 2053, "s": 1926, "text": "Today this alpha version of TensorFlow 2.4 still have some issues and requires workarounds to make it work in some situations." }, { "code": null, "e": 2176, "s": 2053, "text": "Eager mode can only work on CPU. Training on GPU requires to force the graph mode. This is performed by the following code" }, { "code": null, "e": 2399, "s": 2176, "text": "from tensorflow.python.compiler.mlcompute import mlcomputefrom tensorflow.python.framework.ops import disable_eager_executiondisable_eager_execution()mlcompute.set_mlc_device(device_name='gpu')print(tf.executing_eagerly())" }, { "code": null, "e": 2451, "s": 2399, "text": "Evaluating a trained model fails in two situations:" }, { "code": null, "e": 2563, "s": 2451, "text": "In graph mode (CPU or GPU), when the batch size is different from the training batch size (raises an exception)" }, { "code": null, "e": 2683, "s": 2563, "text": "In any case, for LSTM when batch size is lower than the training batch size (returns a very low accuracy in eager mode)" }, { "code": null, "e": 2804, "s": 2683, "text": "The solution simply consists to always set the same batch size for training and for evaluation as in the following code." }, { "code": null, "e": 2861, "s": 2804, "text": "model.evaluate(test_images, test_labels, batch_size=128)" }, { "code": null, "e": 2917, "s": 2861, "text": "The three models are quite simple and summarized below." }, { "code": null, "e": 2921, "s": 2917, "text": "MLP" }, { "code": null, "e": 3206, "s": 2921, "text": "model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=X_train.shape[1:]), tf.keras.layers.Dense(512,activation='relu'), tf.keras.layers.Dropout(rate=0.2), tf.keras.layers.Dense(64,activation='relu'), tf.keras.layers.Dense(10,activation='softmax')])" }, { "code": null, "e": 3210, "s": 3206, "text": "CNN" }, { "code": null, "e": 3658, "s": 3210, "text": "model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32,(3,3),activation = 'relu',input_shape=X_train.shape[1:]), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64,activation='relu'), tf.keras.layers.Dense(10,activation='softmax')])" }, { "code": null, "e": 3663, "s": 3658, "text": "LSTM" }, { "code": null, "e": 3812, "s": 3663, "text": "model = tf.keras.models.Sequential([ tf.keras.layers.LSTM(128,input_shape=X_train.shape[1:]), tf.keras.layers.Dense(10,activation='softmax')])" }, { "code": null, "e": 3874, "s": 3812, "text": "They are all using the following optimizer and loss function." }, { "code": null, "e": 3994, "s": 3874, "text": "model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 4165, "s": 3994, "text": "Fashion MNIST from tf.keras.dataset has integer labels, so instead of converting them to one hot tensors, I directly use a sparse categorical cross entropy loss function." }, { "code": null, "e": 4225, "s": 4165, "text": "The following plots shows the results for trainings on CPU." }, { "code": null, "e": 4366, "s": 4225, "text": "In CPU training, the MacBook Air M1 exceed the performances of the 8 cores Intel(R) Xeon(R) Platinum instance and iMac 27\" in any situation." }, { "code": null, "e": 4444, "s": 4366, "text": "The following plot shows how many times other devices are slower than M1 CPU." }, { "code": null, "e": 4595, "s": 4444, "text": "For MLP and LSTM M1 is about 2 to 4 times faster than iMac 27\" Core i5 and 8 cores Xeon(R) Platinum instance. For CNN, M1 is roughly 1.5 times faster." }, { "code": null, "e": 4664, "s": 4595, "text": "Here are the results for M1 GPU compared to Nvidia Tesla K80 and T4." }, { "code": null, "e": 4828, "s": 4664, "text": "In GPU training the situation is very different as the M1 is much slower than the two GPUs except in one case for a convnet trained on K80 with a batch size of 32." }, { "code": null, "e": 5009, "s": 4828, "text": "The following plot shows how many times other devices are faster than M1 CPU (to make it more readable I inverted the representation compared to the similar previous plot for CPU)." }, { "code": null, "e": 5241, "s": 5009, "text": "Here K80 and T4 instances are much faster than M1 GPU in nearly all the situations. The difference even increases with the batch size. K80 is about 2 to 8 times faster than M1 while T4 is 3 to 13 times faster depending on the case." }, { "code": null, "e": 5307, "s": 5241, "text": "So does the M1 GPU is really used when we force it in graph mode?" }, { "code": null, "e": 5482, "s": 5307, "text": "The answer is Yes. When looking at the GPU usage on M1 while training, the history shows a 70% to 100% GPU load average while CPU never exceeds 20% to 30% on some cores only." }, { "code": null, "e": 5685, "s": 5482, "text": "Now we should not forget that M1 is an integrated 8 GPU cores with 128 execution units for 2.6 TFlops (FP32) while a T4 has 2 560 Cuda Cores for 8.1 TFlops (FP32). The price is also not the same at all." }, { "code": null, "e": 6008, "s": 5685, "text": "We should wait for Apple to complete its ML Compute integration to TensorFlow before drawing conclusions but even if we can get some improvements in the near future there is only a very little chance for M1 to compete with such high-end cards. But we can fairly expect the next Apple Silicon processors to reduce this gap." }, { "code": null, "e": 6185, "s": 6008, "text": "An interesting fact when doing these tests is that training on GPU is nearly always much slower than training on CPU. The following plots shows these differences for each case." }, { "code": null, "e": 6348, "s": 6185, "text": "As we observe here, training on the CPU is much faster than on GPU for MLP and LSTM while on CNN, starting from 128 samples batch size the GPU is slightly faster." }, { "code": null, "e": 6416, "s": 6348, "text": "The last two plots compare training on M1 CPU with K80 and T4 GPUs." }, { "code": null, "e": 6449, "s": 6416, "text": "From these tests it appears that" }, { "code": null, "e": 6493, "s": 6449, "text": "for training MLP, M1 CPU is the best option" }, { "code": null, "e": 6667, "s": 6493, "text": "for training LSTM, M1 CPU is a very good option, beating a K80 and only 2 times slower than a T4, which is not that bad considering the power and price of this high-end card" }, { "code": null, "e": 6790, "s": 6667, "text": "for training CNN, M1 can be used as a descent alternative to a K80 with only a factor 2 to 3 but a T4 is still much faster" }, { "code": null, "e": 6904, "s": 6790, "text": "Of course, these metrics can only be considered for similar neural network types and depths as used in this test." }, { "code": null, "e": 7041, "s": 6904, "text": "As a machine learning engineer, for my day-to-day personal research, using TensorFlow on my MacBook Air M1 is really a very good option." }, { "code": null, "e": 7260, "s": 7041, "text": "My research mostly focuses on structured data and time series, so even if I sometimes use CNN 1D units, most of the models I create are based on Dense, GRU or LSTM units so M1 is clearly the best overall option for me." }, { "code": null, "e": 7393, "s": 7260, "text": "For people working mostly with convnet, Apple Silicon M1 is not convincing at the moment, so a dedicated GPU is still the way to go." }, { "code": null, "e": 7572, "s": 7393, "text": "Apple is still working on ML Compute integration to TensorFlow. If any new release shows a significant performance increase at some point, I will update this article accordingly." }, { "code": null, "e": 7595, "s": 7572, "text": "Thank you for reading." }, { "code": null, "e": 7698, "s": 7595, "text": "After a comment from a reader I double checked the 8 core Xeon(R) instance. It’s using multithreading." }, { "code": null, "e": 7740, "s": 7698, "text": "Part 2 of this article is available here." } ]
Simple Ways to Improve Your Matplotlib | by Kimberly Fessel | Towards Data Science
Matplotlib is typically the first data visualization package that Python programmers learn. While its users can create basic figures with just a few lines of code, these resulting default plots often prove insufficient in both design aesthetics and communicative power. Simple adjustments can lead to dramatic improvements, however, and in this post, I will share several tips on how to upgrade your Matplotlib figures. In the examples that follow, I will be using information found in this Kaggle dataset about cereals. I have normalized three features (calories, fat, and sugar) by serving size to better compare cereal nutrition and ratings. Details about these data transformations and the code used to generate each example figure can be found on my GitHub. The first Matplotlib default to update is that black box surrounding each plot, comprised of four so-called “spines.” To adjust them we first get our figure’s axes via pyplot and then change the visibility of each individual spine as desired. Let’s say, for example, we want to remove the top and right spines. If we have imported Matplotlib’s pyplot submodule with: from matplotlib import pyplot as plt we just need to add the following to our code: plt.gca().spines['top'].set_visible(False)plt.gca().spines['right'].set_visible(False) and the top and right spines will no longer appear. Removing these distracting lines allows more focus to be directed toward your data. Matplotlib’s default colors just got an upgrade but you can still easily change them to make your plots more attractive or even to reflect your company’s brand colors. One of my favorite methods for updating Matplotlib’s colors is directly passing hex codes into the color argument because it allows me to be extremely specific about my color choices. plt.scatter(..., color='#0000CC') This handy tool can help you select an appropriate hex color by testing it against white and black text as well as comparing several lighter and darker shades. Alternatively, you can take a more scientific approach when choosing your palette by checking out Colorgorical by Connor Gramazio from the Brown Visualization Research Lab. The Colorgorical tool allows you to build a color palette by balancing various preferences like human perceptual difference and aesthetic pleasure. The xkcd color library provides another great way to update Matplotlib’s default colors. These 954 colors were specifically curated and named by several hundred thousand participants of the xkcd color name survey. You can use them in Matplotlib by prefixing their names with “xkcd:”. plt.scatter(..., color='xkcd:lightish blue') Matplotlib allows users to layer multiple graphics on top of each other, which proves convenient when comparing results or setting baselines. Two useful properties should be utilized while layering: 1) alpha for controlling each component’s opacity and 2) zorder for moving objects to the foreground or background. The alpha property in Matplotlib adjusts an object’s opacity. This value ranges from zero to one with zero being fully transparent (invisible 👀) and one being entirely opaque. Reducing alpha will make your plot objects see-through, allowing multiple layers to be seen at once as well as allowing overlapping points to be distinguished, say, in a scatter plot. plt.scatter(..., alpha=0.5) Matplotlib’s zorder property determines how close objects are to the foreground. Objects with smaller zorder values appear closer to the background, while those with larger values present closer to the front. If I’m making a scatter plot with an accompanying line plot, for example, I can bring the line forward by increasing its zorder. plt.scatter(..., zorder=1) #backgroundplt.plot(..., zorder=2) #foreground Many visuals can benefit from the annotation of main points or specific, illustrative examples because these directly convey ideas and boost the validity of results. To add text to a Matplotlib figure, just include annotation code specifying the desired text and its location. plt.annotate(TEXT, (X_POSITION, Y_POSITION), ...) The cereal dataset used to produced this blog’s visuals contains nutritional information about several brand name cereals along with a feature labeled as “rating.” One might firstly assume that “rating” is a score indicating cereals that consumers prefer. In the zorder figure above, however, I built a quick linear regression model showing that the correlation between calories per cup and rating is practically non-existent. It seems unlikely that calories would not factor into consumer preference, so we may already be skeptical about our initial assumption about “rating.” This misconception becomes even more obvious when examining the extremes: Cap’n Crunch is the lowest rated cereal while All-Bran with Extra Fiber rates the highest. Annotating the figure with these representative examples immediately dispels false assumptions about “rating.” This rating information more likely indicates a cereal’s nutritional value. (I have also annotated the cereal with the most calories per cup; Grape Nuts is likely not meant to be consumed in such large quantities! 😆) Adding a baseline to your visuals helps set expectations. A simple horizontal or vertical line provides others with appropriate context and often speeds along their understanding of your results. Highlighting a specific region of interest, meanwhile, can further emphasize your conclusions and also facilitates communication with your audience. Matplotlib offers several options for baselining and highlighting, including horizontal and vertical lines, shapes such as rectangles, horizontal and vertical span shading, and filling between two lines. Let’s now consider the interplay between fat and sugar in our cereal dataset. A basic scatter plot of this relationship doesn’t appear interesting at first, but after exploring further, we find the median fat per cup of cereal is just one gram because so many cereals contain no fat at all. Adding this baseline helps people arrive at this finding much more quickly. In other cases you may want to completely remove the default x- and y-axes that Matplotlib provides and create your own axes based on some data aggregate. This process requires three key steps: 1) remove all default spines, 2) remove tick marks, and 3) add new axes as horizontal and vertical lines. #1. Remove spinesfor spine in plt.gca().spines.values(): spine.set_visible(False)#2. Remove ticksplt.xticks([])plt.yticks([])#3. Add horizontal and vertical linesplt.axhline(Y_POSITION, ...) #horizontal lineplt.axvline(X_POSITION, ...) #vertical line Now that we have plotted the cereals’ fat and sugar contents on new axes, it appears that very few cereals are low in sugar but high in fat. That is, the upper-left quadrant is nearly empty. This seems reasonable because cereals typically are not savory. To make this point abundantly clear, we could direct attention to this low-sugar, high-fat area by drawing a rectangle around it and annotating. Matplotlib provides access to several shapes through its patches module, including a rectangle or even a dolphin. Begin by importing code for the rectangle: from matplotlib.patches import Rectangle Then to create a rectangle on the figure, grab the current axes and add a rectangular patch with its location, width, and height: plt.gca().add_patch(Rectangle((X_POSITION, Y_POSITION), WIDTH, HEIGHT, ...) Here, the x- and y-positions refer to the placement of the lower-left corner of the rectangle. Shading provides an alternative option for drawing attention to a particular region of your figure, and there are a few ways to add shading with Matplotlib. If you intend to highlight an entire horizontal or vertical area, just layer a span into your visual: plt.axhspan(Y_START, Y_END, ...) #horizontal shadingplt.axvspan(X_START, X_END, ...) #vertical shading Previously discussed properties like alpha and zorder are critical here because you will likely want to make your shading transparent and/or move it to the background. If the area you would like to shade follows more complicated logic, however, you may instead shade between two user-defined lines. This approach takes a set of x-values, two sets of y-values for the first and second lines, and an optional where argument that allows you to use logic to filter down to your region of interest. plt.gca().fill_between(X_VALUES, Y_LINE1, Y_LINE2, WHERE=FILTER LOGIC, ...) To shade the same area that was previously highlighted with a rectangle, simply define an array of equally spaced sugar values for the x-axis, fill between the median and max fat values on the y-axis (high fat), and filter down to sugar values less than the median (low sugar). sugars = np.linspace(df.sugars_per_cup.min(), df.sugars_per_cup.max(), 1000)plt.gca().fill_between(sugars, df.fat_per_cup.median(), df.fat_per_cup.max(), WHERE=sugars < df.sugars_per_cup.median(), ...) Matplotlib gets a bad reputation because of its poor defaults and the shear amount of code needed to produce decent looking visuals. Hopefully, the tips provided in this blog will help you address the first issue, though I’ll admit that the final few example figures required many updates and subsequently a sizable amount of code. If the required bulk of code bothers you, the Seaborn visualization library is an excellent alternative to Matplotlib. It comes with better defaults overall, demands fewer lines of code, and supports customization via traditional Matplotlib syntax if needed. The main thing to keep in mind when you visualize data–no matter which package you choose–is your audience. The suggestions I’ve offered here aim to smooth out the data communication process by 1) removing extraneous bits like unnecessary spines or tick marks, 2) telling the data story quicker by setting expectations with layering and baselines, and 3) highlighting main conclusions with shading and annotations. The resulting aesthetics also improve, but the primary goal is stronger and more seamless data communication. I recently shared content similar to this in a data visualization talk at ODSC NYC. You can access my original conference materials here as well as the code that powers each example figure on my GitHub here. [1] J.D. Hunter, Matplotlib: A 2D Graphics Environment (2007), Computing in Science & Engineering. [2] C. Crawford, 80 Cereals (2017), Kaggle. [3] C.C. Gramazio, D.H. Laidlaw and K.B. Schloss, Colorgorical: creating discriminable and preferable color palettes for information visualization (2017), IEEE Transactions on Visualization and Computer Graphics.
[ { "code": null, "e": 592, "s": 172, "text": "Matplotlib is typically the first data visualization package that Python programmers learn. While its users can create basic figures with just a few lines of code, these resulting default plots often prove insufficient in both design aesthetics and communicative power. Simple adjustments can lead to dramatic improvements, however, and in this post, I will share several tips on how to upgrade your Matplotlib figures." }, { "code": null, "e": 935, "s": 592, "text": "In the examples that follow, I will be using information found in this Kaggle dataset about cereals. I have normalized three features (calories, fat, and sugar) by serving size to better compare cereal nutrition and ratings. Details about these data transformations and the code used to generate each example figure can be found on my GitHub." }, { "code": null, "e": 1178, "s": 935, "text": "The first Matplotlib default to update is that black box surrounding each plot, comprised of four so-called “spines.” To adjust them we first get our figure’s axes via pyplot and then change the visibility of each individual spine as desired." }, { "code": null, "e": 1302, "s": 1178, "text": "Let’s say, for example, we want to remove the top and right spines. If we have imported Matplotlib’s pyplot submodule with:" }, { "code": null, "e": 1339, "s": 1302, "text": "from matplotlib import pyplot as plt" }, { "code": null, "e": 1386, "s": 1339, "text": "we just need to add the following to our code:" }, { "code": null, "e": 1473, "s": 1386, "text": "plt.gca().spines['top'].set_visible(False)plt.gca().spines['right'].set_visible(False)" }, { "code": null, "e": 1609, "s": 1473, "text": "and the top and right spines will no longer appear. Removing these distracting lines allows more focus to be directed toward your data." }, { "code": null, "e": 1777, "s": 1609, "text": "Matplotlib’s default colors just got an upgrade but you can still easily change them to make your plots more attractive or even to reflect your company’s brand colors." }, { "code": null, "e": 1961, "s": 1777, "text": "One of my favorite methods for updating Matplotlib’s colors is directly passing hex codes into the color argument because it allows me to be extremely specific about my color choices." }, { "code": null, "e": 1995, "s": 1961, "text": "plt.scatter(..., color='#0000CC')" }, { "code": null, "e": 2476, "s": 1995, "text": "This handy tool can help you select an appropriate hex color by testing it against white and black text as well as comparing several lighter and darker shades. Alternatively, you can take a more scientific approach when choosing your palette by checking out Colorgorical by Connor Gramazio from the Brown Visualization Research Lab. The Colorgorical tool allows you to build a color palette by balancing various preferences like human perceptual difference and aesthetic pleasure." }, { "code": null, "e": 2760, "s": 2476, "text": "The xkcd color library provides another great way to update Matplotlib’s default colors. These 954 colors were specifically curated and named by several hundred thousand participants of the xkcd color name survey. You can use them in Matplotlib by prefixing their names with “xkcd:”." }, { "code": null, "e": 2805, "s": 2760, "text": "plt.scatter(..., color='xkcd:lightish blue')" }, { "code": null, "e": 3120, "s": 2805, "text": "Matplotlib allows users to layer multiple graphics on top of each other, which proves convenient when comparing results or setting baselines. Two useful properties should be utilized while layering: 1) alpha for controlling each component’s opacity and 2) zorder for moving objects to the foreground or background." }, { "code": null, "e": 3480, "s": 3120, "text": "The alpha property in Matplotlib adjusts an object’s opacity. This value ranges from zero to one with zero being fully transparent (invisible 👀) and one being entirely opaque. Reducing alpha will make your plot objects see-through, allowing multiple layers to be seen at once as well as allowing overlapping points to be distinguished, say, in a scatter plot." }, { "code": null, "e": 3508, "s": 3480, "text": "plt.scatter(..., alpha=0.5)" }, { "code": null, "e": 3846, "s": 3508, "text": "Matplotlib’s zorder property determines how close objects are to the foreground. Objects with smaller zorder values appear closer to the background, while those with larger values present closer to the front. If I’m making a scatter plot with an accompanying line plot, for example, I can bring the line forward by increasing its zorder." }, { "code": null, "e": 3925, "s": 3846, "text": "plt.scatter(..., zorder=1) #backgroundplt.plot(..., zorder=2) #foreground" }, { "code": null, "e": 4202, "s": 3925, "text": "Many visuals can benefit from the annotation of main points or specific, illustrative examples because these directly convey ideas and boost the validity of results. To add text to a Matplotlib figure, just include annotation code specifying the desired text and its location." }, { "code": null, "e": 4252, "s": 4202, "text": "plt.annotate(TEXT, (X_POSITION, Y_POSITION), ...)" }, { "code": null, "e": 4830, "s": 4252, "text": "The cereal dataset used to produced this blog’s visuals contains nutritional information about several brand name cereals along with a feature labeled as “rating.” One might firstly assume that “rating” is a score indicating cereals that consumers prefer. In the zorder figure above, however, I built a quick linear regression model showing that the correlation between calories per cup and rating is practically non-existent. It seems unlikely that calories would not factor into consumer preference, so we may already be skeptical about our initial assumption about “rating.”" }, { "code": null, "e": 5323, "s": 4830, "text": "This misconception becomes even more obvious when examining the extremes: Cap’n Crunch is the lowest rated cereal while All-Bran with Extra Fiber rates the highest. Annotating the figure with these representative examples immediately dispels false assumptions about “rating.” This rating information more likely indicates a cereal’s nutritional value. (I have also annotated the cereal with the most calories per cup; Grape Nuts is likely not meant to be consumed in such large quantities! 😆)" }, { "code": null, "e": 5872, "s": 5323, "text": "Adding a baseline to your visuals helps set expectations. A simple horizontal or vertical line provides others with appropriate context and often speeds along their understanding of your results. Highlighting a specific region of interest, meanwhile, can further emphasize your conclusions and also facilitates communication with your audience. Matplotlib offers several options for baselining and highlighting, including horizontal and vertical lines, shapes such as rectangles, horizontal and vertical span shading, and filling between two lines." }, { "code": null, "e": 6239, "s": 5872, "text": "Let’s now consider the interplay between fat and sugar in our cereal dataset. A basic scatter plot of this relationship doesn’t appear interesting at first, but after exploring further, we find the median fat per cup of cereal is just one gram because so many cereals contain no fat at all. Adding this baseline helps people arrive at this finding much more quickly." }, { "code": null, "e": 6539, "s": 6239, "text": "In other cases you may want to completely remove the default x- and y-axes that Matplotlib provides and create your own axes based on some data aggregate. This process requires three key steps: 1) remove all default spines, 2) remove tick marks, and 3) add new axes as horizontal and vertical lines." }, { "code": null, "e": 6795, "s": 6539, "text": "#1. Remove spinesfor spine in plt.gca().spines.values(): spine.set_visible(False)#2. Remove ticksplt.xticks([])plt.yticks([])#3. Add horizontal and vertical linesplt.axhline(Y_POSITION, ...) #horizontal lineplt.axvline(X_POSITION, ...) #vertical line" }, { "code": null, "e": 7352, "s": 6795, "text": "Now that we have plotted the cereals’ fat and sugar contents on new axes, it appears that very few cereals are low in sugar but high in fat. That is, the upper-left quadrant is nearly empty. This seems reasonable because cereals typically are not savory. To make this point abundantly clear, we could direct attention to this low-sugar, high-fat area by drawing a rectangle around it and annotating. Matplotlib provides access to several shapes through its patches module, including a rectangle or even a dolphin. Begin by importing code for the rectangle:" }, { "code": null, "e": 7393, "s": 7352, "text": "from matplotlib.patches import Rectangle" }, { "code": null, "e": 7523, "s": 7393, "text": "Then to create a rectangle on the figure, grab the current axes and add a rectangular patch with its location, width, and height:" }, { "code": null, "e": 7629, "s": 7523, "text": "plt.gca().add_patch(Rectangle((X_POSITION, Y_POSITION), WIDTH, HEIGHT, ...)" }, { "code": null, "e": 7724, "s": 7629, "text": "Here, the x- and y-positions refer to the placement of the lower-left corner of the rectangle." }, { "code": null, "e": 7881, "s": 7724, "text": "Shading provides an alternative option for drawing attention to a particular region of your figure, and there are a few ways to add shading with Matplotlib." }, { "code": null, "e": 7983, "s": 7881, "text": "If you intend to highlight an entire horizontal or vertical area, just layer a span into your visual:" }, { "code": null, "e": 8088, "s": 7983, "text": "plt.axhspan(Y_START, Y_END, ...) #horizontal shadingplt.axvspan(X_START, X_END, ...) #vertical shading" }, { "code": null, "e": 8256, "s": 8088, "text": "Previously discussed properties like alpha and zorder are critical here because you will likely want to make your shading transparent and/or move it to the background." }, { "code": null, "e": 8582, "s": 8256, "text": "If the area you would like to shade follows more complicated logic, however, you may instead shade between two user-defined lines. This approach takes a set of x-values, two sets of y-values for the first and second lines, and an optional where argument that allows you to use logic to filter down to your region of interest." }, { "code": null, "e": 8681, "s": 8582, "text": "plt.gca().fill_between(X_VALUES, Y_LINE1, Y_LINE2, WHERE=FILTER LOGIC, ...)" }, { "code": null, "e": 8959, "s": 8681, "text": "To shade the same area that was previously highlighted with a rectangle, simply define an array of equally spaced sugar values for the x-axis, fill between the median and max fat values on the y-axis (high fat), and filter down to sugar values less than the median (low sugar)." }, { "code": null, "e": 9301, "s": 8959, "text": "sugars = np.linspace(df.sugars_per_cup.min(), df.sugars_per_cup.max(), 1000)plt.gca().fill_between(sugars, df.fat_per_cup.median(), df.fat_per_cup.max(), WHERE=sugars < df.sugars_per_cup.median(), ...)" }, { "code": null, "e": 9892, "s": 9301, "text": "Matplotlib gets a bad reputation because of its poor defaults and the shear amount of code needed to produce decent looking visuals. Hopefully, the tips provided in this blog will help you address the first issue, though I’ll admit that the final few example figures required many updates and subsequently a sizable amount of code. If the required bulk of code bothers you, the Seaborn visualization library is an excellent alternative to Matplotlib. It comes with better defaults overall, demands fewer lines of code, and supports customization via traditional Matplotlib syntax if needed." }, { "code": null, "e": 10417, "s": 9892, "text": "The main thing to keep in mind when you visualize data–no matter which package you choose–is your audience. The suggestions I’ve offered here aim to smooth out the data communication process by 1) removing extraneous bits like unnecessary spines or tick marks, 2) telling the data story quicker by setting expectations with layering and baselines, and 3) highlighting main conclusions with shading and annotations. The resulting aesthetics also improve, but the primary goal is stronger and more seamless data communication." }, { "code": null, "e": 10625, "s": 10417, "text": "I recently shared content similar to this in a data visualization talk at ODSC NYC. You can access my original conference materials here as well as the code that powers each example figure on my GitHub here." }, { "code": null, "e": 10724, "s": 10625, "text": "[1] J.D. Hunter, Matplotlib: A 2D Graphics Environment (2007), Computing in Science & Engineering." }, { "code": null, "e": 10768, "s": 10724, "text": "[2] C. Crawford, 80 Cereals (2017), Kaggle." } ]
C# Program to print all permutations of a given string - GeeksforGeeks
10 Dec, 2021 A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB Here is a solution that is used as a basis in backtracking. C# // C# program to print all permutations // of a given string. using System; class GFG { /* Permutation function @param str string to calculate permutation for @param l starting index @param r end index */ private static void permute(String str, int l, int r) { if (l == r) Console.WriteLine(str); else { for (int i = l; i <= r; i++) { str = swap(str, l, i); permute(str, l + 1, r); str = swap(str, l, i); } } } /* Swap Characters at position @param a string value @param i position 1 @param j position 2 @return swapped string */ public static String swap(String a, int i, int j) { char temp; char[] charArray = a.ToCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; string s = new string(charArray); return s; } // Driver Code public static void Main() { String str = "ABC"; int n = str.Length; permute(str, 0, n-1); } } // This code is contributed by mits Output: ABC ACB BAC BCA CBA CAB Algorithm Paradigm: Backtracking Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(r – l) Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL Another approach: C# // C# program to implement// the above approachusing System;public class GFG{ static void permute(String s, String answer){ if (s.Length == 0) { Console.Write(answer + " "); return; } for(int i = 0 ;i < s.Length; i++) { char ch = s[i]; String left_substr = s.Substring(0, i); String right_substr = s.Substring(i + 1); String rest = left_substr + right_substr; permute(rest, answer + ch); }} // Driver codepublic static void Main(String []args){ String s; String answer=""; Console.Write( "Enter the string : "); s = Console.ReadLine(); Console.Write( "\nAll possible strings are : "); permute(s, answer);}}// This code is contributed by gauravrajput1 Output: Enter the string : abc All possible strings are : abc acb bac bca cab cba Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(|s|) Please refer complete article on Write a program to print all permutations of a given string for more details! C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Remove Duplicate Values From an Array in C#? C# Program to Convert a Binary String to an Integer How to Convert ASCII Char to Byte in C#? C# Program to Demonstrate the IList Interface Different Ways to Take Input and Print a Float Value in C# C# Program to Read and Write a Byte Array to File using FileStream Class C# Program to Check a Specified Type is an Enum or Not How to Calculate the Code Execution Time in C#? C# Program to Sort a List of Integers Using the LINQ OrderBy() Method Hash Function for String data in C#
[ { "code": null, "e": 25358, "s": 25330, "text": "\n10 Dec, 2021" }, { "code": null, "e": 25566, "s": 25358, "text": "A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. " }, { "code": null, "e": 25630, "s": 25566, "text": "Source: Mathword(http://mathworld.wolfram.com/Permutation.html)" }, { "code": null, "e": 25696, "s": 25630, "text": "Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB" }, { "code": null, "e": 25756, "s": 25696, "text": "Here is a solution that is used as a basis in backtracking." }, { "code": null, "e": 25759, "s": 25756, "text": "C#" }, { "code": "// C# program to print all permutations // of a given string. using System; class GFG { /* Permutation function @param str string to calculate permutation for @param l starting index @param r end index */ private static void permute(String str, int l, int r) { if (l == r) Console.WriteLine(str); else { for (int i = l; i <= r; i++) { str = swap(str, l, i); permute(str, l + 1, r); str = swap(str, l, i); } } } /* Swap Characters at position @param a string value @param i position 1 @param j position 2 @return swapped string */ public static String swap(String a, int i, int j) { char temp; char[] charArray = a.ToCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; string s = new string(charArray); return s; } // Driver Code public static void Main() { String str = \"ABC\"; int n = str.Length; permute(str, 0, n-1); } } // This code is contributed by mits ", "e": 26985, "s": 25759, "text": null }, { "code": null, "e": 26994, "s": 26985, "text": "Output: " }, { "code": null, "e": 27018, "s": 26994, "text": "ABC\nACB\nBAC\nBCA\nCBA\nCAB" }, { "code": null, "e": 27052, "s": 27018, "text": "Algorithm Paradigm: Backtracking " }, { "code": null, "e": 27163, "s": 27052, "text": "Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 27189, "s": 27163, "text": "Auxiliary Space: O(r – l)" }, { "code": null, "e": 27525, "s": 27189, "text": "Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL" }, { "code": null, "e": 27543, "s": 27525, "text": "Another approach:" }, { "code": null, "e": 27546, "s": 27543, "text": "C#" }, { "code": "// C# program to implement// the above approachusing System;public class GFG{ static void permute(String s, String answer){ if (s.Length == 0) { Console.Write(answer + \" \"); return; } for(int i = 0 ;i < s.Length; i++) { char ch = s[i]; String left_substr = s.Substring(0, i); String right_substr = s.Substring(i + 1); String rest = left_substr + right_substr; permute(rest, answer + ch); }} // Driver codepublic static void Main(String []args){ String s; String answer=\"\"; Console.Write( \"Enter the string : \"); s = Console.ReadLine(); Console.Write( \"\\nAll possible strings are : \"); permute(s, answer);}}// This code is contributed by gauravrajput1 ", "e": 28337, "s": 27546, "text": null }, { "code": null, "e": 28345, "s": 28337, "text": "Output:" }, { "code": null, "e": 28424, "s": 28345, "text": "Enter the string : abc\nAll possible strings are : abc acb bac bca cab cba" }, { "code": null, "e": 28585, "s": 28424, "text": "Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 28609, "s": 28585, "text": "Auxiliary Space: O(|s|)" }, { "code": null, "e": 28720, "s": 28609, "text": "Please refer complete article on Write a program to print all permutations of a given string for more details!" }, { "code": null, "e": 28732, "s": 28720, "text": "C# Programs" }, { "code": null, "e": 28830, "s": 28732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28882, "s": 28830, "text": "How to Remove Duplicate Values From an Array in C#?" }, { "code": null, "e": 28934, "s": 28882, "text": "C# Program to Convert a Binary String to an Integer" }, { "code": null, "e": 28975, "s": 28934, "text": "How to Convert ASCII Char to Byte in C#?" }, { "code": null, "e": 29021, "s": 28975, "text": "C# Program to Demonstrate the IList Interface" }, { "code": null, "e": 29080, "s": 29021, "text": "Different Ways to Take Input and Print a Float Value in C#" }, { "code": null, "e": 29153, "s": 29080, "text": "C# Program to Read and Write a Byte Array to File using FileStream Class" }, { "code": null, "e": 29208, "s": 29153, "text": "C# Program to Check a Specified Type is an Enum or Not" }, { "code": null, "e": 29256, "s": 29208, "text": "How to Calculate the Code Execution Time in C#?" }, { "code": null, "e": 29326, "s": 29256, "text": "C# Program to Sort a List of Integers Using the LINQ OrderBy() Method" } ]
HandCalcs module in Python - GeeksforGeeks
05 Sep, 2020 HandCalcs is a library in Python to make calculations automatically in Latex, but in a way that imitates how the equation might be formatted when handwritten, write the mathematical formula, supported by numerical substitutions, and then the output. Since HandCalcs indicates the numerical replacement, the equations become much easier to manually check and verify. Run the following pip command on the terminal. pip install handcalcs The HandCalcs library in Python is designed to be used in Jupyter Notebook or Jupyter Lab as a cell magic.To use the render feature of the HandCalcs library, import the module by executing import handcalcs.render, after that just use the %%render on the top of the cell in which equations or variables are to be rendered with HandCalcs. Example 1: Addition of 2 numbers Python3 # importing the moduleimport handcalcs.render x = 5y = 6 # run the code below in a new Jupyter cell%%renderz = x + y Output: Example 2: Calculating the tan of an expression. Python3 # importing the librariesimport handcalcs.renderfrom math import tan p = 5r = 12s = 3.5 # run the code below in a new Jupyter cell%%rendert = tan(p ** r + r / s) * r Output: Example 3: Quadratic equation with square root. Python3 # importing the moduleimport handcalcs.renderfrom math import sqrt a = 6b = 7c = -8 # run the code below in a new Jupyter cell%%renderr = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) Output: By using comments, HandCalcs make some conclusions as to how the equation to be structured. Only a single comment can be used per cell. Three types of customizations can be created using the # comment tags at the top of the cell: 1. # Parameters: The display structure of the variables or parameters can be controlled by using the # Parameter tag, this tag is used to classify the display structure into the vertical display or horizontal display. Example: Without the # Parameter comment, all the equations will be displayed vertically Python3 # importing the moduleimport handcalcs.render # run the code below in a new Jupyter cell%%renderp = 5q = 4r = 3s = 2t = 1 Output: Example: This time the # Parameter comment is used. Python3 # importing the moduleimport handcalcs.render # run the code below in a new Jupyter cell%%render # Parameterp = 5q = 4r = 3s = 2t = 1 Output: 2. # Long and # Short: As # Parameter comment tag is used to control the display structure of variables in the same way # Long and # Short comment tags control the display structure of equations, the # Long and # Short are used to display equations vertically and horizontally respectively. Example: Displaying the equations horizontally using # Short. Python3 # importing the modulesimport handcalcs.renderfrom math import sqrt a = 6b = 7c = -8 # run the code below in a new Jupyter cell%%render # Shortx = b ** 2 - 4 * a * cd = sqrt(x)r1 = (-b + d) / (2 * a) r2 = (-b - d) / (2 * a) Output: Example: Displaying the equations vertically using # Long. Python3 # importing the modulesimport handcalcs.renderfrom math import sqrt a = 6b = 7c = -8 # run the code below in a new Jupyter cell%%render # Longx = b ** 2 - 4 * a * cd = sqrt(x)r1 = (-b + d) / (2 * a) r2 = (-b - d) / (2 * a) Output: 3. # Symbolic: The HandCalcs library’s primary objective is to make the complete equation using the numerical substitution. This makes the equation easy to track and validate. However, there might be situations where equations are represented symbolically, the # Symbolic comment tag cab symbolically render Latex equations. Example: Python3 # imporintg the modulesimport handcalcs.renderfrom math import sqrt, tan # Parametersa = 6b = 7c = -8x = 9y = 10 # run the code below in a new Jupyter cell%%render # Symbolicr = (-b + sqrt(b ** 2 -4 * a * c)) / (2 * a)z = tan(x ** y + y / x) Output: python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n05 Sep, 2020" }, { "code": null, "e": 24268, "s": 23901, "text": "HandCalcs is a library in Python to make calculations automatically in Latex, but in a way that imitates how the equation might be formatted when handwritten, write the mathematical formula, supported by numerical substitutions, and then the output. Since HandCalcs indicates the numerical replacement, the equations become much easier to manually check and verify. " }, { "code": null, "e": 24315, "s": 24268, "text": "Run the following pip command on the terminal." }, { "code": null, "e": 24338, "s": 24315, "text": "pip install handcalcs\n" }, { "code": null, "e": 24675, "s": 24338, "text": "The HandCalcs library in Python is designed to be used in Jupyter Notebook or Jupyter Lab as a cell magic.To use the render feature of the HandCalcs library, import the module by executing import handcalcs.render, after that just use the %%render on the top of the cell in which equations or variables are to be rendered with HandCalcs." }, { "code": null, "e": 24709, "s": 24675, "text": "Example 1: Addition of 2 numbers " }, { "code": null, "e": 24717, "s": 24709, "text": "Python3" }, { "code": "# importing the moduleimport handcalcs.render x = 5y = 6 # run the code below in a new Jupyter cell%%renderz = x + y", "e": 24836, "s": 24717, "text": null }, { "code": null, "e": 24846, "s": 24836, "text": "Output: " }, { "code": null, "e": 24896, "s": 24846, "text": "Example 2: Calculating the tan of an expression. " }, { "code": null, "e": 24904, "s": 24896, "text": "Python3" }, { "code": "# importing the librariesimport handcalcs.renderfrom math import tan p = 5r = 12s = 3.5 # run the code below in a new Jupyter cell%%rendert = tan(p ** r + r / s) * r", "e": 25072, "s": 24904, "text": null }, { "code": null, "e": 25082, "s": 25072, "text": "Output: " }, { "code": null, "e": 25131, "s": 25082, "text": "Example 3: Quadratic equation with square root. " }, { "code": null, "e": 25139, "s": 25131, "text": "Python3" }, { "code": "# importing the moduleimport handcalcs.renderfrom math import sqrt a = 6b = 7c = -8 # run the code below in a new Jupyter cell%%renderr = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a)", "e": 25321, "s": 25139, "text": null }, { "code": null, "e": 25331, "s": 25321, "text": "Output: " }, { "code": null, "e": 25469, "s": 25333, "text": "By using comments, HandCalcs make some conclusions as to how the equation to be structured. Only a single comment can be used per cell." }, { "code": null, "e": 25565, "s": 25469, "text": "Three types of customizations can be created using the # comment tags at the top of the cell: " }, { "code": null, "e": 25785, "s": 25565, "text": "1. # Parameters: The display structure of the variables or parameters can be controlled by using the # Parameter tag, this tag is used to classify the display structure into the vertical display or horizontal display. " }, { "code": null, "e": 25876, "s": 25785, "text": "Example: Without the # Parameter comment, all the equations will be displayed vertically " }, { "code": null, "e": 25884, "s": 25876, "text": "Python3" }, { "code": "# importing the moduleimport handcalcs.render # run the code below in a new Jupyter cell%%renderp = 5q = 4r = 3s = 2t = 1", "e": 26007, "s": 25884, "text": null }, { "code": null, "e": 26017, "s": 26007, "text": "Output: " }, { "code": null, "e": 26070, "s": 26017, "text": "Example: This time the # Parameter comment is used. " }, { "code": null, "e": 26078, "s": 26070, "text": "Python3" }, { "code": "# importing the moduleimport handcalcs.render # run the code below in a new Jupyter cell%%render # Parameterp = 5q = 4r = 3s = 2t = 1", "e": 26214, "s": 26078, "text": null }, { "code": null, "e": 26224, "s": 26214, "text": "Output: " }, { "code": null, "e": 26516, "s": 26224, "text": "2. # Long and # Short: As # Parameter comment tag is used to control the display structure of variables in the same way # Long and # Short comment tags control the display structure of equations, the # Long and # Short are used to display equations vertically and horizontally respectively. " }, { "code": null, "e": 26579, "s": 26516, "text": "Example: Displaying the equations horizontally using # Short. " }, { "code": null, "e": 26587, "s": 26579, "text": "Python3" }, { "code": "# importing the modulesimport handcalcs.renderfrom math import sqrt a = 6b = 7c = -8 # run the code below in a new Jupyter cell%%render # Shortx = b ** 2 - 4 * a * cd = sqrt(x)r1 = (-b + d) / (2 * a) r2 = (-b - d) / (2 * a)", "e": 26814, "s": 26587, "text": null }, { "code": null, "e": 26824, "s": 26814, "text": "Output: " }, { "code": null, "e": 26884, "s": 26824, "text": "Example: Displaying the equations vertically using # Long. " }, { "code": null, "e": 26892, "s": 26884, "text": "Python3" }, { "code": "# importing the modulesimport handcalcs.renderfrom math import sqrt a = 6b = 7c = -8 # run the code below in a new Jupyter cell%%render # Longx = b ** 2 - 4 * a * cd = sqrt(x)r1 = (-b + d) / (2 * a) r2 = (-b - d) / (2 * a)", "e": 27118, "s": 26892, "text": null }, { "code": null, "e": 27128, "s": 27118, "text": "Output: " }, { "code": null, "e": 27455, "s": 27128, "text": "3. # Symbolic: The HandCalcs library’s primary objective is to make the complete equation using the numerical substitution. This makes the equation easy to track and validate. However, there might be situations where equations are represented symbolically, the # Symbolic comment tag cab symbolically render Latex equations. " }, { "code": null, "e": 27466, "s": 27455, "text": "Example: " }, { "code": null, "e": 27474, "s": 27466, "text": "Python3" }, { "code": "# imporintg the modulesimport handcalcs.renderfrom math import sqrt, tan # Parametersa = 6b = 7c = -8x = 9y = 10 # run the code below in a new Jupyter cell%%render # Symbolicr = (-b + sqrt(b ** 2 -4 * a * c)) / (2 * a)z = tan(x ** y + y / x)", "e": 27719, "s": 27474, "text": null }, { "code": null, "e": 27729, "s": 27719, "text": "Output: " }, { "code": null, "e": 27744, "s": 27729, "text": "python-modules" }, { "code": null, "e": 27751, "s": 27744, "text": "Python" }, { "code": null, "e": 27849, "s": 27751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27858, "s": 27849, "text": "Comments" }, { "code": null, "e": 27871, "s": 27858, "text": "Old Comments" }, { "code": null, "e": 27903, "s": 27871, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27959, "s": 27903, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28001, "s": 27959, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28043, "s": 28001, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28079, "s": 28043, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28101, "s": 28079, "text": "Defaultdict in Python" }, { "code": null, "e": 28140, "s": 28101, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28167, "s": 28140, "text": "Python Classes and Objects" }, { "code": null, "e": 28198, "s": 28167, "text": "Python | os.path.join() method" } ]
Non-decreasing subsequence | Practice | GeeksforGeeks
Given a sequence of n integers, the task is to find out the non-decreasing subsequence of length k with minimum sum. If no sequence exists output -1. Example 1: Input: N = 10, K = 3, arr[] = {58, 12, 11, 12, 82, 30, 20, 77, 16, 86} Output: 39 Explanation: {11 + 12 + 16} Input: N = 10, K = 4, arr[] = {58, 12, 11, 12, 82, 30, 20, 77, 16, 86} Output: 120 Explanation: {11 + 12 + 16 + 77} Your Task: You don't need to read input or print anything. Complete the function minSum() which takes N, K and array arr as input parameters and returns the sum. Expected Time Complexity: O(N*K) Expected Auxiliary Space: O(N*K) Constraints: 1 ≤ N, K ≤ 103 1 ≤ arr[i] ≤ 105 0 himanshujain4573 months ago Simplest Java Solution:Accepted class Solution{ public int minSum(int arr[], int N, int K) { int [][]dp=new int[N+1][K+1]; for(int i=0;i<=N;i++) { for(int j=0;j<=K;j++) { dp[i][j]=Integer.MAX_VALUE; if(i==0||j==0) dp[i][j]=0; } } for(int i=1;i<=N;i++) { dp[i][1]=arr[i-1]; } for(int k=2;k<=K;k++) { for(int i=2;i<=N;i++) { int mn=Integer.MAX_VALUE; for(int j=1;j<i;j++) { if(arr[i-1]>=arr[j-1] &&dp[j][k-1]!=Integer.MAX_VALUE) { mn=Math.min(mn,arr[i-1]+dp[j][k-1]) ; } } dp[i][k]=mn; } } int res=Integer.MAX_VALUE; for(int i=1;i<=N;i++) { res=Math.min(res,dp[i][K]); } if( res==Integer.MAX_VALUE) return -1; return res;} } 0 Harshvardhan yadav10 months ago Harshvardhan yadav use concept of finding min_sum of increasing Or equal subsequence of size k 0 ultraint2 years ago ultraint how the output of 5 329 16 20 4 11is 47 it should be -1 ?16,20,11 is not an non-decreasing subsequence.. 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": 388, "s": 238, "text": "Given a sequence of n integers, the task is to find out the non-decreasing subsequence of length k with minimum sum. If no sequence exists output -1." }, { "code": null, "e": 399, "s": 388, "text": "Example 1:" }, { "code": null, "e": 517, "s": 399, "text": "Input: N = 10, K = 3, arr[] = {58, 12, \n 11, 12, 82, 30, 20, 77, 16, 86}\nOutput: 39\nExplanation: {11 + 12 + 16}" }, { "code": null, "e": 633, "s": 517, "text": "Input: N = 10, K = 4, arr[] = {58, 12,\n11, 12, 82, 30, 20, 77, 16, 86}\nOutput: 120\nExplanation: {11 + 12 + 16 + 77}" }, { "code": null, "e": 911, "s": 633, "text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function minSum() which takes N, K and array arr as input parameters and returns the sum.\n\nExpected Time Complexity: O(N*K)\nExpected Auxiliary Space: O(N*K)\n\nConstraints:\n1 ≤ N, K ≤ 103\n1 ≤ arr[i] ≤ 105" }, { "code": null, "e": 913, "s": 911, "text": "0" }, { "code": null, "e": 941, "s": 913, "text": "himanshujain4573 months ago" }, { "code": null, "e": 973, "s": 941, "text": "Simplest Java Solution:Accepted" }, { "code": null, "e": 989, "s": 973, "text": "class Solution{" }, { "code": null, "e": 1708, "s": 989, "text": "public int minSum(int arr[], int N, int K) { int [][]dp=new int[N+1][K+1]; for(int i=0;i<=N;i++) { for(int j=0;j<=K;j++) { dp[i][j]=Integer.MAX_VALUE; if(i==0||j==0) dp[i][j]=0; } } for(int i=1;i<=N;i++) { dp[i][1]=arr[i-1]; } for(int k=2;k<=K;k++) { for(int i=2;i<=N;i++) { int mn=Integer.MAX_VALUE; for(int j=1;j<i;j++) { if(arr[i-1]>=arr[j-1] &&dp[j][k-1]!=Integer.MAX_VALUE) { mn=Math.min(mn,arr[i-1]+dp[j][k-1]) ; } } dp[i][k]=mn; } } int res=Integer.MAX_VALUE; for(int i=1;i<=N;i++) { res=Math.min(res,dp[i][K]); } if( res==Integer.MAX_VALUE) return -1; return res;} }" }, { "code": null, "e": 1710, "s": 1708, "text": "0" }, { "code": null, "e": 1742, "s": 1710, "text": "Harshvardhan yadav10 months ago" }, { "code": null, "e": 1761, "s": 1742, "text": "Harshvardhan yadav" }, { "code": null, "e": 1837, "s": 1761, "text": "use concept of finding min_sum of increasing Or equal subsequence of size k" }, { "code": null, "e": 1839, "s": 1837, "text": "0" }, { "code": null, "e": 1859, "s": 1839, "text": "ultraint2 years ago" }, { "code": null, "e": 1868, "s": 1859, "text": "ultraint" }, { "code": null, "e": 1973, "s": 1868, "text": "how the output of 5 329 16 20 4 11is 47 it should be -1 ?16,20,11 is not an non-decreasing subsequence.." }, { "code": null, "e": 2119, "s": 1973, "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": 2155, "s": 2119, "text": " Login to access your submissions. " }, { "code": null, "e": 2165, "s": 2155, "text": "\nProblem\n" }, { "code": null, "e": 2175, "s": 2165, "text": "\nContest\n" }, { "code": null, "e": 2238, "s": 2175, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2386, "s": 2238, "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": 2594, "s": 2386, "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": 2700, "s": 2594, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Stream.reduce() in Java with examples - GeeksforGeeks
16 Oct, 2019 Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element. Syntax : T reduce(T identity, BinaryOperator<T> accumulator); Where, identity is initial value of type T and accumulator is a function for combining two values. sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream. Let us see some examples to understand the reduce() function in a better way :Example 1 : // Implementation of reduce method// to get the longest Stringimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Strings List<String> words = Arrays.asList("GFG", "Geeks", "for", "GeeksQuiz", "GeeksforGeeks"); // The lambda expression passed to // reduce() method takes two Strings // and returns the longer String. // The result of the reduce() method is // an Optional because the list on which // reduce() is called may be empty. Optional<String> longestString = words.stream() .reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2); // Displaying the longest String longestString.ifPresent(System.out::println); }} Output : GeeksforGeeks Example 2 : // Implementation of reduce method// to get the combined Stringimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // String array String[] array = { "Geeks", "for", "Geeks" }; // The result of the reduce() method is // an Optional because the list on which // reduce() is called may be empty. Optional<String> String_combine = Arrays.stream(array) .reduce((str1, str2) -> str1 + "-" + str2); // Displaying the combined String if (String_combine.isPresent()) { System.out.println(String_combine.get()); } }} Output : Geeks-for-Geeks Example 3 : // Implementation of reduce method// to get the sum of all elementsimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating list of integers List<Integer> array = Arrays.asList(-2, 0, 4, 6, 8); // Finding sum of all elements int sum = array.stream().reduce(0, (element1, element2) -> element1 + element2); // Displaying sum of all elements System.out.println("The sum of all elements is " + sum); }} Output : The sum of all elements is 16 Example 4 : // Implementation of reduce method// to get the product of all numbers// in given range.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // To get the product of all elements // in given range excluding the // rightmost element int product = IntStream.range(2, 8) .reduce((num1, num2) -> num1 * num2) .orElse(-1); // Displaying the product System.out.println("The product is : " + product); }} Output : The product is : 5040 Akanksha_Rai Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25497, "s": 25469, "text": "\n16 Oct, 2019" }, { "code": null, "e": 25699, "s": 25497, "text": "Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements." }, { "code": null, "e": 25912, "s": 25699, "text": "reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element." }, { "code": null, "e": 25921, "s": 25912, "text": "Syntax :" }, { "code": null, "e": 26077, "s": 25921, "text": "T reduce(T identity, BinaryOperator<T> accumulator);\n\nWhere, identity is initial value \nof type T and accumulator is a \nfunction for combining two values.\n" }, { "code": null, "e": 26247, "s": 26077, "text": "sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream." }, { "code": null, "e": 26337, "s": 26247, "text": "Let us see some examples to understand the reduce() function in a better way :Example 1 :" }, { "code": "// Implementation of reduce method// to get the longest Stringimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Strings List<String> words = Arrays.asList(\"GFG\", \"Geeks\", \"for\", \"GeeksQuiz\", \"GeeksforGeeks\"); // The lambda expression passed to // reduce() method takes two Strings // and returns the longer String. // The result of the reduce() method is // an Optional because the list on which // reduce() is called may be empty. Optional<String> longestString = words.stream() .reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2); // Displaying the longest String longestString.ifPresent(System.out::println); }}", "e": 27277, "s": 26337, "text": null }, { "code": null, "e": 27286, "s": 27277, "text": "Output :" }, { "code": null, "e": 27301, "s": 27286, "text": "GeeksforGeeks\n" }, { "code": null, "e": 27313, "s": 27301, "text": "Example 2 :" }, { "code": "// Implementation of reduce method// to get the combined Stringimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // String array String[] array = { \"Geeks\", \"for\", \"Geeks\" }; // The result of the reduce() method is // an Optional because the list on which // reduce() is called may be empty. Optional<String> String_combine = Arrays.stream(array) .reduce((str1, str2) -> str1 + \"-\" + str2); // Displaying the combined String if (String_combine.isPresent()) { System.out.println(String_combine.get()); } }}", "e": 28036, "s": 27313, "text": null }, { "code": null, "e": 28045, "s": 28036, "text": "Output :" }, { "code": null, "e": 28062, "s": 28045, "text": "Geeks-for-Geeks\n" }, { "code": null, "e": 28074, "s": 28062, "text": "Example 3 :" }, { "code": "// Implementation of reduce method// to get the sum of all elementsimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating list of integers List<Integer> array = Arrays.asList(-2, 0, 4, 6, 8); // Finding sum of all elements int sum = array.stream().reduce(0, (element1, element2) -> element1 + element2); // Displaying sum of all elements System.out.println(\"The sum of all elements is \" + sum); }}", "e": 28595, "s": 28074, "text": null }, { "code": null, "e": 28604, "s": 28595, "text": "Output :" }, { "code": null, "e": 28635, "s": 28604, "text": "The sum of all elements is 16\n" }, { "code": null, "e": 28647, "s": 28635, "text": "Example 4 :" }, { "code": "// Implementation of reduce method// to get the product of all numbers// in given range.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // To get the product of all elements // in given range excluding the // rightmost element int product = IntStream.range(2, 8) .reduce((num1, num2) -> num1 * num2) .orElse(-1); // Displaying the product System.out.println(\"The product is : \" + product); }}", "e": 29215, "s": 28647, "text": null }, { "code": null, "e": 29224, "s": 29215, "text": "Output :" }, { "code": null, "e": 29247, "s": 29224, "text": "The product is : 5040\n" }, { "code": null, "e": 29260, "s": 29247, "text": "Akanksha_Rai" }, { "code": null, "e": 29280, "s": 29260, "text": "Java - util package" }, { "code": null, "e": 29295, "s": 29280, "text": "Java-Functions" }, { "code": null, "e": 29307, "s": 29295, "text": "java-stream" }, { "code": null, "e": 29329, "s": 29307, "text": "Java-Stream interface" }, { "code": null, "e": 29334, "s": 29329, "text": "Java" }, { "code": null, "e": 29339, "s": 29334, "text": "Java" }, { "code": null, "e": 29437, "s": 29339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29488, "s": 29437, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29518, "s": 29488, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29537, "s": 29518, "text": "Interfaces in Java" }, { "code": null, "e": 29568, "s": 29537, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29600, "s": 29568, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29618, "s": 29600, "text": "ArrayList in Java" }, { "code": null, "e": 29638, "s": 29618, "text": "Stack Class in Java" }, { "code": null, "e": 29662, "s": 29638, "text": "Singleton Class in Java" }, { "code": null, "e": 29694, "s": 29662, "text": "Multidimensional Arrays in Java" } ]
What is vertical bar in Python bitwise assignment operator?
Vertical bar (|) stands for bitwise or operator. In case of two integer objects, it returns bitwise OR operation of two >>> a=4 >>> bin(a) '0b100' >>> b=5 >>> bin(b) '0b101' >>> a|b 5 >>> c=a|b >>> bin(c) '0b101'
[ { "code": null, "e": 1182, "s": 1062, "text": "Vertical bar (|) stands for bitwise or operator. In case of two integer objects, it returns bitwise OR operation of two" }, { "code": null, "e": 1275, "s": 1182, "text": ">>> a=4\n>>> bin(a)\n'0b100'\n>>> b=5\n>>> bin(b)\n'0b101'\n>>> a|b\n5\n>>> c=a|b\n>>> bin(c)\n'0b101'" } ]
How to change the background color of a Treeview in Tkinter?
The Treeview widget is designed to display the data in a hierarchical structure. It can be used to display the directories, child directories or files in the form of a list. The items present in the Listbox are called Listbox items. The treeview widget includes many properties and attributes through which we can change or modify its default properties. We can change the background of a treeview widget by defining the 'background' property in the constructor. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Create a Listbox widget lb = Listbox(win, width=100, height=10, background="purple4", foreground="white", font=('Times 13'),selectbackground="black") lb.pack() # Select the list item and delete the item first # Once the list item is deleted, we can insert a new item in the listbox def edit(): for item in lb.curselection(): lb.delete(item) lb.insert("end", "foo") # Add items in the Listbox lb.insert("end", "item1", "item2", "item3", "item4", "item5") # Add a Button To Edit and Delete the Listbox Item ttk.Button(win, text="Edit", command=edit).pack() win.mainloop() If we run the above code, it will display a window with a treeview widget having a distinct background color and some items in it.
[ { "code": null, "e": 1295, "s": 1062, "text": "The Treeview widget is designed to display the data in a hierarchical structure. It can be used to display the directories, child directories or files in the form of a list. The items present in the Listbox are called Listbox items." }, { "code": null, "e": 1525, "s": 1295, "text": "The treeview widget includes many properties and attributes through which we can change or modify its default properties. We can change the background of a treeview widget by defining the 'background' property in the constructor." }, { "code": null, "e": 2311, "s": 1525, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a Listbox widget\nlb = Listbox(win, width=100, height=10, background=\"purple4\", foreground=\"white\", font=('Times 13'),selectbackground=\"black\")\nlb.pack()\n\n\n# Select the list item and delete the item first\n# Once the list item is deleted, we can insert a new item in the listbox\ndef edit():\n for item in lb.curselection():\n lb.delete(item)\n lb.insert(\"end\", \"foo\")\n\n\n# Add items in the Listbox\nlb.insert(\"end\", \"item1\", \"item2\", \"item3\", \"item4\", \"item5\")\n\n# Add a Button To Edit and Delete the Listbox Item\nttk.Button(win, text=\"Edit\", command=edit).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2442, "s": 2311, "text": "If we run the above code, it will display a window with a treeview widget having a distinct background color and some items in it." } ]
GATE | GATE-CS-2014-(Set-3) | Question 38 - GeeksforGeeks
28 Jun, 2021 An IP router with a Maximum Transmission Unit (MTU) of 1500 bytes has received an IP packet of size 4404 bytes with an IP header of length 20 bytes. The values of the relevant fields in the header of the third IP fragment generated by the router for this packet are (A) MF bit: 0, Datagram Length: 1444; Offset: 370(B) MF bit: 1, Datagram Length: 1424; Offset: 185(C) MF bit: 1, Datagram Length: 1500; Offset: 37(D) MF bit: 0, Datagram Length: 1424; Offset: 2960Answer: (A)Explanation: Number of packet fragments = ⌈ (total size of packet)/(MTU) ⌉ = ⌈ 4404/1500 ⌉ = ⌈ 2.936 ⌉ = 3 So Datagram with data 4404 byte fragmented into 3 fragments. The first frame carries bytes 0 to 1479 (because MTU is 1500 bytes and HLEN is 20 byte so the total bytes in fragments is maximum 1500-20=1480). the offset for this datagram is 0/8 = 0. The second fragment carries byte 1480 to 2959. The offset for this datagram is 1480/8 = 185.finally the third fragment carries byte 2960 to 4404.the offset is 370.and for all fragments except last one the M bit is 1.so in the third bit M is 0..Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) 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-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-CS-2000 | Question 41 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25713, "s": 25685, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25979, "s": 25713, "text": "An IP router with a Maximum Transmission Unit (MTU) of 1500 bytes has received an IP packet of size 4404 bytes with an IP header of length 20 bytes. The values of the relevant fields in the header of the third IP fragment generated by the router for this packet are" }, { "code": null, "e": 26199, "s": 25979, "text": "(A) MF bit: 0, Datagram Length: 1444; Offset: 370(B) MF bit: 1, Datagram Length: 1424; Offset: 185(C) MF bit: 1, Datagram Length: 1500; Offset: 37(D) MF bit: 0, Datagram Length: 1424; Offset: 2960Answer: (A)Explanation:" }, { "code": null, "e": 26438, "s": 26199, "text": "Number of packet fragments = ⌈ (total size of packet)/(MTU) ⌉\n = ⌈ 4404/1500 ⌉\n = ⌈ 2.936 ⌉ \n = 3\n\nSo Datagram with data 4404 byte fragmented into 3 fragments. " }, { "code": null, "e": 26624, "s": 26438, "text": "The first frame carries bytes 0 to 1479 (because MTU is 1500 bytes and HLEN is 20 byte so the total bytes in fragments is maximum 1500-20=1480). the offset for this datagram is 0/8 = 0." }, { "code": null, "e": 26890, "s": 26624, "text": "The second fragment carries byte 1480 to 2959. The offset for this datagram is 1480/8 = 185.finally the third fragment carries byte 2960 to 4404.the offset is 370.and for all fragments except last one the M bit is 1.so in the third bit M is 0..Quiz of this Question" }, { "code": null, "e": 26911, "s": 26890, "text": "GATE-CS-2014-(Set-3)" }, { "code": null, "e": 26937, "s": 26911, "text": "GATE-GATE-CS-2014-(Set-3)" }, { "code": null, "e": 26942, "s": 26937, "text": "GATE" }, { "code": null, "e": 27040, "s": 26942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27074, "s": 27040, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27108, "s": 27074, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27141, "s": 27108, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27177, "s": 27141, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27211, "s": 27177, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27247, "s": 27211, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27281, "s": 27247, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27315, "s": 27281, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27349, "s": 27315, "text": "GATE | GATE-CS-2009 | Question 38" } ]
C++ Vector Library - at() Function
The C++ function std::vector::at() returns reference to the element present at location n in the vector. Following is the declaration for std::vector::at() function form std::vector header. reference at (size_type n); const_reference at (size_type n) const; n − Position of element from container. Returns an element from specified location if n is valid vector index. If vector object is constant qualified then method returns constant reference otherwise it returns non-constant reference. If n is not valid index out_of_bound exception is thrown. Constant i.e. O(1) The following example shows the usage of std::vector::at() function. #include <iostream> #include <vector> using namespace std; int main(void) { auto il = {1, 2, 3, 4, 5}; vector<int> v(il); for (int i = 0; i < v.size(); ++i) cout << v.at(i) << endl; return 0; } Let us compile and run the above program, this will produce the following result − 1 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2603, "text": "The C++ function std::vector::at() returns reference to the element present at location n in the vector." }, { "code": null, "e": 2793, "s": 2708, "text": "Following is the declaration for std::vector::at() function form std::vector header." }, { "code": null, "e": 2862, "s": 2793, "text": "reference at (size_type n);\nconst_reference at (size_type n) const;\n" }, { "code": null, "e": 2902, "s": 2862, "text": "n − Position of element from container." }, { "code": null, "e": 2973, "s": 2902, "text": "Returns an element from specified location if n is valid vector index." }, { "code": null, "e": 3096, "s": 2973, "text": "If vector object is constant qualified then method returns constant reference otherwise it returns non-constant reference." }, { "code": null, "e": 3154, "s": 3096, "text": "If n is not valid index out_of_bound exception is thrown." }, { "code": null, "e": 3173, "s": 3154, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3242, "s": 3173, "text": "The following example shows the usage of std::vector::at() function." }, { "code": null, "e": 3458, "s": 3242, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n auto il = {1, 2, 3, 4, 5};\n vector<int> v(il);\n\n for (int i = 0; i < v.size(); ++i)\n cout << v.at(i) << endl;\n\n return 0;\n}" }, { "code": null, "e": 3541, "s": 3458, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3552, "s": 3541, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 3559, "s": 3552, "text": " Print" }, { "code": null, "e": 3570, "s": 3559, "text": " Add Notes" } ]
DateTime.ToString() Method in C# | Set – 1 - GeeksforGeeks
27 Dec, 2021 This method is used to Converts the value of the current DateTime object to its equivalent string representation. There are total 4 methods in the overload list of this method: ToString(String, IFormatProvider) ToString(String) ToString(IFormatProvider) ToString() Here, we will discuss only first two methods. This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information. Syntax: public string ToString (string format, IFormatProvider provider);Parameters: format: A standard or custom date and time format string. provider: An object that supplies culture-specific formatting information.Return Value: This method returns a string representation of the value of the current DateTime object as specified by format and provider. Exceptions: FormatException: If The length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo or the format does not contain a valid custom format pattern. ArgumentOutOfRangeException: If The date and time is outside the range of dates supported by the calendar used by provider. Below programs illustrate the use of DateTime.ToString(String, IFormatProvider) Method:Example 1: csharp // C# program to demonstrate the// DateTime.ToString(String,// IFormatProvider) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of CultureInfo CultureInfo cultures = CultureInfo.CreateSpecificCulture("de-DE"); // declaring and initializing String array string[] format = {"d", "D", "f", "F", "g", "G", "m", "o", "r","s", "t" }; // calling get() Method Console.WriteLine("Converts the value of the current" + "DateTime object to its equivalent string"); for (int j = 0; j < format.Length; j++) { get(format[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining get() method public static void get(string format, CultureInfo cultures) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format, cultures); // display the converted ulong value Console.WriteLine(" {0} ", val); }} Converts the value of the currentDateTime object to its equivalent string 01.10.2008 Mittwoch, 1. Oktober 2008 Mittwoch, 1. Oktober 2008 17:04 Mittwoch, 1. Oktober 2008 17:04:32 01.10.2008 17:04 01.10.2008 17:04:32 1. Oktober 2008-10-01T17:04:32.0000000 Wed, 01 Oct 2008 17:04:32 GMT 2008-10-01T17:04:32 17:04 Example 2: For FormatException csharp // C# program to demonstrate the// DateTime.ToString(String,// IFormatProvider) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of CultureInfo CultureInfo cultures = CultureInfo.CreateSpecificCulture("de-DE"); // declaring and initializing String array string[] format = {"d", "D", "f", "F", "g", "G", "s", "x"}; // calling get() Method Console.WriteLine("Converts the value of the current" + "DateTime object to its equivalent string"); for (int j = 0; j < format.Length; j++) { get(format[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.WriteLine("format does not contain "+ "a valid custom format pattern."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining get() method public static void get(string format, CultureInfo cultures) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format, cultures); // display the converted ulong value Console.WriteLine(" {0} ", val); }} Converts the value of the currentDateTime object to its equivalent string 01.10.2008 Mittwoch, 1. Oktober 2008 Mittwoch, 1. Oktober 2008 17:04 Mittwoch, 1. Oktober 2008 17:04:32 01.10.2008 17:04 01.10.2008 17:04:32 2008-10-01T17:04:32 format does not contain a valid custom format pattern. Exception Thrown: System.FormatException Example 3: For ArgumentOutOfRangeException csharp // C# program to demonstrate the// DateTime.ToString(String,// IFormatProvider) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of CultureInfo CultureInfo cultures = CultureInfo.CreateSpecificCulture("ar-SA"); // declaring and initializing String array string[] format = {"d", "D", "f", "F", "g", "G","s" }; // calling get() Method Console.WriteLine("Converts the value of the current" + "DateTime object to its equivalent string"); for (int j = 0; j < format.Length; j++) { get(format[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.WriteLine("format does not contain "+ "a valid custom format pattern."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\n"); Console.WriteLine("The date and time is outside the range of dates" + "supported by the calendar used by ar-SA"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining get() method public static void get(string format, CultureInfo cultures) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2999, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format, cultures); // display the converted ulong value Console.WriteLine(" {0} ", val); }} Converts the value of the currentDateTime object to its equivalent string The date and time is outside the range of datessupported by the calendar used by ar-SA Exception Thrown: System.ArgumentOutOfRangeException This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture. Syntax: public string ToString (string format); Here it takes a standard or custom date and time format string.Return Value: This method returns a string representation of value of the current DateTime object as specified by format. Exceptions: FormatException: If the length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo or the format does not contain a valid custom format pattern. ArgumentOutOfRangeException: If the date and time is outside the range of dates supported by the calendar used by the current culture. Below programs illustrate the use of ToString(String) Method:Example 1: csharp // C# program to demonstrate the// DateTime.ToString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // declaring and initializing String array string[] format = {"d", "D", "f", "F", "g", "G", "m", "o", "r","s", "t" }; // calling get() Method Console.WriteLine("Converts the value of the current" + "DateTime object to its equivalent string"); for (int j = 0; j < format.Length; j++) { get(format[j]); } } catch (FormatException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining get() method public static void get(string format) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format); // display the converted ulong value Console.WriteLine(" {0} ", val); }} Converts the value of the currentDateTime object to its equivalent string 10/01/2008 Wednesday, 01 October 2008 Wednesday, 01 October 2008 17:04 Wednesday, 01 October 2008 17:04:32 10/01/2008 17:04 10/01/2008 17:04:32 October 01 2008-10-01T17:04:32.0000000 Wed, 01 Oct 2008 17:04:32 GMT 2008-10-01T17:04:32 17:04 Example 2: For FormatException csharp // C# program to demonstrate the// DateTime.ToString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // declaring and initializing String array string[] format = {"d", "D", "f", "F", "g", "G", "s", "x" }; // calling get() Method Console.WriteLine("Converts the value of the current" + "DateTime object to its equivalent string"); for (int j = 0; j < format.Length; j++) { get(format[j]); } } catch (FormatException e) { Console.WriteLine("\n"); Console.WriteLine("format does not contain "+ "a valid custom format pattern."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining get() method public static void get(string format) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format); // display the converted ulong value Console.WriteLine(" {0} ", val); }} Converts the value of the currentDateTime object to its equivalent string 10/01/2008 Wednesday, 01 October 2008 Wednesday, 01 October 2008 17:04 Wednesday, 01 October 2008 17:04:32 10/01/2008 17:04 10/01/2008 17:04:32 2008-10-01T17:04:32 format does not contain a valid custom format pattern. Exception Thrown: System.FormatException Example 3: For ArgumentOutOfRangeException csharp // C# program to demonstrate the// DateTime.ToString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // declaring and initializing String array string[] format = {"d", "D", "f", "F", "g", "G","s" }; // calling get() Method Console.WriteLine("Converts the value of the current" + "DateTime object to its equivalent string"); for (int j = 0; j < format.Length; j++) { get(format[j]); } } catch (FormatException e) { Console.WriteLine("\n"); Console.WriteLine("format does not contain "+ "a valid custom format pattern."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\n"); Console.WriteLine("The date and time are outside the range of dates " + "supported by the calendar used by the current culture."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining get() method public static void get(string format) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(9999, 13, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format); // display the converted ulong value Console.WriteLine(" {0} ", val); }} Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netframework-4.7.2 sagartomar9927 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25725, "s": 25547, "text": "This method is used to Converts the value of the current DateTime object to its equivalent string representation. There are total 4 methods in the overload list of this method: " }, { "code": null, "e": 25759, "s": 25725, "text": "ToString(String, IFormatProvider)" }, { "code": null, "e": 25776, "s": 25759, "text": "ToString(String)" }, { "code": null, "e": 25802, "s": 25776, "text": "ToString(IFormatProvider)" }, { "code": null, "e": 25813, "s": 25802, "text": "ToString()" }, { "code": null, "e": 25860, "s": 25813, "text": "Here, we will discuss only first two methods. " }, { "code": null, "e": 26040, "s": 25860, "text": "This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information." }, { "code": null, "e": 26397, "s": 26040, "text": "Syntax: public string ToString (string format, IFormatProvider provider);Parameters: format: A standard or custom date and time format string. provider: An object that supplies culture-specific formatting information.Return Value: This method returns a string representation of the value of the current DateTime object as specified by format and provider. " }, { "code": null, "e": 26410, "s": 26397, "text": "Exceptions: " }, { "code": null, "e": 26603, "s": 26410, "text": "FormatException: If The length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo or the format does not contain a valid custom format pattern." }, { "code": null, "e": 26727, "s": 26603, "text": "ArgumentOutOfRangeException: If The date and time is outside the range of dates supported by the calendar used by provider." }, { "code": null, "e": 26825, "s": 26727, "text": "Below programs illustrate the use of DateTime.ToString(String, IFormatProvider) Method:Example 1:" }, { "code": null, "e": 26832, "s": 26825, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTime.ToString(String,// IFormatProvider) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of CultureInfo CultureInfo cultures = CultureInfo.CreateSpecificCulture(\"de-DE\"); // declaring and initializing String array string[] format = {\"d\", \"D\", \"f\", \"F\", \"g\", \"G\", \"m\", \"o\", \"r\",\"s\", \"t\" }; // calling get() Method Console.WriteLine(\"Converts the value of the current\" + \"DateTime object to its equivalent string\"); for (int j = 0; j < format.Length; j++) { get(format[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining get() method public static void get(string format, CultureInfo cultures) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format, cultures); // display the converted ulong value Console.WriteLine(\" {0} \", val); }}", "e": 28550, "s": 26832, "text": null }, { "code": null, "e": 28881, "s": 28550, "text": "Converts the value of the currentDateTime object to its equivalent string\n 01.10.2008 \n Mittwoch, 1. Oktober 2008 \n Mittwoch, 1. Oktober 2008 17:04 \n Mittwoch, 1. Oktober 2008 17:04:32 \n 01.10.2008 17:04 \n 01.10.2008 17:04:32 \n 1. Oktober \n 2008-10-01T17:04:32.0000000 \n Wed, 01 Oct 2008 17:04:32 GMT \n 2008-10-01T17:04:32 \n 17:04" }, { "code": null, "e": 28914, "s": 28883, "text": "Example 2: For FormatException" }, { "code": null, "e": 28921, "s": 28914, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTime.ToString(String,// IFormatProvider) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of CultureInfo CultureInfo cultures = CultureInfo.CreateSpecificCulture(\"de-DE\"); // declaring and initializing String array string[] format = {\"d\", \"D\", \"f\", \"F\", \"g\", \"G\", \"s\", \"x\"}; // calling get() Method Console.WriteLine(\"Converts the value of the current\" + \"DateTime object to its equivalent string\"); for (int j = 0; j < format.Length; j++) { get(format[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.WriteLine(\"format does not contain \"+ \"a valid custom format pattern.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining get() method public static void get(string format, CultureInfo cultures) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format, cultures); // display the converted ulong value Console.WriteLine(\" {0} \", val); }}", "e": 30712, "s": 28921, "text": null }, { "code": null, "e": 31059, "s": 30712, "text": "Converts the value of the currentDateTime object to its equivalent string\n 01.10.2008 \n Mittwoch, 1. Oktober 2008 \n Mittwoch, 1. Oktober 2008 17:04 \n Mittwoch, 1. Oktober 2008 17:04:32 \n 01.10.2008 17:04 \n 01.10.2008 17:04:32 \n 2008-10-01T17:04:32 \n\n\nformat does not contain a valid custom format pattern.\nException Thrown: System.FormatException" }, { "code": null, "e": 31104, "s": 31061, "text": "Example 3: For ArgumentOutOfRangeException" }, { "code": null, "e": 31111, "s": 31104, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTime.ToString(String,// IFormatProvider) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of CultureInfo CultureInfo cultures = CultureInfo.CreateSpecificCulture(\"ar-SA\"); // declaring and initializing String array string[] format = {\"d\", \"D\", \"f\", \"F\", \"g\", \"G\",\"s\" }; // calling get() Method Console.WriteLine(\"Converts the value of the current\" + \"DateTime object to its equivalent string\"); for (int j = 0; j < format.Length; j++) { get(format[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.WriteLine(\"format does not contain \"+ \"a valid custom format pattern.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\n\"); Console.WriteLine(\"The date and time is outside the range of dates\" + \"supported by the calendar used by ar-SA\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining get() method public static void get(string format, CultureInfo cultures) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2999, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format, cultures); // display the converted ulong value Console.WriteLine(\" {0} \", val); }}", "e": 33062, "s": 31111, "text": null }, { "code": null, "e": 33278, "s": 33062, "text": "Converts the value of the currentDateTime object to its equivalent string\n\n\nThe date and time is outside the range of datessupported by the calendar used by ar-SA\nException Thrown: System.ArgumentOutOfRangeException" }, { "code": null, "e": 33474, "s": 33280, "text": "This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture." }, { "code": null, "e": 33709, "s": 33474, "text": "Syntax: public string ToString (string format); Here it takes a standard or custom date and time format string.Return Value: This method returns a string representation of value of the current DateTime object as specified by format. " }, { "code": null, "e": 33722, "s": 33709, "text": "Exceptions: " }, { "code": null, "e": 33915, "s": 33722, "text": "FormatException: If the length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo or the format does not contain a valid custom format pattern." }, { "code": null, "e": 34050, "s": 33915, "text": "ArgumentOutOfRangeException: If the date and time is outside the range of dates supported by the calendar used by the current culture." }, { "code": null, "e": 34122, "s": 34050, "text": "Below programs illustrate the use of ToString(String) Method:Example 1:" }, { "code": null, "e": 34129, "s": 34122, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTime.ToString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // declaring and initializing String array string[] format = {\"d\", \"D\", \"f\", \"F\", \"g\", \"G\", \"m\", \"o\", \"r\",\"s\", \"t\" }; // calling get() Method Console.WriteLine(\"Converts the value of the current\" + \"DateTime object to its equivalent string\"); for (int j = 0; j < format.Length; j++) { get(format[j]); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining get() method public static void get(string format) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format); // display the converted ulong value Console.WriteLine(\" {0} \", val); }}", "e": 35610, "s": 34129, "text": null }, { "code": null, "e": 35944, "s": 35610, "text": "Converts the value of the currentDateTime object to its equivalent string\n 10/01/2008 \n Wednesday, 01 October 2008 \n Wednesday, 01 October 2008 17:04 \n Wednesday, 01 October 2008 17:04:32 \n 10/01/2008 17:04 \n 10/01/2008 17:04:32 \n October 01 \n 2008-10-01T17:04:32.0000000 \n Wed, 01 Oct 2008 17:04:32 GMT \n 2008-10-01T17:04:32 \n 17:04" }, { "code": null, "e": 35977, "s": 35946, "text": "Example 2: For FormatException" }, { "code": null, "e": 35984, "s": 35977, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTime.ToString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // declaring and initializing String array string[] format = {\"d\", \"D\", \"f\", \"F\", \"g\", \"G\", \"s\", \"x\" }; // calling get() Method Console.WriteLine(\"Converts the value of the current\" + \"DateTime object to its equivalent string\"); for (int j = 0; j < format.Length; j++) { get(format[j]); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.WriteLine(\"format does not contain \"+ \"a valid custom format pattern.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining get() method public static void get(string format) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(2008, 10, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format); // display the converted ulong value Console.WriteLine(\" {0} \", val); }}", "e": 37571, "s": 35984, "text": null }, { "code": null, "e": 37921, "s": 37571, "text": "Converts the value of the currentDateTime object to its equivalent string\n 10/01/2008 \n Wednesday, 01 October 2008 \n Wednesday, 01 October 2008 17:04 \n Wednesday, 01 October 2008 17:04:32 \n 10/01/2008 17:04 \n 10/01/2008 17:04:32 \n 2008-10-01T17:04:32 \n\n\nformat does not contain a valid custom format pattern.\nException Thrown: System.FormatException" }, { "code": null, "e": 37966, "s": 37923, "text": "Example 3: For ArgumentOutOfRangeException" }, { "code": null, "e": 37973, "s": 37966, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTime.ToString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // declaring and initializing String array string[] format = {\"d\", \"D\", \"f\", \"F\", \"g\", \"G\",\"s\" }; // calling get() Method Console.WriteLine(\"Converts the value of the current\" + \"DateTime object to its equivalent string\"); for (int j = 0; j < format.Length; j++) { get(format[j]); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.WriteLine(\"format does not contain \"+ \"a valid custom format pattern.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\n\"); Console.WriteLine(\"The date and time are outside the range of dates \" + \"supported by the calendar used by the current culture.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining get() method public static void get(string format) { // Define date to be displayed. DateTime dateToDisplay = new DateTime(9999, 13, 1, 17, 4, 32); // converting DateTime to specified string string val = dateToDisplay.ToString(format); // display the converted ulong value Console.WriteLine(\" {0} \", val); }}", "e": 39721, "s": 37973, "text": null }, { "code": null, "e": 39733, "s": 39721, "text": "Reference: " }, { "code": null, "e": 39827, "s": 39733, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netframework-4.7.2 " }, { "code": null, "e": 39842, "s": 39827, "text": "sagartomar9927" }, { "code": null, "e": 39865, "s": 39842, "text": "CSharp DateTime Struct" }, { "code": null, "e": 39879, "s": 39865, "text": "CSharp-method" }, { "code": null, "e": 39882, "s": 39879, "text": "C#" }, { "code": null, "e": 39980, "s": 39882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40003, "s": 39980, "text": "Extension Method in C#" }, { "code": null, "e": 40031, "s": 40003, "text": "HashSet in C# with Examples" }, { "code": null, "e": 40048, "s": 40031, "text": "C# | Inheritance" }, { "code": null, "e": 40070, "s": 40048, "text": "Partial Classes in C#" }, { "code": null, "e": 40099, "s": 40070, "text": "C# | Generics - Introduction" }, { "code": null, "e": 40139, "s": 40099, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 40162, "s": 40139, "text": "Switch Statement in C#" }, { "code": null, "e": 40202, "s": 40162, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 40245, "s": 40202, "text": "C# | How to insert an element in an Array?" } ]
Create Classes Dynamically in Python - GeeksforGeeks
09 Mar, 2020 A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects having similar characteristics and behaviour are the instance of the same class. Python is a dynamic programming language and due to its flexibility Python has a significant advantage over statically typed languages. Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. Syntax: type(object) The above syntax returns the type of object. Example: # program to illustrate the use of type() print(type("Geeks4Geeks !")) print(type(1706256)) Output: class 'str' class 'int' Classes can be created dynamically using the below syntax:Syntax: type(name, bases, attributes) Parameters: name: The user defined name of the class bases: A list of base classes, and its type is tuple attributes: the data members and methods contained in the class The above Syntax returns a new type of object. Example: # program to create class dynamically # constructordef constructor(self, arg): self.constructor_arg = arg # methoddef displayMethod(self, arg): print(arg) # class method@classmethoddef classMethod(cls, arg): print(arg) # creating class dynamicallyGeeks = type("Geeks", (object, ), { # constructor "__init__": constructor, # data members "string_attribute": "Geeks 4 geeks !", "int_attribute": 1706256, # member functions "func_arg": displayMethod, "class_func": classMethod}) # creating objectsobj = Geeks("constructor argument")print(obj.constructor_arg)print(obj.string_attribute)print(obj.int_attribute)obj.func_arg("Geeks for Geeks")Geeks.class_func("Class Dynamically Created !") Output: constructor argument Geeks 4 geeks! 1706256 Geeks for GeeksClass Dynamically Created! In the above program, class Geeks is dynamically created which has a constructor. The data members of Geeks are string_attribute and int_attribute and member functions of Geeks are displayMethod() and classMethod(). An object obj of class Geeks is created and all the data members are assigned and displayed, all the member functions of Geeks are also called. Python-OOP python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25367, "s": 25339, "text": "\n09 Mar, 2020" }, { "code": null, "e": 25749, "s": 25367, "text": "A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects having similar characteristics and behaviour are the instance of the same class." }, { "code": null, "e": 25977, "s": 25749, "text": "Python is a dynamic programming language and due to its flexibility Python has a significant advantage over statically typed languages. Python Code can be dynamically imported and classes can be dynamically created at run-time." }, { "code": null, "e": 26111, "s": 25977, "text": "Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object." }, { "code": null, "e": 26119, "s": 26111, "text": "Syntax:" }, { "code": null, "e": 26133, "s": 26119, "text": "type(object)\n" }, { "code": null, "e": 26178, "s": 26133, "text": "The above syntax returns the type of object." }, { "code": null, "e": 26187, "s": 26178, "text": "Example:" }, { "code": "# program to illustrate the use of type() print(type(\"Geeks4Geeks !\")) print(type(1706256))", "e": 26280, "s": 26187, "text": null }, { "code": null, "e": 26288, "s": 26280, "text": "Output:" }, { "code": null, "e": 26313, "s": 26288, "text": "class 'str'\nclass 'int'\n" }, { "code": null, "e": 26379, "s": 26313, "text": "Classes can be created dynamically using the below syntax:Syntax:" }, { "code": null, "e": 26582, "s": 26379, "text": "type(name, bases, attributes) \n\nParameters:\nname: The user defined name of the class\nbases: A list of base classes, and its type is tuple\nattributes: the data members and methods contained in the class\n" }, { "code": null, "e": 26629, "s": 26582, "text": "The above Syntax returns a new type of object." }, { "code": null, "e": 26638, "s": 26629, "text": "Example:" }, { "code": "# program to create class dynamically # constructordef constructor(self, arg): self.constructor_arg = arg # methoddef displayMethod(self, arg): print(arg) # class method@classmethoddef classMethod(cls, arg): print(arg) # creating class dynamicallyGeeks = type(\"Geeks\", (object, ), { # constructor \"__init__\": constructor, # data members \"string_attribute\": \"Geeks 4 geeks !\", \"int_attribute\": 1706256, # member functions \"func_arg\": displayMethod, \"class_func\": classMethod}) # creating objectsobj = Geeks(\"constructor argument\")print(obj.constructor_arg)print(obj.string_attribute)print(obj.int_attribute)obj.func_arg(\"Geeks for Geeks\")Geeks.class_func(\"Class Dynamically Created !\")", "e": 27373, "s": 26638, "text": null }, { "code": null, "e": 27381, "s": 27373, "text": "Output:" }, { "code": null, "e": 27468, "s": 27381, "text": "constructor argument\nGeeks 4 geeks!\n1706256\nGeeks for GeeksClass Dynamically Created!\n" }, { "code": null, "e": 27828, "s": 27468, "text": "In the above program, class Geeks is dynamically created which has a constructor. The data members of Geeks are string_attribute and int_attribute and member functions of Geeks are displayMethod() and classMethod(). An object obj of class Geeks is created and all the data members are assigned and displayed, all the member functions of Geeks are also called." }, { "code": null, "e": 27839, "s": 27828, "text": "Python-OOP" }, { "code": null, "e": 27859, "s": 27839, "text": "python-oop-concepts" }, { "code": null, "e": 27866, "s": 27859, "text": "Python" }, { "code": null, "e": 27964, "s": 27866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27982, "s": 27964, "text": "Python Dictionary" }, { "code": null, "e": 28017, "s": 27982, "text": "Read a file line by line in Python" }, { "code": null, "e": 28049, "s": 28017, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28071, "s": 28049, "text": "Enumerate() in Python" }, { "code": null, "e": 28113, "s": 28071, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28143, "s": 28113, "text": "Iterate over a list in Python" }, { "code": null, "e": 28169, "s": 28143, "text": "Python String | replace()" }, { "code": null, "e": 28198, "s": 28169, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28242, "s": 28198, "text": "Reading and Writing to text files in Python" } ]
Java program to find the Frequency of a character in a given String
To find the Frequency of a character in a given String Read a string from the user. Read the character. Create an integer variable initialize it with 0. Compare each character in the given string with the entered character increment the above created integer variable each time a match occurs. import java.util.Scanner; public class FrequencyOfACharacter { public static void main(String args[]){ System.out.println("Enter a string value ::"); Scanner sc = new Scanner(System.in); String str = sc.nextLine(); System.out.println("Enter a particular character ::"); char character = sc.nextLine().charAt(0); int count = 0; for (int i=0; i<str.length(); i++){ if(character == str.charAt(i)){ count++; } } System.out.println("Frequency of the give character:: "+count); } } Enter a string value :: Hi welcome to Tutorialspoint Enter a particular character :: t Frequency of the give character:: 3
[ { "code": null, "e": 1117, "s": 1062, "text": "To find the Frequency of a character in a given String" }, { "code": null, "e": 1147, "s": 1117, "text": " Read a string from the user." }, { "code": null, "e": 1168, "s": 1147, "text": " Read the character." }, { "code": null, "e": 1218, "s": 1168, "text": " Create an integer variable initialize it with 0." }, { "code": null, "e": 1360, "s": 1218, "text": " Compare each character in the given string with the entered character increment the above created integer variable each time a match occurs." }, { "code": null, "e": 1928, "s": 1360, "text": "import java.util.Scanner;\npublic class FrequencyOfACharacter {\n public static void main(String args[]){\n System.out.println(\"Enter a string value ::\");\n Scanner sc = new Scanner(System.in);\n String str = sc.nextLine();\n\n System.out.println(\"Enter a particular character ::\");\n char character = sc.nextLine().charAt(0);\n int count = 0;\n\n for (int i=0; i<str.length(); i++){\n if(character == str.charAt(i)){\n count++;\n }\n }\n System.out.println(\"Frequency of the give character:: \"+count);\n }\n}" }, { "code": null, "e": 2051, "s": 1928, "text": "Enter a string value ::\nHi welcome to Tutorialspoint\nEnter a particular character ::\nt\nFrequency of the give character:: 3" } ]
Write a function to delete a Linked List - GeeksforGeeks
01 Feb, 2022 Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted.In Java, Python and JavaScript automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. Implementation: C++ C Java Python3 C# Javascript // C++ program to delete a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; /* Function to delete the entire linked list */void deleteList(Node** head_ref){ /* deref head_ref to get the real head */ Node* current = *head_ref; Node* next = NULL; while (current != NULL) { next = current->next; free(current); current = next; } /* deref head_ref to affect the real head back in the caller. */ *head_ref = NULL;} /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the list. */void 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;} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); cout << "Deleting linked list"; deleteList(&head); cout << "\nLinked list deleted";} // This is code is contributed by rathbhupendra // C program to delete a linked list#include<stdio.h>#include<stdlib.h>#include<assert.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* Function to delete the entire linked list */void deleteList(struct Node** head_ref){ /* deref head_ref to get the real head */ struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; free(current); current = next; } /* deref head_ref to affect the real head back in the caller. */ *head_ref = NULL;} /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); printf("\n Deleting linked list"); deleteList(&head); printf("\n Linked list deleted");} // Java program to delete a linked listclass LinkedList{ Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function deletes the entire linked list */ void deleteList() { head = null; } /* 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; } public static void main(String [] args) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->12->1->4->1 */ llist.push(1); llist.push(4); llist.push(1); llist.push(12); llist.push(1); System.out.println("Deleting the list"); llist.deleteList(); System.out.println("Linked list deleted"); }}// This code is contributed by Rajat Mishra # Python3 program to delete all# the nodes of singly linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Constructor to initialize the node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None def deleteList(self): # initialize the current node current = self.head while current: prev = current.next # move next node # delete the current node del current.data # set current equals prev node current = prev # In python garbage collection happens # therefore, only # self.head = None # would also delete the link list # push function to add node in front of llist def push(self, new_data): # Allocate the Node & # Put in the data new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Use push() to construct below# list 1-> 12-> 1-> 4-> 1if __name__ == '__main__': llist = LinkedList() llist.push(1) llist.push(4) llist.push(1) llist.push(12) llist.push(1) print("Deleting linked list") llist.deleteList() print("Linked list deleted") # This article is provided by Shrikant13 // C# program to delete a linked listusing System; public class LinkedList{ Node head; // head of the list /* Linked List node */ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function deletes the entire linked list */ void deleteList() { head = null; } /* 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; } // Driver code public static void Main(String [] args) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->12->1->4->1 */ llist.push(1); llist.push(4); llist.push(1); llist.push(12); llist.push(1); Console.WriteLine("Deleting the list"); llist.deleteList(); Console.WriteLine("Linked list deleted"); }} // This code has been contributed by Rajput-Ji <script>// javascript program to delete a linked listvar head; // head of the list /* Linked List node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Function deletes the entire linked list */ function deleteList() { head = null; } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var 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; } /* * Use push() to construct below list 1->12->1->4->1 */ push(1); push(4); push(1); push(12); push(1); document.write("Deleting the list<br/>"); deleteList(); document.write("Linked list deleted"); // This code contributed by Rajput-Ji</script> Deleting linked list Linked list deleted Time Complexity: O(n) Auxiliary Space: O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji rathbhupendra nidhi_biet RajSingh7 kumarashu414283 simranarora5sos diwakarsingh1 Delete a Linked List Linked Lists Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Merge Sort for Linked Lists Remove duplicates from a sorted linked list Top 20 Linked List Interview Question Function to check if a singly linked list is palindrome Detect and Remove Loop in a Linked List Remove duplicates from an unsorted linked list Reverse a Linked List in groups of given size | Set 1 Add two numbers represented by linked lists | Set 1
[ { "code": null, "e": 24433, "s": 24405, "text": "\n01 Feb, 2022" }, { "code": null, "e": 24764, "s": 24433, "text": "Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted.In Java, Python and JavaScript automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null." }, { "code": null, "e": 24781, "s": 24764, "text": "Implementation: " }, { "code": null, "e": 24785, "s": 24781, "text": "C++" }, { "code": null, "e": 24787, "s": 24785, "text": "C" }, { "code": null, "e": 24792, "s": 24787, "text": "Java" }, { "code": null, "e": 24800, "s": 24792, "text": "Python3" }, { "code": null, "e": 24803, "s": 24800, "text": "C#" }, { "code": null, "e": 24814, "s": 24803, "text": "Javascript" }, { "code": "// C++ program to delete a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; /* Function to delete the entire linked list */void deleteList(Node** head_ref){ /* deref head_ref to get the real head */ Node* current = *head_ref; Node* next = NULL; while (current != NULL) { next = current->next; free(current); current = next; } /* deref head_ref to affect the real head back in the caller. */ *head_ref = NULL;} /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the list. */void 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;} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); cout << \"Deleting linked list\"; deleteList(&head); cout << \"\\nLinked list deleted\";} // This is code is contributed by rathbhupendra", "e": 26170, "s": 24814, "text": null }, { "code": "// C program to delete a linked list#include<stdio.h>#include<stdlib.h>#include<assert.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* Function to delete the entire linked list */void deleteList(struct Node** head_ref){ /* deref head_ref to get the real head */ struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; free(current); current = next; } /* deref head_ref to affect the real head back in the caller. */ *head_ref = NULL;} /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); printf(\"\\n Deleting linked list\"); deleteList(&head); printf(\"\\n Linked list deleted\");}", "e": 27610, "s": 26170, "text": null }, { "code": "// Java program to delete a linked listclass LinkedList{ Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function deletes the entire linked list */ void deleteList() { head = null; } /* 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; } public static void main(String [] args) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->12->1->4->1 */ llist.push(1); llist.push(4); llist.push(1); llist.push(12); llist.push(1); System.out.println(\"Deleting the list\"); llist.deleteList(); System.out.println(\"Linked list deleted\"); }}// This code is contributed by Rajat Mishra", "e": 28751, "s": 27610, "text": null }, { "code": "# Python3 program to delete all# the nodes of singly linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Constructor to initialize the node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None def deleteList(self): # initialize the current node current = self.head while current: prev = current.next # move next node # delete the current node del current.data # set current equals prev node current = prev # In python garbage collection happens # therefore, only # self.head = None # would also delete the link list # push function to add node in front of llist def push(self, new_data): # Allocate the Node & # Put in the data new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Use push() to construct below# list 1-> 12-> 1-> 4-> 1if __name__ == '__main__': llist = LinkedList() llist.push(1) llist.push(4) llist.push(1) llist.push(12) llist.push(1) print(\"Deleting linked list\") llist.deleteList() print(\"Linked list deleted\") # This article is provided by Shrikant13", "e": 30224, "s": 28751, "text": null }, { "code": "// C# program to delete a linked listusing System; public class LinkedList{ Node head; // head of the list /* Linked List node */ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function deletes the entire linked list */ void deleteList() { head = null; } /* 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; } // Driver code public static void Main(String [] args) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->12->1->4->1 */ llist.push(1); llist.push(4); llist.push(1); llist.push(12); llist.push(1); Console.WriteLine(\"Deleting the list\"); llist.deleteList(); Console.WriteLine(\"Linked list deleted\"); }} // This code has been contributed by Rajput-Ji", "e": 31448, "s": 30224, "text": null }, { "code": "<script>// javascript program to delete a linked listvar head; // head of the list /* Linked List node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Function deletes the entire linked list */ function deleteList() { head = null; } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var 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; } /* * Use push() to construct below list 1->12->1->4->1 */ push(1); push(4); push(1); push(12); push(1); document.write(\"Deleting the list<br/>\"); deleteList(); document.write(\"Linked list deleted\"); // This code contributed by Rajput-Ji</script>", "e": 32469, "s": 31448, "text": null }, { "code": null, "e": 32510, "s": 32469, "text": "Deleting linked list\nLinked list deleted" }, { "code": null, "e": 32555, "s": 32510, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 32680, "s": 32555, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32690, "s": 32680, "text": "Rajput-Ji" }, { "code": null, "e": 32704, "s": 32690, "text": "rathbhupendra" }, { "code": null, "e": 32715, "s": 32704, "text": "nidhi_biet" }, { "code": null, "e": 32725, "s": 32715, "text": "RajSingh7" }, { "code": null, "e": 32741, "s": 32725, "text": "kumarashu414283" }, { "code": null, "e": 32757, "s": 32741, "text": "simranarora5sos" }, { "code": null, "e": 32771, "s": 32757, "text": "diwakarsingh1" }, { "code": null, "e": 32792, "s": 32771, "text": "Delete a Linked List" }, { "code": null, "e": 32805, "s": 32792, "text": "Linked Lists" }, { "code": null, "e": 32817, "s": 32805, "text": "Linked List" }, { "code": null, "e": 32829, "s": 32817, "text": "Linked List" }, { "code": null, "e": 32927, "s": 32829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32974, "s": 32927, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 33035, "s": 32974, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 33063, "s": 33035, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 33107, "s": 33063, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 33145, "s": 33107, "text": "Top 20 Linked List Interview Question" }, { "code": null, "e": 33201, "s": 33145, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 33241, "s": 33201, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 33288, "s": 33241, "text": "Remove duplicates from an unsorted linked list" }, { "code": null, "e": 33342, "s": 33288, "text": "Reverse a Linked List in groups of given size | Set 1" } ]
How to cluster images based on visual similarity | by Gabe Flomo | Towards Data Science
In this tutorial, I'm going to walk you through using a pre-trained neural network to extract a feature vector from images and cluster the images based on how similar the feature vectors are. The pre-trained model that will be used in this tutorial is the VGG16 convolutional neural network (CNN), which is considered to be state of the art for image recognition tasks. We are going to be using this model as a feature extractor only, meaning that we will remove the final (prediction) layer so that we can obtain a feature vector. This implementation will use the flowers dataset from Kaggle which you can download here. The dataset contains 210 images of 10 different species of flowers that will be downloaded as png files. Before we get started, we need to import the modules needed in order to load/process the images along with the modules to extract and cluster our feature vectors. load_img allows us to load an image from a file as a PIL object img_to_array allows us to convert the PIL object into a NumPy array preproccess_input is meant to prepare your image into the format the model requires. You should load images with the Keras load_img function so that you guarantee the images you load are compatible with the preprocess_input function. VGG16 is the pre-trained model we’re going to use KMeans the clustering algorithm we’re going to use PCA for reducing the dimensions of our feature vector Now that the data is downloaded on your computer, we want python to point to the location where the images are located. This way instead of loading a whole file path, we can simply just use the name of the file. # view the first 10 flower entriesprint(flowers[:10])output:['0001.png', '0002.png', '0003.png', '0004.png', '0005.png', '0006.png', '0007.png', '0008.png', '0009.png', '0010.png'] Now that we have all of the filenames loaded into the list of flowers, we can start preprocessing the images. This is where we put the load_img() and preprocess_input() methods to use. When loading the images we are going to set the target size to (224, 224) because the VGG model expects the images it receives to be 224x224 NumPy arrays. Currently, our array has only 3 dimensions (rows, columns, channels) and the model operates in batches of samples. So we need to expand our array to add the dimension that will let the model know how many images we are giving it (num_of_samples, rows, columns, channels). Number of dimensions: 4 Number of images (batch size): 1 Number of rows (0th axis): 224 Number of columns (1st axis): 224 Number of channels (rgb): 3 The last step is to pass the reshaped array to the preprocess_input method and our image is ready to be loaded into the model. Now we can load the VGG model and remove the output layer manually. This means that the new final layer is a fully-connected layer with 4,096 output nodes. This vector of 4,096 numbers is the feature vector that we will use to cluster the images. Now that the final layer is removed, we can pass our image through the predict method to get our feature vector. Heres the all the code in a single function Now we can use this feature_extraction function to extract the features from all of the images and store the features in a dictionary with filename as the keys. Wall time: 56.2 s Since our feature vector has over 4,000 dimensions, your computer will thank you if you reduce the number of dimensions from 4,000 to a much smaller number. We can't simply just shorten the list by slicing it or using some subset of it because we will lose information. If only there was a way to reduce the dimensionality while keeping as much information as possible. Enter the realm of principle component analysis. I'm not going to waste time explaining what PCA is because there are already tons of articles explaining it, which I’ll link here. Simply put, if you are working with data and have a lot of variables to consider (in our case 4096), PCA allows you to reduce the number of variables while preserving as much information from the original set as possible. The number of dimensions to reduce down to is up to you and I'm sure there's a method for finding the best number of components to use, but for this case, I just chose 100 as an arbitrary number. print(f"Components before PCA: {f.shape[1]}")print(f"Components after PCA: {pca.n_components}")Components before PCA: 4096Components after PCA: 100 Now that we have a smaller feature set, we are ready to cluster our images. You’ll define a target number k, which refers to the number of centroids you need in the dataset. A centroid is the imaginary or real location representing the center of the cluster. This algorithm will allow us to group our feature vectors into k clusters. Each cluster should contain images that are visually similar. In this case, we know there are 10 different species of flowers so we can have k = 10. kmeans.labels_ [6, 6, 8, 6, 6, 5, 4, 6, 5, 6, 4, 6, 6, 3, 3, 5, 6, 6, 4, 4, 8, 1, 3, 8, 4, 2, 8, 4, 2, 6, 9, 7, 4, 4, 0, 5, 4, 9, 8, 5, 9, 5, 3, 6, 5, 1, 3, 9, 6, 5, 0, 1, 3, 9, 6, 7, 4, 6, 4, 5, 8, 5, 3, 6, 5, 4, 6, 5, 2, 1, 4, 3, 9, 5, 4, 6, 2, 4, 5, 0, 5, 1, 2, 9, 5, 4, 8, 1, 7, 1, 3, 5, 4, 8, 5, 4, 6, 9, 5, 9, 5, 8, 1, 4, 9, 8, 5, 4, 5, 6, 4, 1, 8, 9, 4, 6, 5, 7, 5, 6, 4, 8, 1, 4, 5, 5, 8, 6, 5, 2, 4, 8, 5, 1, 1, 6, 6, 7, 8, 1, 9, 1, 6, 4, 8, 3, 6, 1, 0, 0, 8, 1, 3, 4, 9, 9, 0, 4, 0, 6, 4, 9, 0, 3, 5, 0, 3, 9, 9, 4, 9, 5, 0, 9, 5, 4, 5, 1, 8, 3, 6, 4, 5, 2, 6, 6, 9, 5, 0, 3, 1, 3, 5, 4, 5, 0, 9, 4, 2, 1, 0, 9, 4, 9, 1, 2, 6, 1, 6, 0] Each label in this list is a cluster identifier for each image in our dataset. The order of the labels is parallel to the list of filenames for each image. This way we can group the images into their clusters. # view the filenames in cluster 0groups[0]output: ['0035.png', '0051.png', '0080.png', '0149.png', '0150.png', '0157.png', '0159.png', '0163.png', '0166.png', '0173.png', '0189.png', '0196.png', '0201.png', '0210.png'] All we have left to do is to view a cluster to see how well our model did by inspecting the clusters. Here we can see that our model did pretty well on clustering the flower images. We can even see that cluster 2 and cluster 0 both have yellow flowers yet, the type of flowers in each cluster are different species. Here is the whole process in one file. Hope you all learned something new, leave a comment if you have any questions or had an aha moment :) Transfer Learning for feature extraction
[ { "code": null, "e": 239, "s": 47, "text": "In this tutorial, I'm going to walk you through using a pre-trained neural network to extract a feature vector from images and cluster the images based on how similar the feature vectors are." }, { "code": null, "e": 579, "s": 239, "text": "The pre-trained model that will be used in this tutorial is the VGG16 convolutional neural network (CNN), which is considered to be state of the art for image recognition tasks. We are going to be using this model as a feature extractor only, meaning that we will remove the final (prediction) layer so that we can obtain a feature vector." }, { "code": null, "e": 774, "s": 579, "text": "This implementation will use the flowers dataset from Kaggle which you can download here. The dataset contains 210 images of 10 different species of flowers that will be downloaded as png files." }, { "code": null, "e": 937, "s": 774, "text": "Before we get started, we need to import the modules needed in order to load/process the images along with the modules to extract and cluster our feature vectors." }, { "code": null, "e": 1001, "s": 937, "text": "load_img allows us to load an image from a file as a PIL object" }, { "code": null, "e": 1069, "s": 1001, "text": "img_to_array allows us to convert the PIL object into a NumPy array" }, { "code": null, "e": 1303, "s": 1069, "text": "preproccess_input is meant to prepare your image into the format the model requires. You should load images with the Keras load_img function so that you guarantee the images you load are compatible with the preprocess_input function." }, { "code": null, "e": 1353, "s": 1303, "text": "VGG16 is the pre-trained model we’re going to use" }, { "code": null, "e": 1404, "s": 1353, "text": "KMeans the clustering algorithm we’re going to use" }, { "code": null, "e": 1458, "s": 1404, "text": "PCA for reducing the dimensions of our feature vector" }, { "code": null, "e": 1670, "s": 1458, "text": "Now that the data is downloaded on your computer, we want python to point to the location where the images are located. This way instead of loading a whole file path, we can simply just use the name of the file." }, { "code": null, "e": 1851, "s": 1670, "text": "# view the first 10 flower entriesprint(flowers[:10])output:['0001.png', '0002.png', '0003.png', '0004.png', '0005.png', '0006.png', '0007.png', '0008.png', '0009.png', '0010.png']" }, { "code": null, "e": 1961, "s": 1851, "text": "Now that we have all of the filenames loaded into the list of flowers, we can start preprocessing the images." }, { "code": null, "e": 2191, "s": 1961, "text": "This is where we put the load_img() and preprocess_input() methods to use. When loading the images we are going to set the target size to (224, 224) because the VGG model expects the images it receives to be 224x224 NumPy arrays." }, { "code": null, "e": 2463, "s": 2191, "text": "Currently, our array has only 3 dimensions (rows, columns, channels) and the model operates in batches of samples. So we need to expand our array to add the dimension that will let the model know how many images we are giving it (num_of_samples, rows, columns, channels)." }, { "code": null, "e": 2613, "s": 2463, "text": "Number of dimensions: 4 Number of images (batch size): 1 Number of rows (0th axis): 224 Number of columns (1st axis): 224 Number of channels (rgb): 3" }, { "code": null, "e": 2740, "s": 2613, "text": "The last step is to pass the reshaped array to the preprocess_input method and our image is ready to be loaded into the model." }, { "code": null, "e": 2987, "s": 2740, "text": "Now we can load the VGG model and remove the output layer manually. This means that the new final layer is a fully-connected layer with 4,096 output nodes. This vector of 4,096 numbers is the feature vector that we will use to cluster the images." }, { "code": null, "e": 3100, "s": 2987, "text": "Now that the final layer is removed, we can pass our image through the predict method to get our feature vector." }, { "code": null, "e": 3144, "s": 3100, "text": "Heres the all the code in a single function" }, { "code": null, "e": 3305, "s": 3144, "text": "Now we can use this feature_extraction function to extract the features from all of the images and store the features in a dictionary with filename as the keys." }, { "code": null, "e": 3323, "s": 3305, "text": "Wall time: 56.2 s" }, { "code": null, "e": 3693, "s": 3323, "text": "Since our feature vector has over 4,000 dimensions, your computer will thank you if you reduce the number of dimensions from 4,000 to a much smaller number. We can't simply just shorten the list by slicing it or using some subset of it because we will lose information. If only there was a way to reduce the dimensionality while keeping as much information as possible." }, { "code": null, "e": 3742, "s": 3693, "text": "Enter the realm of principle component analysis." }, { "code": null, "e": 3873, "s": 3742, "text": "I'm not going to waste time explaining what PCA is because there are already tons of articles explaining it, which I’ll link here." }, { "code": null, "e": 4095, "s": 3873, "text": "Simply put, if you are working with data and have a lot of variables to consider (in our case 4096), PCA allows you to reduce the number of variables while preserving as much information from the original set as possible." }, { "code": null, "e": 4291, "s": 4095, "text": "The number of dimensions to reduce down to is up to you and I'm sure there's a method for finding the best number of components to use, but for this case, I just chose 100 as an arbitrary number." }, { "code": null, "e": 4439, "s": 4291, "text": "print(f\"Components before PCA: {f.shape[1]}\")print(f\"Components after PCA: {pca.n_components}\")Components before PCA: 4096Components after PCA: 100" }, { "code": null, "e": 4515, "s": 4439, "text": "Now that we have a smaller feature set, we are ready to cluster our images." }, { "code": null, "e": 4698, "s": 4515, "text": "You’ll define a target number k, which refers to the number of centroids you need in the dataset. A centroid is the imaginary or real location representing the center of the cluster." }, { "code": null, "e": 4922, "s": 4698, "text": "This algorithm will allow us to group our feature vectors into k clusters. Each cluster should contain images that are visually similar. In this case, we know there are 10 different species of flowers so we can have k = 10." }, { "code": null, "e": 4937, "s": 4922, "text": "kmeans.labels_" }, { "code": null, "e": 5568, "s": 4937, "text": "[6, 6, 8, 6, 6, 5, 4, 6, 5, 6, 4, 6, 6, 3, 3, 5, 6, 6, 4, 4, 8, 1, 3, 8, 4, 2, 8, 4, 2, 6, 9, 7, 4, 4, 0, 5, 4, 9, 8, 5, 9, 5, 3, 6, 5, 1, 3, 9, 6, 5, 0, 1, 3, 9, 6, 7, 4, 6, 4, 5, 8, 5, 3, 6, 5, 4, 6, 5, 2, 1, 4, 3, 9, 5, 4, 6, 2, 4, 5, 0, 5, 1, 2, 9, 5, 4, 8, 1, 7, 1, 3, 5, 4, 8, 5, 4, 6, 9, 5, 9, 5, 8, 1, 4, 9, 8, 5, 4, 5, 6, 4, 1, 8, 9, 4, 6, 5, 7, 5, 6, 4, 8, 1, 4, 5, 5, 8, 6, 5, 2, 4, 8, 5, 1, 1, 6, 6, 7, 8, 1, 9, 1, 6, 4, 8, 3, 6, 1, 0, 0, 8, 1, 3, 4, 9, 9, 0, 4, 0, 6, 4, 9, 0, 3, 5, 0, 3, 9, 9, 4, 9, 5, 0, 9, 5, 4, 5, 1, 8, 3, 6, 4, 5, 2, 6, 6, 9, 5, 0, 3, 1, 3, 5, 4, 5, 0, 9, 4, 2, 1, 0, 9, 4, 9, 1, 2, 6, 1, 6, 0]" }, { "code": null, "e": 5778, "s": 5568, "text": "Each label in this list is a cluster identifier for each image in our dataset. The order of the labels is parallel to the list of filenames for each image. This way we can group the images into their clusters." }, { "code": null, "e": 5997, "s": 5778, "text": "# view the filenames in cluster 0groups[0]output: ['0035.png', '0051.png', '0080.png', '0149.png', '0150.png', '0157.png', '0159.png', '0163.png', '0166.png', '0173.png', '0189.png', '0196.png', '0201.png', '0210.png']" }, { "code": null, "e": 6099, "s": 5997, "text": "All we have left to do is to view a cluster to see how well our model did by inspecting the clusters." }, { "code": null, "e": 6313, "s": 6099, "text": "Here we can see that our model did pretty well on clustering the flower images. We can even see that cluster 2 and cluster 0 both have yellow flowers yet, the type of flowers in each cluster are different species." }, { "code": null, "e": 6352, "s": 6313, "text": "Here is the whole process in one file." }, { "code": null, "e": 6454, "s": 6352, "text": "Hope you all learned something new, leave a comment if you have any questions or had an aha moment :)" } ]
Predictive Analysis of an IPL Match | by Geet Pithadia | Towards Data Science
Since the dawn of the IPL in 2008, it has attracted viewers all around the globe. High level of uncertainty and last moment nail biters has urged fans to watch the matches. Within a short period, IPL has become the highest revenue generating league of cricket. Data Analytics has been a part of sports entertainment for a long time. In a cricket match, we might have seen the scoreline showing the probability of the team winning based on the current match situation. This, my friend, is Data Analytics in action! Being a cricket fan, visualizing the statistics of cricket is mesmerizing. While I was jumping blogs on Medium and kernels (Let’s say code playbook) on Kaggle, I was fascinated by the analysis done. Hence, I decided to get my first hands-on experience by building a classifier to predict the winning team. In Machine Learning, the problems are categorized into 2 groups mainly: Regression Problem and Classification problem. The Regression problem deals with the kind of problems having continuous values as output while in the Classification problem the outputs are categorical values. Since the output of winner prediction is a categorical value, the problem which we are trying to solve is a Classification problem. So where to start, and what to do? Understand the dataset.Clean the data.Analyze the candidate columns to be Features.Process the features as required by the model/algorithm.Train the model/algorithm on training data.Test the model/algorithm on testing data.Tune the model/algorithm for higher accuracy. Understand the dataset. Clean the data. Analyze the candidate columns to be Features. Process the features as required by the model/algorithm. Train the model/algorithm on training data. Test the model/algorithm on testing data. Tune the model/algorithm for higher accuracy. Let’s get started! Well, for smooth learning I recommend having a glance at Python libraries that I used like Pandas, Numpy, and Scikit-learn. While dealing with data, Kaggle: Your Home for Data Science is the to-go platform. I used the dataset https://www.kaggle.com/nowke9/ipldata. The dataset has 2 files: matches.csv having every match detail from 2008 to 2019 and deliveries.csv having ball by ball detail for every match. I am using .read_csv() to read the CSV file. The path in the .read_csv() function can be relative or absolute. Here, I am using Google Colaboratory as my playground and hence the file is stored there. Nothing is perfect. Life is messy. Relationships are complex. Outcomes are uncertain. People are irrational. — Hugh Mackay As rightly said by Hugh Mackay “Nothing is perfect” in the above quote and in this case, it relates to our data. The data that we have, contains null values in several columns. column null_valuescity 7 winner 4 player_of_match 4 umpire1 2 umpire2 2 umpire3 637 dtype: int64 There are several ways to handle the null values and among them, I will be using Imputation on column city. Imputation is a way to fill the missing values statistically. For more reference, you might find https://www.kaggle.com/alexisbcook/missing-values helpful. Since filling the values in the column winner is illogical, we can drop those records. Combination of .select() and .where() from numpy replaces the values in the columns city based on the column venue if the values in city are null. While playing around with the data, I found an interesting redundancy. Team Rising Pune SuperGiants were duplicated in columns team_1, team_2, winner, and toss_winner. Replacing these values with one value is the obvious thing to do next. Python libraries make data manipulation an easy task to perform. Pandas allow us to load the data into DataFrame and perform manipulations on it easily and efficiently. Phew!! The data is clean now. We can finally start on analyzing the features (columns). Note: The columns taken into consideration are: team_1, team_2, toss_winner, toss_decision, venue, city and winner. For the columns to be able to assist the model in the prediction, the values should make some sense to the computers. Since they (still) don’t have the ability to understand and draw inference from the text, we need to encode the strings to numeric categorical values. While we may choose to do the process manually, the Scikit-learn library gives us an option to use LabelEncoder. Before we hop on to building models, an important observation has to be acknowledged. Columns like toss_winner, toss_decision, and winner might make sense to us, but what about the machines? Let me elaborate. The values in toss_winner and winner include team names, but what is the relation of these variables with team_1 or team_2? The only thing common between them is that they would share the same value, but that is not enough to be logical. Also, toss_decision might be bat or field, but what team are they referring to? To tackle this problem, we will add new columns team1_win, team1_toss_win, and team1_bat for columns winner, toss_winner, and toss_decision such that they reflect the relationship with column team_1. The value in the column team1_win will be 1 if team1 wins else 0, for column team1_toss_decision it will be 1 if team1 wins the toss and finally team1_bat will be 1 if team1 is batting first. We manually selected a bunch of features based on the domain knowledge we had. But we have no statistical proof of the selected features being important for our dataset. Scikit-learn provides an excellent module named feature_selection which gives us a couple of ways to do the feature selection. First, we will check the columns if any of them represent the same values as other columns. For this, we need to create a correlation matrix to find out the relationships between the column. If the absolute value of the correlation between the columns is high enough, we can say that they represent similar values. Correlation matrix for our data would look something like this: Here, we see that team1_bat represents the same information as team1_toss_win. Strange, right? It’s just how the dataset was built, if team1 wins the toss then they will always bat and if team2 wins the toss then they will always field. So we removed the column team1_bat from our list of features. For a Classification problem, multiple algorithms can train the classifier according to the data we have and using the pattern, predict the outcomes of certain input conditions. We will try DecisionTreeClassifier, RandomForestClassifier, LogisticRegression, and SVM and choose the algorithm best suited for our data distribution. Once we build the model, we need to validate that model using values that are never exposed to the model. Hence we split our data using train_test_split, a class provided by Scikit-learn into 2 parts having a distribution of 80–20. The model is trained on 80% of data and validated against the other 20% of the data. We can now train various models and compare the performances. This resulted in: It is evident from the results that SVM gives us a higher accuracy of 66.23% than other algorithms for this data distribution. Even though the accuracy is not high enough to be useful, it gives a basic idea about the strategies and methodologies used in designing a solution to the Machine Learning problem. There are many other factors affecting the outcome of a match like weather, the form of a player, home ground advantage, etc which are not included here. Try adding these features and playing around with it. A further modification to the code can be done by using the concept of K-Fold cross-validation that is an alternative to train_test_split. Check out an amazing article in the link for K-Fold. Since you have made it till here, we did a decent job in predicting the probability of an IPL team to win by converting it to a Binary classification problem and using Python libraries while learning about them. If you have any questions, suggestions or feedback, feel free to reach out to me on Email or LinkedIn. You can find this code on my GitHub and you are more than welcome to contribute. Happy Predicting! Thanks to Dhrumil Patel, Syed Zubair, Sahil Sangani, and Yash Shah for the help!
[ { "code": null, "e": 560, "s": 46, "text": "Since the dawn of the IPL in 2008, it has attracted viewers all around the globe. High level of uncertainty and last moment nail biters has urged fans to watch the matches. Within a short period, IPL has become the highest revenue generating league of cricket. Data Analytics has been a part of sports entertainment for a long time. In a cricket match, we might have seen the scoreline showing the probability of the team winning based on the current match situation. This, my friend, is Data Analytics in action!" }, { "code": null, "e": 866, "s": 560, "text": "Being a cricket fan, visualizing the statistics of cricket is mesmerizing. While I was jumping blogs on Medium and kernels (Let’s say code playbook) on Kaggle, I was fascinated by the analysis done. Hence, I decided to get my first hands-on experience by building a classifier to predict the winning team." }, { "code": null, "e": 1279, "s": 866, "text": "In Machine Learning, the problems are categorized into 2 groups mainly: Regression Problem and Classification problem. The Regression problem deals with the kind of problems having continuous values as output while in the Classification problem the outputs are categorical values. Since the output of winner prediction is a categorical value, the problem which we are trying to solve is a Classification problem." }, { "code": null, "e": 1314, "s": 1279, "text": "So where to start, and what to do?" }, { "code": null, "e": 1583, "s": 1314, "text": "Understand the dataset.Clean the data.Analyze the candidate columns to be Features.Process the features as required by the model/algorithm.Train the model/algorithm on training data.Test the model/algorithm on testing data.Tune the model/algorithm for higher accuracy." }, { "code": null, "e": 1607, "s": 1583, "text": "Understand the dataset." }, { "code": null, "e": 1623, "s": 1607, "text": "Clean the data." }, { "code": null, "e": 1669, "s": 1623, "text": "Analyze the candidate columns to be Features." }, { "code": null, "e": 1726, "s": 1669, "text": "Process the features as required by the model/algorithm." }, { "code": null, "e": 1770, "s": 1726, "text": "Train the model/algorithm on training data." }, { "code": null, "e": 1812, "s": 1770, "text": "Test the model/algorithm on testing data." }, { "code": null, "e": 1858, "s": 1812, "text": "Tune the model/algorithm for higher accuracy." }, { "code": null, "e": 1877, "s": 1858, "text": "Let’s get started!" }, { "code": null, "e": 2001, "s": 1877, "text": "Well, for smooth learning I recommend having a glance at Python libraries that I used like Pandas, Numpy, and Scikit-learn." }, { "code": null, "e": 2286, "s": 2001, "text": "While dealing with data, Kaggle: Your Home for Data Science is the to-go platform. I used the dataset https://www.kaggle.com/nowke9/ipldata. The dataset has 2 files: matches.csv having every match detail from 2008 to 2019 and deliveries.csv having ball by ball detail for every match." }, { "code": null, "e": 2487, "s": 2286, "text": "I am using .read_csv() to read the CSV file. The path in the .read_csv() function can be relative or absolute. Here, I am using Google Colaboratory as my playground and hence the file is stored there." }, { "code": null, "e": 2610, "s": 2487, "text": "Nothing is perfect. Life is messy. Relationships are complex. Outcomes are uncertain. People are irrational. — Hugh Mackay" }, { "code": null, "e": 2787, "s": 2610, "text": "As rightly said by Hugh Mackay “Nothing is perfect” in the above quote and in this case, it relates to our data. The data that we have, contains null values in several columns." }, { "code": null, "e": 2897, "s": 2787, "text": "column null_valuescity 7 winner 4 player_of_match 4 umpire1 2 umpire2 2 umpire3 637 dtype: int64" }, { "code": null, "e": 3248, "s": 2897, "text": "There are several ways to handle the null values and among them, I will be using Imputation on column city. Imputation is a way to fill the missing values statistically. For more reference, you might find https://www.kaggle.com/alexisbcook/missing-values helpful. Since filling the values in the column winner is illogical, we can drop those records." }, { "code": null, "e": 3395, "s": 3248, "text": "Combination of .select() and .where() from numpy replaces the values in the columns city based on the column venue if the values in city are null." }, { "code": null, "e": 3563, "s": 3395, "text": "While playing around with the data, I found an interesting redundancy. Team Rising Pune SuperGiants were duplicated in columns team_1, team_2, winner, and toss_winner." }, { "code": null, "e": 3803, "s": 3563, "text": "Replacing these values with one value is the obvious thing to do next. Python libraries make data manipulation an easy task to perform. Pandas allow us to load the data into DataFrame and perform manipulations on it easily and efficiently." }, { "code": null, "e": 3891, "s": 3803, "text": "Phew!! The data is clean now. We can finally start on analyzing the features (columns)." }, { "code": null, "e": 4007, "s": 3891, "text": "Note: The columns taken into consideration are: team_1, team_2, toss_winner, toss_decision, venue, city and winner." }, { "code": null, "e": 4389, "s": 4007, "text": "For the columns to be able to assist the model in the prediction, the values should make some sense to the computers. Since they (still) don’t have the ability to understand and draw inference from the text, we need to encode the strings to numeric categorical values. While we may choose to do the process manually, the Scikit-learn library gives us an option to use LabelEncoder." }, { "code": null, "e": 4580, "s": 4389, "text": "Before we hop on to building models, an important observation has to be acknowledged. Columns like toss_winner, toss_decision, and winner might make sense to us, but what about the machines?" }, { "code": null, "e": 5116, "s": 4580, "text": "Let me elaborate. The values in toss_winner and winner include team names, but what is the relation of these variables with team_1 or team_2? The only thing common between them is that they would share the same value, but that is not enough to be logical. Also, toss_decision might be bat or field, but what team are they referring to? To tackle this problem, we will add new columns team1_win, team1_toss_win, and team1_bat for columns winner, toss_winner, and toss_decision such that they reflect the relationship with column team_1." }, { "code": null, "e": 5308, "s": 5116, "text": "The value in the column team1_win will be 1 if team1 wins else 0, for column team1_toss_decision it will be 1 if team1 wins the toss and finally team1_bat will be 1 if team1 is batting first." }, { "code": null, "e": 5920, "s": 5308, "text": "We manually selected a bunch of features based on the domain knowledge we had. But we have no statistical proof of the selected features being important for our dataset. Scikit-learn provides an excellent module named feature_selection which gives us a couple of ways to do the feature selection. First, we will check the columns if any of them represent the same values as other columns. For this, we need to create a correlation matrix to find out the relationships between the column. If the absolute value of the correlation between the columns is high enough, we can say that they represent similar values." }, { "code": null, "e": 5984, "s": 5920, "text": "Correlation matrix for our data would look something like this:" }, { "code": null, "e": 6283, "s": 5984, "text": "Here, we see that team1_bat represents the same information as team1_toss_win. Strange, right? It’s just how the dataset was built, if team1 wins the toss then they will always bat and if team2 wins the toss then they will always field. So we removed the column team1_bat from our list of features." }, { "code": null, "e": 6613, "s": 6283, "text": "For a Classification problem, multiple algorithms can train the classifier according to the data we have and using the pattern, predict the outcomes of certain input conditions. We will try DecisionTreeClassifier, RandomForestClassifier, LogisticRegression, and SVM and choose the algorithm best suited for our data distribution." }, { "code": null, "e": 6930, "s": 6613, "text": "Once we build the model, we need to validate that model using values that are never exposed to the model. Hence we split our data using train_test_split, a class provided by Scikit-learn into 2 parts having a distribution of 80–20. The model is trained on 80% of data and validated against the other 20% of the data." }, { "code": null, "e": 6992, "s": 6930, "text": "We can now train various models and compare the performances." }, { "code": null, "e": 7010, "s": 6992, "text": "This resulted in:" }, { "code": null, "e": 7137, "s": 7010, "text": "It is evident from the results that SVM gives us a higher accuracy of 66.23% than other algorithms for this data distribution." }, { "code": null, "e": 7318, "s": 7137, "text": "Even though the accuracy is not high enough to be useful, it gives a basic idea about the strategies and methodologies used in designing a solution to the Machine Learning problem." }, { "code": null, "e": 7718, "s": 7318, "text": "There are many other factors affecting the outcome of a match like weather, the form of a player, home ground advantage, etc which are not included here. Try adding these features and playing around with it. A further modification to the code can be done by using the concept of K-Fold cross-validation that is an alternative to train_test_split. Check out an amazing article in the link for K-Fold." }, { "code": null, "e": 8114, "s": 7718, "text": "Since you have made it till here, we did a decent job in predicting the probability of an IPL team to win by converting it to a Binary classification problem and using Python libraries while learning about them. If you have any questions, suggestions or feedback, feel free to reach out to me on Email or LinkedIn. You can find this code on my GitHub and you are more than welcome to contribute." }, { "code": null, "e": 8132, "s": 8114, "text": "Happy Predicting!" } ]
ThaiBuddhistDate now(ZoneId) method in Java with Examples - GeeksforGeeks
20 May, 2020 The now() method of java.time.chrono.ThaiBuddhistDate class is used to get the current ThaiBuddhist date according to the ThaiBuddhist calendar system in the specified zone. Syntax: public static ThaiBuddhistDate now(ZoneId zone) Parameter: This method takes the object of zone id on the basis of which ThaiBuddhist date is going to be formed. Return Value: This method returns the current ThaiBuddhist date according to the ThaiBuddhist calendar system from the specified clock. Below are the examples to illustrate the now() method: Example 1: Java // Java program to demonstrate now() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.*; public class GFG { public static void main(String[] argv) { try { // Creating and initializing ZoneId ZoneId id = ZoneId.systemDefault(); // Creating and initializing // ThaiBuddhistDate Object ThaiBuddhistDate hidate = ThaiBuddhistDate.now(id); // Display the result System.out.println( "ThaiBuddhistDate: " + hidate); } catch (DateTimeException e) { System.out.println( "Passed parameter can" + " not form a date"); System.out.println( "Exception thrown: " + e); } }} ThaiBuddhistDate: ThaiBuddhist BE 2563-05-08 Example 2: Java // Java program to demonstrate now() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.*; public class GFG { public static void main(String[] argv) { try { // Creating and initializing ZoneId ZoneId id = ZoneId.of("Z"); // Creating and initializing // ThaiBuddhistDate Object ThaiBuddhistDate hidate = ThaiBuddhistDate.now(id); // Display the result System.out.println( "ThaiBuddhistDate: " + hidate); } catch (DateTimeException e) { System.out.println( "passed parameter can" + " not form a date"); System.out.println( "Exception thrown: " + e); } }} ThaiBuddhistDate: ThaiBuddhist BE 2563-05-08 Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ThaiBuddhistDate.html#now-java.time.ZoneId- Java-Functions Java-Time-Chrono package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23948, "s": 23920, "text": "\n20 May, 2020" }, { "code": null, "e": 24122, "s": 23948, "text": "The now() method of java.time.chrono.ThaiBuddhistDate class is used to get the current ThaiBuddhist date according to the ThaiBuddhist calendar system in the specified zone." }, { "code": null, "e": 24130, "s": 24122, "text": "Syntax:" }, { "code": null, "e": 24193, "s": 24130, "text": "public static ThaiBuddhistDate\n now(ZoneId zone)\n" }, { "code": null, "e": 24307, "s": 24193, "text": "Parameter: This method takes the object of zone id on the basis of which ThaiBuddhist date is going to be formed." }, { "code": null, "e": 24443, "s": 24307, "text": "Return Value: This method returns the current ThaiBuddhist date according to the ThaiBuddhist calendar system from the specified clock." }, { "code": null, "e": 24498, "s": 24443, "text": "Below are the examples to illustrate the now() method:" }, { "code": null, "e": 24509, "s": 24498, "text": "Example 1:" }, { "code": null, "e": 24514, "s": 24509, "text": "Java" }, { "code": "// Java program to demonstrate now() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.*; public class GFG { public static void main(String[] argv) { try { // Creating and initializing ZoneId ZoneId id = ZoneId.systemDefault(); // Creating and initializing // ThaiBuddhistDate Object ThaiBuddhistDate hidate = ThaiBuddhistDate.now(id); // Display the result System.out.println( \"ThaiBuddhistDate: \" + hidate); } catch (DateTimeException e) { System.out.println( \"Passed parameter can\" + \" not form a date\"); System.out.println( \"Exception thrown: \" + e); } }}", "e": 25404, "s": 24514, "text": null }, { "code": null, "e": 25450, "s": 25404, "text": "ThaiBuddhistDate: ThaiBuddhist BE 2563-05-08\n" }, { "code": null, "e": 25461, "s": 25450, "text": "Example 2:" }, { "code": null, "e": 25466, "s": 25461, "text": "Java" }, { "code": "// Java program to demonstrate now() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.*; public class GFG { public static void main(String[] argv) { try { // Creating and initializing ZoneId ZoneId id = ZoneId.of(\"Z\"); // Creating and initializing // ThaiBuddhistDate Object ThaiBuddhistDate hidate = ThaiBuddhistDate.now(id); // Display the result System.out.println( \"ThaiBuddhistDate: \" + hidate); } catch (DateTimeException e) { System.out.println( \"passed parameter can\" + \" not form a date\"); System.out.println( \"Exception thrown: \" + e); } }}", "e": 26350, "s": 25466, "text": null }, { "code": null, "e": 26396, "s": 26350, "text": "ThaiBuddhistDate: ThaiBuddhist BE 2563-05-08\n" }, { "code": null, "e": 26510, "s": 26396, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ThaiBuddhistDate.html#now-java.time.ZoneId-" }, { "code": null, "e": 26525, "s": 26510, "text": "Java-Functions" }, { "code": null, "e": 26550, "s": 26525, "text": "Java-Time-Chrono package" }, { "code": null, "e": 26555, "s": 26550, "text": "Java" }, { "code": null, "e": 26560, "s": 26555, "text": "Java" }, { "code": null, "e": 26658, "s": 26560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26673, "s": 26658, "text": "Stream In Java" }, { "code": null, "e": 26719, "s": 26673, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26740, "s": 26719, "text": "Constructors in Java" }, { "code": null, "e": 26759, "s": 26740, "text": "Exceptions in Java" }, { "code": null, "e": 26776, "s": 26759, "text": "Generics in Java" }, { "code": null, "e": 26806, "s": 26776, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26849, "s": 26806, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26878, "s": 26849, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26894, "s": 26878, "text": "Strings in Java" } ]
numpy.fv() in Python - GeeksforGeeks
29 Nov, 2018 numpy.fv(rate, nper, pmt, pv, when = ‘end’) : This financial function helps user to compute future values. Parameters : rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodnper : [scalar or (M, )array] total compounding periodspmt : [scalar or (M, )array] fixed paymentpv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period. Default is {‘end’, 0} Return : value at the end of nper periods Equation being solved : fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or when rate == 0 fv + pv + pmt * nper == 0 Code 1 : Working # Python program explaining fv() function import numpy as np'''Question : Future value after 10 years of saving $100 now, with an additional monthly savings of $100. Assume the interest rate is 5% (annually) compounded monthly ?''' # rate np pmt pvSolution = np.fv(0.05/12, 10*12, -100, -100) print("Solution : ", Solution) Output : Solution : 15692.9288943 References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fv.html#numpy.fv. Python numpy-Financial Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24866, "s": 24838, "text": "\n29 Nov, 2018" }, { "code": null, "e": 24973, "s": 24866, "text": "numpy.fv(rate, nper, pmt, pv, when = ‘end’) : This financial function helps user to compute future values." }, { "code": null, "e": 24986, "s": 24973, "text": "Parameters :" }, { "code": null, "e": 25322, "s": 24986, "text": "rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodnper : [scalar or (M, )array] total compounding periodspmt : [scalar or (M, )array] fixed paymentpv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period. Default is {‘end’, 0}" }, { "code": null, "e": 25331, "s": 25322, "text": "Return :" }, { "code": null, "e": 25365, "s": 25331, "text": "value at the end of nper periods\n" }, { "code": null, "e": 25389, "s": 25365, "text": "Equation being solved :" }, { "code": null, "e": 25467, "s": 25389, "text": "fv + pv*(1+rate)**nper +\npmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0" }, { "code": null, "e": 25485, "s": 25467, "text": "or when rate == 0" }, { "code": null, "e": 25511, "s": 25485, "text": "fv + pv + pmt * nper == 0" }, { "code": null, "e": 25528, "s": 25511, "text": "Code 1 : Working" }, { "code": "# Python program explaining fv() function import numpy as np'''Question : Future value after 10 years of saving $100 now, with an additional monthly savings of $100. Assume the interest rate is 5% (annually) compounded monthly ?''' # rate np pmt pvSolution = np.fv(0.05/12, 10*12, -100, -100) print(\"Solution : \", Solution)", "e": 25887, "s": 25528, "text": null }, { "code": null, "e": 25896, "s": 25887, "text": "Output :" }, { "code": null, "e": 25923, "s": 25896, "text": "Solution : 15692.9288943\n" }, { "code": null, "e": 26019, "s": 25923, "text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fv.html#numpy.fv." }, { "code": null, "e": 26052, "s": 26019, "text": "Python numpy-Financial Functions" }, { "code": null, "e": 26065, "s": 26052, "text": "Python-numpy" }, { "code": null, "e": 26072, "s": 26065, "text": "Python" }, { "code": null, "e": 26170, "s": 26072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26179, "s": 26170, "text": "Comments" }, { "code": null, "e": 26192, "s": 26179, "text": "Old Comments" }, { "code": null, "e": 26210, "s": 26192, "text": "Python Dictionary" }, { "code": null, "e": 26245, "s": 26210, "text": "Read a file line by line in Python" }, { "code": null, "e": 26267, "s": 26245, "text": "Enumerate() in Python" }, { "code": null, "e": 26299, "s": 26267, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26329, "s": 26299, "text": "Iterate over a list in Python" }, { "code": null, "e": 26371, "s": 26329, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26397, "s": 26371, "text": "Python String | replace()" }, { "code": null, "e": 26440, "s": 26397, "text": "Python program to convert a list to string" }, { "code": null, "e": 26477, "s": 26440, "text": "Create a Pandas DataFrame from Lists" } ]
break, continue and label in Java loop
Following example showcases labels 'first', 'second' before a for statement and use the break/continue controls to jump to that label. See the example below. Live Demo public class Tester { public static void main(String args[]) { first: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ continue first; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } System.out.println(); second: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ break second; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } } } first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1; second is the label for second outermost for loop and continue second cause the loop to break the loop.
[ { "code": null, "e": 1220, "s": 1062, "text": "Following example showcases labels 'first', 'second' before a for statement and use the break/continue controls to jump to that label. See the example below." }, { "code": null, "e": 1230, "s": 1220, "text": "Live Demo" }, { "code": null, "e": 1913, "s": 1230, "text": "public class Tester {\n public static void main(String args[]) {\n first:\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j< 3; j++){\n if(i == 1){\n continue first;\n } \n System.out.print(\" [i = \" + i + \", j = \" + j + \"] \");\n }\n }\n \n System.out.println();\n \n second:\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j< 3; j++){\n if(i == 1){\n break second;\n } \n \n System.out.print(\" [i = \" + i + \", j = \" + j + \"] \");\n }\n }\n }\n}" }, { "code": null, "e": 2029, "s": 1913, "text": "first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1;" }, { "code": null, "e": 2133, "s": 2029, "text": "second is the label for second outermost for loop and continue second cause the loop to break the loop." } ]
ES6 - Collections
ES6 introduces two new data structures: Maps and Sets. Maps − This data structure enables mapping a key to a value. Maps − This data structure enables mapping a key to a value. Sets − Sets are similar to arrays. However, sets do not encourage duplicates. Sets − Sets are similar to arrays. However, sets do not encourage duplicates. The Map object is a simple key/value pair. Keys and values in a map may be primitive or objects. Following is the syntax for the same. new Map([iterable]) The parameter iterable represents any iterable object whose elements comprise of a key/value pair. Maps are ordered, i.e. they traverse the elements in the order of their insertion. This property returns the number of key/value pairs in the Map object. The set() function sets the value for the key in the Map object. The set() function takes two parameters namely, the key and its value. This function returns the Map object. The has() function returns a boolean value indicating whether the specified key is found in the Map object. This function takes a key as parameter. var map = new Map(); map.set('name','Tutorial Point'); map.get('name'); // Tutorial point The above example creates a map object. The map has only one element. The element key is denoted by name. The key is mapped to a value Tutorial point. Note − Maps distinguish between similar values but bear different data types. In other words, an integer key 1 is considered different from a string key “1”. Consider the following example to better understand this concept var map = new Map(); map.set(1,true); console.log(map.has("1")); //false map.set("1",true); console.log(map.has("1")); //true false true The set() method is also chainable. Consider the following example. var roles = new Map(); roles.set('r1', 'User') .set('r2', 'Guest') .set('r3', 'Admin'); console.log(roles.has('r1')) True The above example, defines a map object. The example chains the set() function to define the key/value pair. The get() function is used to retrieve the value corresponding to the specified key. The Map constructor can also be passed an array. Moreover, map also supports the use of spread operator to represent an array. var roles = new Map([ ['r1', 'User'], ['r2', 'Guest'], ['r3', 'Admin'], ]); console.log(roles.get('r2')) The following output is displayed on successful execution of the above code. Guest Note − The get() function returns undefined if the key specified doesn’t exist in the map. The set() replaces the value for the key, if it already exists in the map. Consider the following example. var roles = new Map([ ['r1', 'User'], ['r2', 'Guest'], ['r3', 'Admin'], ]); console.log(`value of key r1 before set(): ${roles.get('r1')}`) roles.set('r1','superUser') console.log(`value of key r1 after set(): ${roles.get('r1')}`) The following output is displayed on successful execution of the above code. value of key r1 before set(): User value of key r1 after set(): superUser Removes all key/value pairs from the Map object. Removes any value associated to the key and returns the value that Map.prototype.has(key) would have previously returned. Map.prototype.has(key) will return false afterwards. Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order. Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the ‘this’ value for each callback . Returns a new Iterator object that contains the keys for each element in the Map object in insertion order. Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order. The following example illustrates traversing a map using the for...of loop. 'use strict' var roles = new Map([ ['r1', 'User'], ['r2', 'Guest'], ['r3', 'Admin'], ]); for(let r of roles.entries()) console.log(`${r[0]}: ${r[1]}`); The following output is displayed on successful execution of the above code. r1: User r2: Guest r3: Admin A weak map is identical to a map with the following exceptions − Its keys must be objects. Its keys must be objects. Keys in a weak map can be Garbage collected. Garbage collection is a process of clearing the memory occupied by unreferenced objects in a program. Keys in a weak map can be Garbage collected. Garbage collection is a process of clearing the memory occupied by unreferenced objects in a program. A weak map cannot be iterated or cleared. A weak map cannot be iterated or cleared. 'use strict' let weakMap = new WeakMap(); let obj = {}; console.log(weakMap.set(obj,"hello")); console.log(weakMap.has(obj));// true The following output is displayed on successful execution of the above code. WeakMap {} true A set is an ES6 data structure. It is similar to an array with an exception that it cannot contain duplicates. In other words, it lets you store unique values. Sets support both primitive values and object references. Just like maps, sets are also ordered, i.e. elements are iterated in their insertion order. A set can be initialized using the following syntax. Returns the number of values in the Set object. Appends a new element with the given value to the Set object. Returns the Set object. Removes all the elements from the Set object. Removes the element associated to the value. Returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is kept similar to the Map object, so that each entry has the same value for its key and value here. Calls callbackFn once for each value present in the Set object, in insertion order. If athisArg parameter is provided to forEach, it will be used as the ‘this’ value for each callback. Returns a boolean asserting whether an element is present with the given value in the Set object or not. Returns a new Iterator object that contains the values for each element in the Set object in insertion order. Weak sets can only contain objects, and the objects they contain may be garbage collected. Like weak maps, weak sets cannot be iterated. 'use strict' let weakSet = new WeakSet(); let obj = {msg:"hello"}; weakSet.add(obj); console.log(weakSet.has(obj)); weakSet.delete(obj); console.log(weakSet.has(obj)); The following output is displayed on successful execution of the above code. true false Iterator is an object which allows to access a collection of objects one at a time. Both set and map have methods which returns an iterator. Iterators are objects with next() method. When next() method is invoked, it returns an object with 'value' and 'done' properties . 'done' is boolean, this will return true after reading all items in the collection var set = new Set(['a','b','c','d','e']); var iterator = set.entries(); console.log(iterator.next()) The following output is displayed on successful execution of the above code. { value: [ 'a', 'a' ], done: false } Since, the set does not store key/value, the value array contains similar key and value. done will be false as there are more elements to be read. var set = new Set(['a','b','c','d','e']); var iterator = set.values(); console.log(iterator.next()); The following output is displayed on successful execution of the above code. { value: 'a', done: false } var set = new Set(['a','b','c','d','e']); var iterator = set.keys(); console.log(iterator.next()); The following output is displayed on successful execution of the above code. { value: 'a', done: false } var map = new Map([[1,'one'],[2,'two'],[3,'three']]); var iterator = map.entries(); console.log(iterator.next()); The following output is displayed on successful execution of the above code. { value: [ 1, 'one' ], done: false } var map = new Map([[1,'one'],[2,'two'],[3,'three']]); var iterator = map.values(); console.log(iterator.next()); The following output is displayed on successful execution of the above code. {value: "one", done: false} var map = new Map([[1,'one'],[2,'two'],[3,'three']]); var iterator = map.keys(); console.log(iterator.next()); The following output is displayed on successful execution of the above code. {value: 1, done: false} 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2332, "s": 2277, "text": "ES6 introduces two new data structures: Maps and Sets." }, { "code": null, "e": 2393, "s": 2332, "text": "Maps − This data structure enables mapping a key to a value." }, { "code": null, "e": 2454, "s": 2393, "text": "Maps − This data structure enables mapping a key to a value." }, { "code": null, "e": 2532, "s": 2454, "text": "Sets − Sets are similar to arrays. However, sets do not encourage duplicates." }, { "code": null, "e": 2610, "s": 2532, "text": "Sets − Sets are similar to arrays. However, sets do not encourage duplicates." }, { "code": null, "e": 2707, "s": 2610, "text": "The Map object is a simple key/value pair. Keys and values in a map may be primitive or objects." }, { "code": null, "e": 2745, "s": 2707, "text": "Following is the syntax for the same." }, { "code": null, "e": 2767, "s": 2745, "text": "new Map([iterable]) \n" }, { "code": null, "e": 2949, "s": 2767, "text": "The parameter iterable represents any iterable object whose elements comprise of a key/value pair. Maps are ordered, i.e. they traverse the elements in the order of their insertion." }, { "code": null, "e": 3020, "s": 2949, "text": "This property returns the number of key/value pairs in the Map object." }, { "code": null, "e": 3195, "s": 3020, "text": "The set() function sets the value for the key in the Map object. The set() function takes two parameters namely, the key and its value. This function returns the Map object." }, { "code": null, "e": 3343, "s": 3195, "text": "The has() function returns a boolean value indicating whether the specified key is found in the Map object. This function takes a key as parameter." }, { "code": null, "e": 3436, "s": 3343, "text": "var map = new Map(); \nmap.set('name','Tutorial Point'); \nmap.get('name'); // Tutorial point\n" }, { "code": null, "e": 3587, "s": 3436, "text": "The above example creates a map object. The map has only one element. The element key is denoted by name. The key is mapped to a value Tutorial point." }, { "code": null, "e": 3810, "s": 3587, "text": "Note − Maps distinguish between similar values but bear different data types. In other words, an integer key 1 is considered different from a string key “1”. Consider the following example to better understand this concept" }, { "code": null, "e": 3940, "s": 3810, "text": "var map = new Map(); \nmap.set(1,true); \nconsole.log(map.has(\"1\")); //false \nmap.set(\"1\",true); \nconsole.log(map.has(\"1\")); //true" }, { "code": null, "e": 3954, "s": 3940, "text": "false \ntrue \n" }, { "code": null, "e": 4022, "s": 3954, "text": "The set() method is also chainable. Consider the following example." }, { "code": null, "e": 4143, "s": 4022, "text": "var roles = new Map(); \nroles.set('r1', 'User') \n.set('r2', 'Guest') \n.set('r3', 'Admin'); \nconsole.log(roles.has('r1'))" }, { "code": null, "e": 4150, "s": 4143, "text": "True \n" }, { "code": null, "e": 4259, "s": 4150, "text": "The above example, defines a map object. The example chains the set() function to define the key/value pair." }, { "code": null, "e": 4345, "s": 4259, "text": "The get() function is used to retrieve the value corresponding to the specified key." }, { "code": null, "e": 4472, "s": 4345, "text": "The Map constructor can also be passed an array. Moreover, map also supports the use of spread operator to represent an array." }, { "code": null, "e": 4592, "s": 4472, "text": "var roles = new Map([ \n ['r1', 'User'], \n ['r2', 'Guest'], \n ['r3', 'Admin'], \n]); \nconsole.log(roles.get('r2'))" }, { "code": null, "e": 4669, "s": 4592, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 4676, "s": 4669, "text": "Guest\n" }, { "code": null, "e": 4767, "s": 4676, "text": "Note − The get() function returns undefined if the key specified doesn’t exist in the map." }, { "code": null, "e": 4874, "s": 4767, "text": "The set() replaces the value for the key, if it already exists in the map. Consider the following example." }, { "code": null, "e": 5122, "s": 4874, "text": "var roles = new Map([ \n ['r1', 'User'], \n ['r2', 'Guest'], \n ['r3', 'Admin'], \n]); \nconsole.log(`value of key r1 before set(): ${roles.get('r1')}`) \nroles.set('r1','superUser') \nconsole.log(`value of key r1 after set(): ${roles.get('r1')}`)" }, { "code": null, "e": 5199, "s": 5122, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 5275, "s": 5199, "text": "value of key r1 before set(): User \nvalue of key r1 after set(): superUser\n" }, { "code": null, "e": 5324, "s": 5275, "text": "Removes all key/value pairs from the Map object." }, { "code": null, "e": 5446, "s": 5324, "text": "Removes any value associated to the key and returns the value that Map.prototype.has(key) would have previously returned." }, { "code": null, "e": 5499, "s": 5446, "text": "Map.prototype.has(key) will return false afterwards." }, { "code": null, "e": 5623, "s": 5499, "text": "Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order." }, { "code": null, "e": 5819, "s": 5623, "text": "Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the ‘this’ value for each callback ." }, { "code": null, "e": 5927, "s": 5819, "text": "Returns a new Iterator object that contains the keys for each element in the Map object in insertion order." }, { "code": null, "e": 6051, "s": 5927, "text": "Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order." }, { "code": null, "e": 6127, "s": 6051, "text": "The following example illustrates traversing a map using the for...of loop." }, { "code": null, "e": 6294, "s": 6127, "text": "'use strict' \nvar roles = new Map([ \n ['r1', 'User'], \n ['r2', 'Guest'], \n ['r3', 'Admin'], \n]);\nfor(let r of roles.entries()) \nconsole.log(`${r[0]}: ${r[1]}`);" }, { "code": null, "e": 6371, "s": 6294, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 6403, "s": 6371, "text": "r1: User \nr2: Guest \nr3: Admin\n" }, { "code": null, "e": 6468, "s": 6403, "text": "A weak map is identical to a map with the following exceptions −" }, { "code": null, "e": 6494, "s": 6468, "text": "Its keys must be objects." }, { "code": null, "e": 6520, "s": 6494, "text": "Its keys must be objects." }, { "code": null, "e": 6667, "s": 6520, "text": "Keys in a weak map can be Garbage collected. Garbage collection is a process of clearing the memory occupied by unreferenced objects in a program." }, { "code": null, "e": 6814, "s": 6667, "text": "Keys in a weak map can be Garbage collected. Garbage collection is a process of clearing the memory occupied by unreferenced objects in a program." }, { "code": null, "e": 6856, "s": 6814, "text": "A weak map cannot be iterated or cleared." }, { "code": null, "e": 6898, "s": 6856, "text": "A weak map cannot be iterated or cleared." }, { "code": null, "e": 7036, "s": 6898, "text": "'use strict' \nlet weakMap = new WeakMap(); \nlet obj = {}; \nconsole.log(weakMap.set(obj,\"hello\")); \nconsole.log(weakMap.has(obj));// true" }, { "code": null, "e": 7113, "s": 7036, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 7131, "s": 7113, "text": "WeakMap {} \ntrue\n" }, { "code": null, "e": 7349, "s": 7131, "text": "A set is an ES6 data structure. It is similar to an array with an exception that it cannot contain duplicates. In other words, it lets you store unique values. Sets support both primitive values and object references." }, { "code": null, "e": 7494, "s": 7349, "text": "Just like maps, sets are also ordered, i.e. elements are iterated in their insertion order. A set can be initialized using the following syntax." }, { "code": null, "e": 7542, "s": 7494, "text": "Returns the number of values in the Set object." }, { "code": null, "e": 7628, "s": 7542, "text": "Appends a new element with the given value to the Set object. Returns the Set object." }, { "code": null, "e": 7674, "s": 7628, "text": "Removes all the elements from the Set object." }, { "code": null, "e": 7719, "s": 7674, "text": "Removes the element associated to the value." }, { "code": null, "e": 7952, "s": 7719, "text": "Returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is kept similar to the Map object, so that each entry has the same value for its key and value here." }, { "code": null, "e": 8137, "s": 7952, "text": "Calls callbackFn once for each value present in the Set object, in insertion order. If athisArg parameter is provided to forEach, it will be used as the ‘this’ value for each callback." }, { "code": null, "e": 8242, "s": 8137, "text": "Returns a boolean asserting whether an element is present with the given value in the Set object or not." }, { "code": null, "e": 8352, "s": 8242, "text": "Returns a new Iterator object that contains the values for each element in the Set object in insertion order." }, { "code": null, "e": 8489, "s": 8352, "text": "Weak sets can only contain objects, and the objects they contain may be garbage collected. Like weak maps, weak sets cannot be iterated." }, { "code": null, "e": 8682, "s": 8489, "text": "'use strict' \n let weakSet = new WeakSet(); \n let obj = {msg:\"hello\"}; \n weakSet.add(obj); \n console.log(weakSet.has(obj)); \n weakSet.delete(obj); \n console.log(weakSet.has(obj));" }, { "code": null, "e": 8759, "s": 8682, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 8772, "s": 8759, "text": "true \nfalse\n" }, { "code": null, "e": 8913, "s": 8772, "text": "Iterator is an object which allows to access a collection of objects one at a time. Both set and map have methods which returns an iterator." }, { "code": null, "e": 9127, "s": 8913, "text": "Iterators are objects with next() method. When next() method is invoked, it returns an object with 'value' and 'done' properties . 'done' is boolean, this will return true after reading all items in the collection" }, { "code": null, "e": 9232, "s": 9127, "text": "var set = new Set(['a','b','c','d','e']); \nvar iterator = set.entries(); \nconsole.log(iterator.next())" }, { "code": null, "e": 9309, "s": 9232, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 9348, "s": 9309, "text": "{ value: [ 'a', 'a' ], done: false } \n" }, { "code": null, "e": 9495, "s": 9348, "text": "Since, the set does not store key/value, the value array contains similar key and value. done will be false as there are more elements to be read." }, { "code": null, "e": 9600, "s": 9495, "text": "var set = new Set(['a','b','c','d','e']); \nvar iterator = set.values(); \nconsole.log(iterator.next());" }, { "code": null, "e": 9677, "s": 9600, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 9708, "s": 9677, "text": "{ value: 'a', done: false } \n" }, { "code": null, "e": 9812, "s": 9708, "text": "var set = new Set(['a','b','c','d','e']); \nvar iterator = set.keys(); \nconsole.log(iterator.next()); " }, { "code": null, "e": 9889, "s": 9812, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 9920, "s": 9889, "text": "{ value: 'a', done: false } \n" }, { "code": null, "e": 10037, "s": 9920, "text": "var map = new Map([[1,'one'],[2,'two'],[3,'three']]); \nvar iterator = map.entries(); \nconsole.log(iterator.next()); " }, { "code": null, "e": 10114, "s": 10037, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 10154, "s": 10114, "text": "{ value: [ 1, 'one' ], done: false } \n" }, { "code": null, "e": 10271, "s": 10154, "text": "var map = new Map([[1,'one'],[2,'two'],[3,'three']]); \nvar iterator = map.values(); \nconsole.log(iterator.next()); " }, { "code": null, "e": 10348, "s": 10271, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 10378, "s": 10348, "text": "{value: \"one\", done: false} \n" }, { "code": null, "e": 10493, "s": 10378, "text": "var map = new Map([[1,'one'],[2,'two'],[3,'three']]); \nvar iterator = map.keys(); \nconsole.log(iterator.next()); " }, { "code": null, "e": 10570, "s": 10493, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 10596, "s": 10570, "text": "{value: 1, done: false} \n" }, { "code": null, "e": 10631, "s": 10596, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10645, "s": 10631, "text": " Sharad Kumar" }, { "code": null, "e": 10678, "s": 10645, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 10696, "s": 10678, "text": " Richa Maheshwari" }, { "code": null, "e": 10729, "s": 10696, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 10743, "s": 10729, "text": " Anadi Sharma" }, { "code": null, "e": 10778, "s": 10743, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 10795, "s": 10778, "text": " Gowthami Swarna" }, { "code": null, "e": 10828, "s": 10795, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 10844, "s": 10828, "text": " Deepti Trivedi" }, { "code": null, "e": 10879, "s": 10844, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10887, "s": 10879, "text": " Shweta" }, { "code": null, "e": 10894, "s": 10887, "text": " Print" }, { "code": null, "e": 10905, "s": 10894, "text": " Add Notes" } ]
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks
14 Feb, 2018 Consider the following set of processes that need to be scheduled on a single CPU. All the times are given in milliseconds. Process Name Arrival Time Execution Time A 0 6 B 3 2 c 5 4 D 7 6 E 10 3 Using the shortest remaining time first scheduling algorithm, the average process turnaround time (in msec) is ____________________.(A) 7.2(B) 8(C) 7(D) 7.5Answer: (A)Explanation: Turn around time of a process is total time between submission of the process and its completion. Shortest remaining time (SRT) scheduling algorithm selects the process for execution which has the smallest amount of time remaining until completion. Solution:Let the processes be A, ,C,D and E. These processes will be executed in following order. Gantt chart is as follows: First 3 sec, A will run, then remaining time A=3, B=2,C=4,D=6,E=3 Now B will get chance to run for 2 sec, then remaining time. A=3, B=0,C=4,D=6,E=3Now A will get chance to run for 3 sec, then remaining time. A=0, B=0,C=4,D=6,E=3 By doing this way, you will get above gantt chart. Scheduling table: As we know, turn around time is total time between submission of the process and its completion. i.e turn around time=completion time-arrival time. i.e. TAT=CT-ATTurn around time of A = 8 (8-0)Turn around time of B = 2 (5-3)Turn around time of C = 7 (12-5)Turn around time of D = 14 (21-7)Turn around time of E = 5 (15-10)Average turn around time is (8+2+7+14+5)/5 = 7.2.Answer is 7.2.Reference:https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_CPU_Scheduling.html This solution is contributed by Nitika Bansal Alternate Explanatio: After drawing Gantt Chart Completion Time for processes A, B, C, D and E are 8, 5, 12, 21 and 15 respectively. Turnaround Time = Completion Time - Arrival Time Quiz of this Question GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(Set-1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | Gate IT 2007 | Question 30 GATE | GATE CS 2011 | Question 7
[ { "code": null, "e": 24466, "s": 24438, "text": "\n14 Feb, 2018" }, { "code": null, "e": 24590, "s": 24466, "text": "Consider the following set of processes that need to be scheduled on a single CPU. All the times are given in milliseconds." }, { "code": null, "e": 24861, "s": 24590, "text": "Process Name Arrival Time Execution Time\n A 0 6\n B 3 2\n c 5 4\n D 7 6\n E 10 3" }, { "code": null, "e": 25290, "s": 24861, "text": "Using the shortest remaining time first scheduling algorithm, the average process turnaround time (in msec) is ____________________.(A) 7.2(B) 8(C) 7(D) 7.5Answer: (A)Explanation: Turn around time of a process is total time between submission of the process and its completion. Shortest remaining time (SRT) scheduling algorithm selects the process for execution which has the smallest amount of time remaining until completion." }, { "code": null, "e": 25415, "s": 25290, "text": "Solution:Let the processes be A, ,C,D and E. These processes will be executed in following order. Gantt chart is as follows:" }, { "code": null, "e": 25695, "s": 25415, "text": "First 3 sec, A will run, then remaining time A=3, B=2,C=4,D=6,E=3 Now B will get chance to run for 2 sec, then remaining time. A=3, B=0,C=4,D=6,E=3Now A will get chance to run for 3 sec, then remaining time. A=0, B=0,C=4,D=6,E=3 By doing this way, you will get above gantt chart." }, { "code": null, "e": 25713, "s": 25695, "text": "Scheduling table:" }, { "code": null, "e": 26189, "s": 25713, "text": "As we know, turn around time is total time between submission of the process and its completion. i.e turn around time=completion time-arrival time. i.e. TAT=CT-ATTurn around time of A = 8 (8-0)Turn around time of B = 2 (5-3)Turn around time of C = 7 (12-5)Turn around time of D = 14 (21-7)Turn around time of E = 5 (15-10)Average turn around time is (8+2+7+14+5)/5 = 7.2.Answer is 7.2.Reference:https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_CPU_Scheduling.html" }, { "code": null, "e": 26235, "s": 26189, "text": "This solution is contributed by Nitika Bansal" }, { "code": null, "e": 26257, "s": 26235, "text": "Alternate Explanatio:" }, { "code": null, "e": 26420, "s": 26257, "text": "After drawing Gantt Chart\n\nCompletion Time for processes A, B, C, D \nand E are 8, 5, 12, 21 and 15 respectively.\n\nTurnaround Time = Completion Time - Arrival Time" }, { "code": null, "e": 26442, "s": 26420, "text": "Quiz of this Question" }, { "code": null, "e": 26463, "s": 26442, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 26489, "s": 26463, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 26494, "s": 26489, "text": "GATE" }, { "code": null, "e": 26592, "s": 26494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26626, "s": 26592, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26668, "s": 26626, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26702, "s": 26668, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26736, "s": 26702, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26769, "s": 26736, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26803, "s": 26769, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26845, "s": 26803, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" }, { "code": null, "e": 26887, "s": 26845, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 26921, "s": 26887, "text": "GATE | Gate IT 2007 | Question 30" } ]
How to grant replication privilege to a database in MySQL?
To grant replication privilege, use GRANT REPLICATION SLAVE ON. First list all the user names along with host from MySQL.user table − mysql> select user,host from mysql.user; This will produce the following output − +------------------+-----------+ | user | host | +------------------+-----------+ | Bob | % | | Charlie | % | | Robert | % | | User2 | % | | mysql.infoschema | % | | mysql.session | % | | mysql.sys | % | | root | % | | @UserName@ | localhost | | Adam | localhost | | Adam Smith | localhost | | Chris | localhost | | David | localhost | | James | localhost | | John | localhost | | John Doe | localhost | | Mike | localhost | | User1 | localhost | | am | localhost | | hbstudent | localhost | | mysql.infoschema | localhost | | mysql.session | localhost | +------------------+-----------+ 22 rows in set (0.00 sec) Let us implement the above syntax to grant replication privilege to a database in MySQL − mysql> GRANT REPLICATION SLAVE ON *.* TO 'Mike'@'localhost'; Query OK, 0 rows affected (0.20 sec) Let us check the grant is successful or not − mysql> SHOW GRANTS FOR 'Mike'@'localhost'; This will produce the following output − +------------------------------------------------------+ | Grants for Mike@localhost | +------------------------------------------------------+ | GRANT REPLICATION SLAVE ON *.* TO `Mike`@`localhost` | +------------------------------------------------------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1126, "s": 1062, "text": "To grant replication privilege, use GRANT REPLICATION SLAVE ON." }, { "code": null, "e": 1196, "s": 1126, "text": "First list all the user names along with host from MySQL.user table −" }, { "code": null, "e": 1237, "s": 1196, "text": "mysql> select user,host from mysql.user;" }, { "code": null, "e": 1278, "s": 1237, "text": "This will produce the following output −" }, { "code": null, "e": 2162, "s": 1278, "text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Bob | % |\n| Charlie | % |\n| Robert | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| @UserName@ | localhost |\n| Adam | localhost |\n| Adam Smith | localhost |\n| Chris | localhost |\n| David | localhost |\n| James | localhost |\n| John | localhost |\n| John Doe | localhost |\n| Mike | localhost |\n| User1 | localhost |\n| am | localhost |\n| hbstudent | localhost |\n| mysql.infoschema | localhost |\n| mysql.session | localhost |\n+------------------+-----------+\n22 rows in set (0.00 sec)" }, { "code": null, "e": 2252, "s": 2162, "text": "Let us implement the above syntax to grant replication privilege to a database in MySQL −" }, { "code": null, "e": 2350, "s": 2252, "text": "mysql> GRANT REPLICATION SLAVE ON *.* TO 'Mike'@'localhost';\nQuery OK, 0 rows affected (0.20 sec)" }, { "code": null, "e": 2396, "s": 2350, "text": "Let us check the grant is successful or not −" }, { "code": null, "e": 2439, "s": 2396, "text": "mysql> SHOW GRANTS FOR 'Mike'@'localhost';" }, { "code": null, "e": 2480, "s": 2439, "text": "This will produce the following output −" }, { "code": null, "e": 2789, "s": 2480, "text": "+------------------------------------------------------+\n| Grants for Mike@localhost |\n+------------------------------------------------------+\n| GRANT REPLICATION SLAVE ON *.* TO `Mike`@`localhost` |\n+------------------------------------------------------+\n1 row in set (0.04 sec)" } ]
Find the Rotation Count in Rotated Sorted array - GeeksforGeeks
30 Mar, 2022 Consider an array arr of distinct numbers sorted in increasing order. Given that this array has been rotated (clockwise) k number of times. Given such an array, find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Output: 2Explanation: Initial array must be {2, 3, 6, 12, 15, 18}. We get the given array after rotating the initial array twice. Input: arr[] = {7, 9, 11, 12, 5}Output: 4 Input: arr[] = {7, 9, 11, 12, 15};Output: 0 Method 1 (Using linear search)If we take closer look at examples, we can notice that the number of rotations is equal to index of minimum element. A simple linear solution is to find minimum element and returns its index. Below is C++ implementation of the idea. C++ Java Python3 C# PHP Javascript // C++ program to find number of rotations// in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedint countRotations(int arr[], int n){ // We basically find index of minimum // element int min = arr[0], min_index; for (int i=0; i<n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index;} // Driver codeint main(){ int arr[] = {15, 18, 2, 3, 6, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << countRotations(arr, n); return 0;} // Java program to find number of// rotations in a sorted and rotated// array.import java.util.*;import java.lang.*;import java.io.*; class LinearSearch{ // Returns count of rotations for an // array which is first sorted in // ascending order, then rotated static int countRotations(int arr[], int n) { // We basically find index of minimum // element int min = arr[0], min_index = -1; for (int i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index; } // Driver program to test above functions public static void main (String[] args) { int arr[] = {15, 18, 2, 3, 6, 12}; int n = arr.length; System.out.println(countRotations(arr, n)); }}// This code is contributed by Chhavi # Python3 program to find number# of rotations in a sorted and# rotated array. # Returns count of rotations for# an array which is first sorted# in ascending order, then rotateddef countRotations(arr, n): # We basically find index # of minimum element min = arr[0] for i in range(0, n): if (min > arr[i]): min = arr[i] min_index = i return min_index; # Driver codearr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr, n)) # This code is contributed by Smitha Dinesh Semwal // c# program to find number of// rotations in a sorted and rotated// array.using System; class LinearSearch{ // Returns count of rotations for an // array which is first sorted in // ascending order, then rotated static int countRotations(int []arr, int n) { // We basically find index of minimum // element int min = arr[0], min_index = -1; for (int i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index; } // Driver program to test above functions public static void Main () { int []arr = {15, 18, 2, 3, 6, 12}; int n = arr.Length; Console.WriteLine(countRotations(arr, n)); }}// This code is contributed by vt_m. <?php// PHP program to find number// of rotations in a sorted// and rotated array. // Returns count of rotations// for an array which is first// sorted in ascending order,// then rotatedfunction countRotations($arr, $n){ // We basically find index // of minimum element $min = $arr[0]; $min_index; for ($i = 0; $i < $n; $i++) { if ($min > $arr[$i]) { $min = $arr[$i]; $min_index = $i; } } return $min_index;} // Driver code$arr = array(15, 18, 2, 3, 6, 12);$n = sizeof($arr);echo countRotations($arr, $n); // This code is contributed// by ajit?> <script> // Javascript program to find number of rotations// in a sorted and rotated array. // Returns count of rotations for an array which// is first sorted in ascending order, then rotated function countRotations(arr, n) { // We basically find index of minimum // element let min = arr[0], min_index = -1; for (let i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index; } // Driver Code let arr = [15, 18, 2, 3, 6, 12]; let n = arr.length; document.write(countRotations(arr, n)); </script> 2 Time Complexity : O(n) Auxiliary Space : O(1) Method 2 (Efficient Using Binary Search) Here also we find the index of minimum element, but using Binary Search. The idea is based on the below facts : The minimum element is the only element whose previous is greater than it. If there is no previous element, then there is no rotation (first element is minimum). We check this condition for middle element by comparing it with (mid-1)’th and (mid+1)’th elements. If the minimum element is not at the middle (neither mid nor mid + 1), then minimum element lies in either left half or right half. If middle element is smaller than last element, then the minimum element lies in left halfElse minimum element lies in right half. If middle element is smaller than last element, then the minimum element lies in left halfElse minimum element lies in right half. If middle element is smaller than last element, then the minimum element lies in left half Else minimum element lies in right half. Below is the implementation taken from here. C++ Java Python3 C# PHP Javascript // Binary Search based C++ program to find number// of rotations in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedint countRotations(int arr[], int low, int high){ // This condition is needed to handle the case // when the array is not rotated at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. // Consider the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid+1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left half or // right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid-1); return countRotations(arr, mid+1, high);} // Driver codeint main(){ int arr[] = {15, 18, 2, 3, 6, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << countRotations(arr, 0, n-1); return 0;} // Java program to find number of// rotations in a sorted and rotated// array.import java.util.*;import java.lang.*;import java.io.*; class BinarySearch{ // Returns count of rotations for an array // which is first sorted in ascending order, // then rotated static int countRotations(int arr[], int low, int high) { // This condition is needed to handle // the case when array is not rotated // at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid // /*(low + high)/2;*/ int mid = low + (high - low)/2; // Check if element (mid+1) is minimum // element. Consider the cases like // {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid + 1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left // half or right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid - 1); return countRotations(arr, mid + 1, high); } // Driver program to test above functions public static void main (String[] args) { int arr[] = {15, 18, 2, 3, 6, 12}; int n = arr.length; System.out.println(countRotations(arr, 0, n-1)); }}// This code is contributed by Chhavi # Binary Search based Python3# program to find number of# rotations in a sorted and# rotated array. # Returns count of rotations for# an array which is first sorted# in ascending order, then rotated def countRotations(arr): n = len(arr) start = 0 end = n-1 # Finding the index of minimum of the array # index of min would be equal to number to rotation while start<=end: mid = start+(end-start)//2 # Calculating the previous(prev) # and next(nex) index of mid prev = (mid-1+n)%n nex = (mid+1)%n # Checking if mid is minimum if arr[mid]<arr[prev]\ and arr[mid]<=arr[nex]: return mid # if not selecting the unsorted part of array elif arr[mid]<arr[start]: end = mid-1 elif arr[mid]>arr[end]: start = mid+1 else: return 0 # Driver codearr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr)) # This code is contributed by Smitha Dinesh Semwal // C# program to find number of// rotations in a sorted and rotated// array.using System; class BinarySearch{ // Returns count of rotations for an array // which is first sorted in ascending order, // then rotated static int countRotations(int []arr, int low, int high) { // This condition is needed to handle // the case when array is not rotated // at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid // /*(low + high)/2;*/ int mid = low + (high - low)/2; // Check if element (mid+1) is minimum // element. Consider the cases like // {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid + 1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left // half or right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid - 1); return countRotations(arr, mid + 1, high); } // Driver program to test above functions public static void Main () { int []arr = {15, 18, 2, 3, 6, 12}; int n = arr.Length; Console.WriteLine(countRotations(arr, 0, n-1)); }}// This code is contributed by vt_m. <?php// Binary Search based PHP// program to find number// of rotations in a sorted// and rotated array. // Returns count of rotations// for an array which is// first sorted in ascending// order, then rotatedfunction countRotations($arr, $low, $high){ // This condition is needed // to handle the case when // array is not rotated at all if ($high < $low) return 0; // If there is only // one element left if ($high == $low) return $low; // Find mid $mid = $low + ($high - $low) / 2; // Check if element (mid+1) // is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if ($mid < $high && $arr[$mid + 1] < $arr[$mid]) return (int)($mid + 1); // Check if mid itself // is minimum element if ($mid > $low && $arr[$mid] < $arr[$mid - 1]) return (int)($mid); // Decide whether we need // to go to left half or // right half if ($arr[$high] > $arr[$mid]) return countRotations($arr, $low, $mid - 1); return countRotations($arr, $mid + 1, $high);} // Driver code$arr = array(15, 18, 2, 3, 6, 12);$n = sizeof($arr);echo countRotations($arr, 0, $n - 1); // This code is contributed bu ajit?> <script>// Binary Search based C++ program to find number// of rotations in a sorted and rotated array. // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedfunction countRotations(arr, low, high){ // This condition is needed to handle the case // when the array is not rotated at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid let mid = Math.floor(low + (high - low)/2); /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. // Consider the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid+1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left half or // right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid-1); return countRotations(arr, mid+1, high);} // Driver code let arr = [15, 18, 2, 3, 6, 12]; let n = arr.length; document.write(countRotations(arr, 0, n-1)); // This code is contributed by Surbhi Tyagi.</script> 2 Time Complexity : O(Log n) Auxiliary Space : O(Log n) Method 3: Iterative Code (Binary Search) C++ Python3 Javascript #include <bits/stdc++.h>using namespace std; // Returns count of rotations// for an array which is first sorted// in ascending order, then rotated // Observation: We have to return// index of the smallest elementint countRotations(int arr[], int n){ int low = 0, high = n - 1; while (low <= high) { // if first element is mid or // last element is mid // then simply use modulo so it // never goes out of bound. int mid = low + (high - low) / 2; int prev = (mid - 1 + n) % n; int next = (mid + 1) % n; if (arr[mid] <= arr[prev] && arr[mid] <= arr[next]) return mid; else if (arr[mid] <= arr[high]) high = mid - 1; else if (arr[mid] >= arr[low]) low = mid + 1; } return 0;} // Driver codeint main(){ int arr[] = { 15, 18, 2, 3, 6, 12 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countRotations(arr, n); return 0;} # Returns count of rotations for an array which# is first sorted in ascending order, then rotated # Observation: We have to return index of the smallest elementdef countRotations(arr, n): low = 0 high = n - 1 while(low<=high): # if first element is mid or # last element is mid # then simply use modulo # so it never goes out of bound. mid = low + ((high - low) // 2) prev = (mid - 1 + n) % n next = (mid + 1) % n if(arr[mid] <= arr[prev] \ and arr[mid] <= arr[next]): return mid elif (arr[mid] <= arr[high]): high = mid - 1 elif (arr[mid] >= arr[low]): low = mid + 1 return 0 # Driver code arr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr, n)) # This code is contributed by shinjanpatra. <script> // Returns count of rotations for an array which// is first sorted in ascending order, then rotated //Observation: We have to return index of the smallest elementfunction countRotations(arr, n){ let low =0 , high = n-1; while(low<=high){ let mid = low + Math.floor((high-low)/2) ; let prev = (mid-1 + n) %n , next = (mid+1)%n;//if first element is mid or //last element is mid then simply use modulo so it never goes out of bound. if(arr[mid]<=arr[prev] && arr[mid]<=arr[next]) return mid; else if (arr[mid]<=arr[high]) high = mid-1 ; else if (arr[mid]>=arr[low]) low=mid+1; } return 0;} // Driver code let arr = [15, 18, 2, 3, 6, 12];let n = arr.length;document.write(countRotations(arr, n)); // This code is contributed by shinjanpatra.</script> 2 Time Complexity : O(Log n)Auxiliary Space : O(1) YouTubeGeeksforGeeks501K subscribersFind the Rotation Count in Rotated Sorted array | 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 / 3:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qHGpfJPQ0xY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Rakesh Kumar. 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. komal27 jit_t _je_raj3sh code_hunt surbhityagi15 dishamangla9255 simmytarika5 jaiswalshruti1102 kavitarawat1 shinjanpatra RishabhPrabhu ABCO Amazon Binary Search rotation Arrays Divide and Conquer Amazon ABCO Arrays Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Merge Sort QuickSort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 41274, "s": 41246, "text": "\n30 Mar, 2022" }, { "code": null, "e": 41456, "s": 41274, "text": "Consider an array arr of distinct numbers sorted in increasing order. Given that this array has been rotated (clockwise) k number of times. Given such an array, find the value of k." }, { "code": null, "e": 41468, "s": 41456, "text": "Examples: " }, { "code": null, "e": 41634, "s": 41468, "text": "Input: arr[] = {15, 18, 2, 3, 6, 12}Output: 2Explanation: Initial array must be {2, 3, 6, 12, 15, 18}. We get the given array after rotating the initial array twice." }, { "code": null, "e": 41676, "s": 41634, "text": "Input: arr[] = {7, 9, 11, 12, 5}Output: 4" }, { "code": null, "e": 41720, "s": 41676, "text": "Input: arr[] = {7, 9, 11, 12, 15};Output: 0" }, { "code": null, "e": 41985, "s": 41720, "text": "Method 1 (Using linear search)If we take closer look at examples, we can notice that the number of rotations is equal to index of minimum element. A simple linear solution is to find minimum element and returns its index. Below is C++ implementation of the idea. " }, { "code": null, "e": 41989, "s": 41985, "text": "C++" }, { "code": null, "e": 41994, "s": 41989, "text": "Java" }, { "code": null, "e": 42002, "s": 41994, "text": "Python3" }, { "code": null, "e": 42005, "s": 42002, "text": "C#" }, { "code": null, "e": 42009, "s": 42005, "text": "PHP" }, { "code": null, "e": 42020, "s": 42009, "text": "Javascript" }, { "code": "// C++ program to find number of rotations// in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedint countRotations(int arr[], int n){ // We basically find index of minimum // element int min = arr[0], min_index; for (int i=0; i<n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index;} // Driver codeint main(){ int arr[] = {15, 18, 2, 3, 6, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << countRotations(arr, n); return 0;}", "e": 42668, "s": 42020, "text": null }, { "code": "// Java program to find number of// rotations in a sorted and rotated// array.import java.util.*;import java.lang.*;import java.io.*; class LinearSearch{ // Returns count of rotations for an // array which is first sorted in // ascending order, then rotated static int countRotations(int arr[], int n) { // We basically find index of minimum // element int min = arr[0], min_index = -1; for (int i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index; } // Driver program to test above functions public static void main (String[] args) { int arr[] = {15, 18, 2, 3, 6, 12}; int n = arr.length; System.out.println(countRotations(arr, n)); }}// This code is contributed by Chhavi", "e": 43550, "s": 42668, "text": null }, { "code": "# Python3 program to find number# of rotations in a sorted and# rotated array. # Returns count of rotations for# an array which is first sorted# in ascending order, then rotateddef countRotations(arr, n): # We basically find index # of minimum element min = arr[0] for i in range(0, n): if (min > arr[i]): min = arr[i] min_index = i return min_index; # Driver codearr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr, n)) # This code is contributed by Smitha Dinesh Semwal", "e": 44103, "s": 43550, "text": null }, { "code": "// c# program to find number of// rotations in a sorted and rotated// array.using System; class LinearSearch{ // Returns count of rotations for an // array which is first sorted in // ascending order, then rotated static int countRotations(int []arr, int n) { // We basically find index of minimum // element int min = arr[0], min_index = -1; for (int i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index; } // Driver program to test above functions public static void Main () { int []arr = {15, 18, 2, 3, 6, 12}; int n = arr.Length; Console.WriteLine(countRotations(arr, n)); }}// This code is contributed by vt_m.", "e": 44922, "s": 44103, "text": null }, { "code": "<?php// PHP program to find number// of rotations in a sorted// and rotated array. // Returns count of rotations// for an array which is first// sorted in ascending order,// then rotatedfunction countRotations($arr, $n){ // We basically find index // of minimum element $min = $arr[0]; $min_index; for ($i = 0; $i < $n; $i++) { if ($min > $arr[$i]) { $min = $arr[$i]; $min_index = $i; } } return $min_index;} // Driver code$arr = array(15, 18, 2, 3, 6, 12);$n = sizeof($arr);echo countRotations($arr, $n); // This code is contributed// by ajit?>", "e": 45547, "s": 44922, "text": null }, { "code": "<script> // Javascript program to find number of rotations// in a sorted and rotated array. // Returns count of rotations for an array which// is first sorted in ascending order, then rotated function countRotations(arr, n) { // We basically find index of minimum // element let min = arr[0], min_index = -1; for (let i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; min_index = i; } } return min_index; } // Driver Code let arr = [15, 18, 2, 3, 6, 12]; let n = arr.length; document.write(countRotations(arr, n)); </script>", "e": 46219, "s": 45547, "text": null }, { "code": null, "e": 46221, "s": 46219, "text": "2" }, { "code": null, "e": 46268, "s": 46221, "text": "Time Complexity : O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 46423, "s": 46268, "text": "Method 2 (Efficient Using Binary Search) Here also we find the index of minimum element, but using Binary Search. The idea is based on the below facts : " }, { "code": null, "e": 46685, "s": 46423, "text": "The minimum element is the only element whose previous is greater than it. If there is no previous element, then there is no rotation (first element is minimum). We check this condition for middle element by comparing it with (mid-1)’th and (mid+1)’th elements." }, { "code": null, "e": 46948, "s": 46685, "text": "If the minimum element is not at the middle (neither mid nor mid + 1), then minimum element lies in either left half or right half. If middle element is smaller than last element, then the minimum element lies in left halfElse minimum element lies in right half." }, { "code": null, "e": 47079, "s": 46948, "text": "If middle element is smaller than last element, then the minimum element lies in left halfElse minimum element lies in right half." }, { "code": null, "e": 47170, "s": 47079, "text": "If middle element is smaller than last element, then the minimum element lies in left half" }, { "code": null, "e": 47211, "s": 47170, "text": "Else minimum element lies in right half." }, { "code": null, "e": 47258, "s": 47211, "text": "Below is the implementation taken from here. " }, { "code": null, "e": 47262, "s": 47258, "text": "C++" }, { "code": null, "e": 47267, "s": 47262, "text": "Java" }, { "code": null, "e": 47275, "s": 47267, "text": "Python3" }, { "code": null, "e": 47278, "s": 47275, "text": "C#" }, { "code": null, "e": 47282, "s": 47278, "text": "PHP" }, { "code": null, "e": 47293, "s": 47282, "text": "Javascript" }, { "code": "// Binary Search based C++ program to find number// of rotations in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedint countRotations(int arr[], int low, int high){ // This condition is needed to handle the case // when the array is not rotated at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. // Consider the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid+1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left half or // right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid-1); return countRotations(arr, mid+1, high);} // Driver codeint main(){ int arr[] = {15, 18, 2, 3, 6, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << countRotations(arr, 0, n-1); return 0;}", "e": 48481, "s": 47293, "text": null }, { "code": "// Java program to find number of// rotations in a sorted and rotated// array.import java.util.*;import java.lang.*;import java.io.*; class BinarySearch{ // Returns count of rotations for an array // which is first sorted in ascending order, // then rotated static int countRotations(int arr[], int low, int high) { // This condition is needed to handle // the case when array is not rotated // at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid // /*(low + high)/2;*/ int mid = low + (high - low)/2; // Check if element (mid+1) is minimum // element. Consider the cases like // {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid + 1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left // half or right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid - 1); return countRotations(arr, mid + 1, high); } // Driver program to test above functions public static void main (String[] args) { int arr[] = {15, 18, 2, 3, 6, 12}; int n = arr.length; System.out.println(countRotations(arr, 0, n-1)); }}// This code is contributed by Chhavi", "e": 49987, "s": 48481, "text": null }, { "code": "# Binary Search based Python3# program to find number of# rotations in a sorted and# rotated array. # Returns count of rotations for# an array which is first sorted# in ascending order, then rotated def countRotations(arr): n = len(arr) start = 0 end = n-1 # Finding the index of minimum of the array # index of min would be equal to number to rotation while start<=end: mid = start+(end-start)//2 # Calculating the previous(prev) # and next(nex) index of mid prev = (mid-1+n)%n nex = (mid+1)%n # Checking if mid is minimum if arr[mid]<arr[prev]\\ and arr[mid]<=arr[nex]: return mid # if not selecting the unsorted part of array elif arr[mid]<arr[start]: end = mid-1 elif arr[mid]>arr[end]: start = mid+1 else: return 0 # Driver codearr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr)) # This code is contributed by Smitha Dinesh Semwal", "e": 50968, "s": 49987, "text": null }, { "code": "// C# program to find number of// rotations in a sorted and rotated// array.using System; class BinarySearch{ // Returns count of rotations for an array // which is first sorted in ascending order, // then rotated static int countRotations(int []arr, int low, int high) { // This condition is needed to handle // the case when array is not rotated // at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid // /*(low + high)/2;*/ int mid = low + (high - low)/2; // Check if element (mid+1) is minimum // element. Consider the cases like // {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid + 1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left // half or right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid - 1); return countRotations(arr, mid + 1, high); } // Driver program to test above functions public static void Main () { int []arr = {15, 18, 2, 3, 6, 12}; int n = arr.Length; Console.WriteLine(countRotations(arr, 0, n-1)); }}// This code is contributed by vt_m.", "e": 52373, "s": 50968, "text": null }, { "code": "<?php// Binary Search based PHP// program to find number// of rotations in a sorted// and rotated array. // Returns count of rotations// for an array which is// first sorted in ascending// order, then rotatedfunction countRotations($arr, $low, $high){ // This condition is needed // to handle the case when // array is not rotated at all if ($high < $low) return 0; // If there is only // one element left if ($high == $low) return $low; // Find mid $mid = $low + ($high - $low) / 2; // Check if element (mid+1) // is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if ($mid < $high && $arr[$mid + 1] < $arr[$mid]) return (int)($mid + 1); // Check if mid itself // is minimum element if ($mid > $low && $arr[$mid] < $arr[$mid - 1]) return (int)($mid); // Decide whether we need // to go to left half or // right half if ($arr[$high] > $arr[$mid]) return countRotations($arr, $low, $mid - 1); return countRotations($arr, $mid + 1, $high);} // Driver code$arr = array(15, 18, 2, 3, 6, 12);$n = sizeof($arr);echo countRotations($arr, 0, $n - 1); // This code is contributed bu ajit?>", "e": 53688, "s": 52373, "text": null }, { "code": "<script>// Binary Search based C++ program to find number// of rotations in a sorted and rotated array. // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedfunction countRotations(arr, low, high){ // This condition is needed to handle the case // when the array is not rotated at all if (high < low) return 0; // If there is only one element left if (high == low) return low; // Find mid let mid = Math.floor(low + (high - low)/2); /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. // Consider the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return (mid+1); // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return mid; // Decide whether we need to go to left half or // right half if (arr[high] > arr[mid]) return countRotations(arr, low, mid-1); return countRotations(arr, mid+1, high);} // Driver code let arr = [15, 18, 2, 3, 6, 12]; let n = arr.length; document.write(countRotations(arr, 0, n-1)); // This code is contributed by Surbhi Tyagi.</script>", "e": 54857, "s": 53688, "text": null }, { "code": null, "e": 54859, "s": 54857, "text": "2" }, { "code": null, "e": 54914, "s": 54859, "text": "Time Complexity : O(Log n) Auxiliary Space : O(Log n) " }, { "code": null, "e": 54955, "s": 54914, "text": "Method 3: Iterative Code (Binary Search)" }, { "code": null, "e": 54959, "s": 54955, "text": "C++" }, { "code": null, "e": 54967, "s": 54959, "text": "Python3" }, { "code": null, "e": 54978, "s": 54967, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Returns count of rotations// for an array which is first sorted// in ascending order, then rotated // Observation: We have to return// index of the smallest elementint countRotations(int arr[], int n){ int low = 0, high = n - 1; while (low <= high) { // if first element is mid or // last element is mid // then simply use modulo so it // never goes out of bound. int mid = low + (high - low) / 2; int prev = (mid - 1 + n) % n; int next = (mid + 1) % n; if (arr[mid] <= arr[prev] && arr[mid] <= arr[next]) return mid; else if (arr[mid] <= arr[high]) high = mid - 1; else if (arr[mid] >= arr[low]) low = mid + 1; } return 0;} // Driver codeint main(){ int arr[] = { 15, 18, 2, 3, 6, 12 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countRotations(arr, n); return 0;}", "e": 55935, "s": 54978, "text": null }, { "code": "# Returns count of rotations for an array which# is first sorted in ascending order, then rotated # Observation: We have to return index of the smallest elementdef countRotations(arr, n): low = 0 high = n - 1 while(low<=high): # if first element is mid or # last element is mid # then simply use modulo # so it never goes out of bound. mid = low + ((high - low) // 2) prev = (mid - 1 + n) % n next = (mid + 1) % n if(arr[mid] <= arr[prev] \\ and arr[mid] <= arr[next]): return mid elif (arr[mid] <= arr[high]): high = mid - 1 elif (arr[mid] >= arr[low]): low = mid + 1 return 0 # Driver code arr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr, n)) # This code is contributed by shinjanpatra.", "e": 56784, "s": 55935, "text": null }, { "code": "<script> // Returns count of rotations for an array which// is first sorted in ascending order, then rotated //Observation: We have to return index of the smallest elementfunction countRotations(arr, n){ let low =0 , high = n-1; while(low<=high){ let mid = low + Math.floor((high-low)/2) ; let prev = (mid-1 + n) %n , next = (mid+1)%n;//if first element is mid or //last element is mid then simply use modulo so it never goes out of bound. if(arr[mid]<=arr[prev] && arr[mid]<=arr[next]) return mid; else if (arr[mid]<=arr[high]) high = mid-1 ; else if (arr[mid]>=arr[low]) low=mid+1; } return 0;} // Driver code let arr = [15, 18, 2, 3, 6, 12];let n = arr.length;document.write(countRotations(arr, n)); // This code is contributed by shinjanpatra.</script>", "e": 57655, "s": 56784, "text": null }, { "code": null, "e": 57657, "s": 57655, "text": "2" }, { "code": null, "e": 57706, "s": 57657, "text": "Time Complexity : O(Log n)Auxiliary Space : O(1)" }, { "code": null, "e": 58552, "s": 57706, "text": "YouTubeGeeksforGeeks501K subscribersFind the Rotation Count in Rotated Sorted array | 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 / 3:38•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=qHGpfJPQ0xY\" 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": 58973, "s": 58552, "text": "This article is contributed by Rakesh Kumar. 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": 58981, "s": 58973, "text": "komal27" }, { "code": null, "e": 58987, "s": 58981, "text": "jit_t" }, { "code": null, "e": 58998, "s": 58987, "text": "_je_raj3sh" }, { "code": null, "e": 59008, "s": 58998, "text": "code_hunt" }, { "code": null, "e": 59022, "s": 59008, "text": "surbhityagi15" }, { "code": null, "e": 59038, "s": 59022, "text": "dishamangla9255" }, { "code": null, "e": 59051, "s": 59038, "text": "simmytarika5" }, { "code": null, "e": 59069, "s": 59051, "text": "jaiswalshruti1102" }, { "code": null, "e": 59082, "s": 59069, "text": "kavitarawat1" }, { "code": null, "e": 59095, "s": 59082, "text": "shinjanpatra" }, { "code": null, "e": 59109, "s": 59095, "text": "RishabhPrabhu" }, { "code": null, "e": 59114, "s": 59109, "text": "ABCO" }, { "code": null, "e": 59121, "s": 59114, "text": "Amazon" }, { "code": null, "e": 59135, "s": 59121, "text": "Binary Search" }, { "code": null, "e": 59144, "s": 59135, "text": "rotation" }, { "code": null, "e": 59151, "s": 59144, "text": "Arrays" }, { "code": null, "e": 59170, "s": 59151, "text": "Divide and Conquer" }, { "code": null, "e": 59177, "s": 59170, "text": "Amazon" }, { "code": null, "e": 59182, "s": 59177, "text": "ABCO" }, { "code": null, "e": 59189, "s": 59182, "text": "Arrays" }, { "code": null, "e": 59208, "s": 59189, "text": "Divide and Conquer" }, { "code": null, "e": 59222, "s": 59208, "text": "Binary Search" }, { "code": null, "e": 59320, "s": 59222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 59329, "s": 59320, "text": "Comments" }, { "code": null, "e": 59342, "s": 59329, "text": "Old Comments" }, { "code": null, "e": 59357, "s": 59342, "text": "Arrays in Java" }, { "code": null, "e": 59373, "s": 59357, "text": "Arrays in C/C++" }, { "code": null, "e": 59400, "s": 59373, "text": "Program for array rotation" }, { "code": null, "e": 59448, "s": 59400, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 59492, "s": 59448, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 59503, "s": 59492, "text": "Merge Sort" }, { "code": null, "e": 59513, "s": 59503, "text": "QuickSort" }, { "code": null, "e": 59527, "s": 59513, "text": "Binary Search" }, { "code": null, "e": 59554, "s": 59527, "text": "Program for Tower of Hanoi" } ]
Advanced Excel Financial - XNPV Function
The XNPV function returns the net present value for a schedule of cash flows that is not necessarily periodic. To calculate the net present value for a series of cash flows that is periodic, use the NPV function. XNPV (rate, values, dates) A series of cash flows that corresponds to a schedule of payments in dates. See Notes below. A schedule of payment dates that corresponds to the cash flow payments. See Notes below. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. If the first value is a cost or payment, it must be a negative value. If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. All succeeding payments are discounted based on a 365-day year. The first payment date indicates the beginning of the schedule of payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order. All other dates must be later than this date, but they may occur in any order. The series of values must contain at least one positive value and one negative value. The series of values must contain at least one positive value and one negative value. Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900. Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900. Numbers in dates are truncated to integers. Numbers in dates are truncated to integers. If any number in dates is not a valid Excel date, XNPV returns the #VALUE! error value. If any number in dates is not a valid Excel date, XNPV returns the #VALUE! error value. If any number in dates precedes the starting date, XNPV returns the #NUM! error value. If any number in dates precedes the starting date, XNPV returns the #NUM! error value. If values and dates contain a different number of values, XNPV returns the #NUM! error value. If values and dates contain a different number of values, XNPV returns the #NUM! error value. XNPV is calculated as follows − $$XNPV = \sum_{i=1}^{N} \frac{P_i}{\left ( 1 + rate \right )^{\frac{\left ( d_i - d_1 \right )}{365}}}$$ Where, di = the ith, or last, payment date. d1 = the 0th payment date. Pi = the ith, or last, payment. XNPV is calculated as follows − $$XNPV = \sum_{i=1}^{N} \frac{P_i}{\left ( 1 + rate \right )^{\frac{\left ( d_i - d_1 \right )}{365}}}$$ Where, di = the ith, or last, payment date. d1 = the 0th payment date. Pi = the ith, or last, payment. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2067, "s": 1854, "text": "The XNPV function returns the net present value for a schedule of cash flows that is not necessarily periodic. To calculate the net present value for a series of cash flows that is periodic, use the NPV function." }, { "code": null, "e": 2095, "s": 2067, "text": "XNPV (rate, values, dates)\n" }, { "code": null, "e": 2171, "s": 2095, "text": "A series of cash flows that corresponds to a schedule of payments in dates." }, { "code": null, "e": 2188, "s": 2171, "text": "See Notes below." }, { "code": null, "e": 2260, "s": 2188, "text": "A schedule of payment dates that corresponds to the cash flow payments." }, { "code": null, "e": 2277, "s": 2260, "text": "See Notes below." }, { "code": null, "e": 2392, "s": 2277, "text": "The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment." }, { "code": null, "e": 2507, "s": 2392, "text": "The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment." }, { "code": null, "e": 2577, "s": 2507, "text": "If the first value is a cost or payment, it must be a negative value." }, { "code": null, "e": 2647, "s": 2577, "text": "If the first value is a cost or payment, it must be a negative value." }, { "code": null, "e": 2711, "s": 2647, "text": "All succeeding payments are discounted based on a 365-day year." }, { "code": null, "e": 2775, "s": 2711, "text": "All succeeding payments are discounted based on a 365-day year." }, { "code": null, "e": 2851, "s": 2775, "text": "The first payment date indicates the beginning of the schedule of payments." }, { "code": null, "e": 2927, "s": 2851, "text": "The first payment date indicates the beginning of the schedule of payments." }, { "code": null, "e": 3006, "s": 2927, "text": "All other dates must be later than this date, but they may occur in any order." }, { "code": null, "e": 3085, "s": 3006, "text": "All other dates must be later than this date, but they may occur in any order." }, { "code": null, "e": 3171, "s": 3085, "text": "The series of values must contain at least one positive value and one negative value." }, { "code": null, "e": 3257, "s": 3171, "text": "The series of values must contain at least one positive value and one negative value." }, { "code": null, "e": 3492, "s": 3257, "text": "Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900." }, { "code": null, "e": 3727, "s": 3492, "text": "Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900." }, { "code": null, "e": 3771, "s": 3727, "text": "Numbers in dates are truncated to integers." }, { "code": null, "e": 3815, "s": 3771, "text": "Numbers in dates are truncated to integers." }, { "code": null, "e": 3903, "s": 3815, "text": "If any number in dates is not a valid Excel date, XNPV returns the #VALUE! error value." }, { "code": null, "e": 3991, "s": 3903, "text": "If any number in dates is not a valid Excel date, XNPV returns the #VALUE! error value." }, { "code": null, "e": 4078, "s": 3991, "text": "If any number in dates precedes the starting date, XNPV returns the #NUM! error value." }, { "code": null, "e": 4165, "s": 4078, "text": "If any number in dates precedes the starting date, XNPV returns the #NUM! error value." }, { "code": null, "e": 4259, "s": 4165, "text": "If values and dates contain a different number of values, XNPV returns the #NUM! error value." }, { "code": null, "e": 4353, "s": 4259, "text": "If values and dates contain a different number of values, XNPV returns the #NUM! error value." }, { "code": null, "e": 4594, "s": 4353, "text": "XNPV is calculated as follows −\n$$XNPV = \\sum_{i=1}^{N} \\frac{P_i}{\\left ( 1\n+ rate \\right )^{\\frac{\\left ( d_i - d_1 \\right )}{365}}}$$\nWhere,\ndi = the ith, or last, payment date.\nd1 = the 0th payment date.\nPi = the ith, or last, payment.\n" }, { "code": null, "e": 4626, "s": 4594, "text": "XNPV is calculated as follows −" }, { "code": null, "e": 4731, "s": 4626, "text": "$$XNPV = \\sum_{i=1}^{N} \\frac{P_i}{\\left ( 1\n+ rate \\right )^{\\frac{\\left ( d_i - d_1 \\right )}{365}}}$$" }, { "code": null, "e": 4738, "s": 4731, "text": "Where," }, { "code": null, "e": 4775, "s": 4738, "text": "di = the ith, or last, payment date." }, { "code": null, "e": 4802, "s": 4775, "text": "d1 = the 0th payment date." }, { "code": null, "e": 4834, "s": 4802, "text": "Pi = the ith, or last, payment." }, { "code": null, "e": 4881, "s": 4834, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 4917, "s": 4881, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 4931, "s": 4917, "text": " Arun Motoori" }, { "code": null, "e": 4966, "s": 4931, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4981, "s": 4966, "text": " Pavan Lalwani" }, { "code": null, "e": 5017, "s": 4981, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5026, "s": 5017, "text": " Inf Sid" }, { "code": null, "e": 5062, "s": 5026, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5077, "s": 5062, "text": " Yoda Learning" }, { "code": null, "e": 5112, "s": 5077, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5127, "s": 5112, "text": " William Fiset" }, { "code": null, "e": 5162, "s": 5127, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5176, "s": 5162, "text": " Sasha Miller" }, { "code": null, "e": 5183, "s": 5176, "text": " Print" }, { "code": null, "e": 5194, "s": 5183, "text": " Add Notes" } ]
multiset erase() in C++ STL - GeeksforGeeks
06 Jan, 2020 Prerequisite : multiset The multiset::erase() is the STL function in C++ removes the specified element from multiset. There are three versions of this method. These are: Syntax:void erase (iterator position_of_iterator); Parameters: This method accepts following parameters:position_of_iterator: It refers to the position of the specific element to be removed with the help of iterator.Return value: This method returns the iterator following the removed element.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); ms_iterator++; // Passing the iterator for the position // at which the value is to be erased multi_set.erase(ms_iterator); cout << "Modified multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset: 1 3 4 5 6 7 8 9 Syntax:size_type erase (const value_type& contant_value); Parameters: This method accepts following parameters:constant_value: It refers to the specific element to be removed from the multiset with the help of its value. It must be constant. All instances of this value is erased by this method.Return value: This method returns the no. of values that is/are removed.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); // Passing constant value to be erased int num = multi_set.erase(2); cout << "Modified multiset: " << "(" << num << ")" << "removed"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset:(1)removed 1 3 4 5 6 7 8 9 Syntax:void erase (iterator starting_iterator, iterator ending_iterator); Parameters: This method accepts following parameters:starting_iterator: It refers to the starting iterator of the range of values to be removed from the multiset.ending_iterator: It refers to the ending iterator of the range of values to be removed from the multiset.Return value: This method returns the iterator following the last removed element or end iterator.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); ms_iterator++; ms_iterator++; // Passing the iterator range for the positions // at which the values are to be erased auto ir = multi_set.erase(ms_iterator, multi_set.end()); cout << "Modified multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; (ir == multi_set.end()) ? cout << "Return value is: multi_set.end()\n " : cout << "Return value is not multi_set.end()\n"; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset: 1 2 Return value is: multi_set.end(); Syntax:void erase (iterator position_of_iterator); Parameters: This method accepts following parameters:position_of_iterator: It refers to the position of the specific element to be removed with the help of iterator.Return value: This method returns the iterator following the removed element.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); ms_iterator++; // Passing the iterator for the position // at which the value is to be erased multi_set.erase(ms_iterator); cout << "Modified multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset: 1 3 4 5 6 7 8 9 void erase (iterator position_of_iterator); Parameters: This method accepts following parameters: position_of_iterator: It refers to the position of the specific element to be removed with the help of iterator. Return value: This method returns the iterator following the removed element. Below examples illustrate the working of multiset::erase() method: // C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); ms_iterator++; // Passing the iterator for the position // at which the value is to be erased multi_set.erase(ms_iterator); cout << "Modified multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; return 0;} Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset: 1 3 4 5 6 7 8 9 Syntax:size_type erase (const value_type& contant_value); Parameters: This method accepts following parameters:constant_value: It refers to the specific element to be removed from the multiset with the help of its value. It must be constant. All instances of this value is erased by this method.Return value: This method returns the no. of values that is/are removed.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); // Passing constant value to be erased int num = multi_set.erase(2); cout << "Modified multiset: " << "(" << num << ")" << "removed"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset:(1)removed 1 3 4 5 6 7 8 9 size_type erase (const value_type& contant_value); Parameters: This method accepts following parameters: constant_value: It refers to the specific element to be removed from the multiset with the help of its value. It must be constant. All instances of this value is erased by this method. Return value: This method returns the no. of values that is/are removed. Below examples illustrate the working of multiset::erase() method: // C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); // Passing constant value to be erased int num = multi_set.erase(2); cout << "Modified multiset: " << "(" << num << ")" << "removed"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; return 0;} Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset:(1)removed 1 3 4 5 6 7 8 9 Syntax:void erase (iterator starting_iterator, iterator ending_iterator); Parameters: This method accepts following parameters:starting_iterator: It refers to the starting iterator of the range of values to be removed from the multiset.ending_iterator: It refers to the ending iterator of the range of values to be removed from the multiset.Return value: This method returns the iterator following the last removed element or end iterator.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); ms_iterator++; ms_iterator++; // Passing the iterator range for the positions // at which the values are to be erased auto ir = multi_set.erase(ms_iterator, multi_set.end()); cout << "Modified multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; (ir == multi_set.end()) ? cout << "Return value is: multi_set.end()\n " : cout << "Return value is not multi_set.end()\n"; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset: 1 2 Return value is: multi_set.end(); void erase (iterator starting_iterator, iterator ending_iterator); Parameters: This method accepts following parameters: starting_iterator: It refers to the starting iterator of the range of values to be removed from the multiset. ending_iterator: It refers to the ending iterator of the range of values to be removed from the multiset. Return value: This method returns the iterator following the last removed element or end iterator. Below examples illustrate the working of multiset::erase() method: // C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << "Original multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; ms_iterator = multi_set.begin(); ms_iterator++; ms_iterator++; // Passing the iterator range for the positions // at which the values are to be erased auto ir = multi_set.erase(ms_iterator, multi_set.end()); cout << "Modified multiset: "; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\n'; (ir == multi_set.end()) ? cout << "Return value is: multi_set.end()\n " : cout << "Return value is not multi_set.end()\n"; return 0;} Original multiset: 1 2 3 4 5 6 7 8 9 Modified multiset: 1 2 Return value is: multi_set.end(); vaibhavkpatel1 CPP-Functions cpp-multiset STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Operator Overloading in C++ Socket Programming in C/C++ Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort Program to print ASCII Value of a character Sorting a Map by value in C++ STL
[ { "code": null, "e": 24664, "s": 24636, "text": "\n06 Jan, 2020" }, { "code": null, "e": 24688, "s": 24664, "text": "Prerequisite : multiset" }, { "code": null, "e": 24782, "s": 24688, "text": "The multiset::erase() is the STL function in C++ removes the specified element from multiset." }, { "code": null, "e": 24834, "s": 24782, "text": "There are three versions of this method. These are:" }, { "code": null, "e": 29321, "s": 24834, "text": "Syntax:void erase (iterator position_of_iterator);\nParameters: This method accepts following parameters:position_of_iterator: It refers to the position of the specific element to be removed with the help of iterator.Return value: This method returns the iterator following the removed element.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); ms_iterator++; // Passing the iterator for the position // at which the value is to be erased multi_set.erase(ms_iterator); cout << \"Modified multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset: 1 3 4 5 6 7 8 9\nSyntax:size_type erase (const value_type& contant_value);\nParameters: This method accepts following parameters:constant_value: It refers to the specific element to be removed from the multiset with the help of its value. It must be constant. All instances of this value is erased by this method.Return value: This method returns the no. of values that is/are removed.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); // Passing constant value to be erased int num = multi_set.erase(2); cout << \"Modified multiset: \" << \"(\" << num << \")\" << \"removed\"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset:(1)removed 1 3 4 5 6 7 8 9\nSyntax:void erase (iterator starting_iterator, iterator ending_iterator);\nParameters: This method accepts following parameters:starting_iterator: It refers to the starting iterator of the range of values to be removed from the multiset.ending_iterator: It refers to the ending iterator of the range of values to be removed from the multiset.Return value: This method returns the iterator following the last removed element or end iterator.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); ms_iterator++; ms_iterator++; // Passing the iterator range for the positions // at which the values are to be erased auto ir = multi_set.erase(ms_iterator, multi_set.end()); cout << \"Modified multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; (ir == multi_set.end()) ? cout << \"Return value is: multi_set.end()\\n \" : cout << \"Return value is not multi_set.end()\\n\"; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset: 1 2\nReturn value is: multi_set.end();\n" }, { "code": null, "e": 30676, "s": 29321, "text": "Syntax:void erase (iterator position_of_iterator);\nParameters: This method accepts following parameters:position_of_iterator: It refers to the position of the specific element to be removed with the help of iterator.Return value: This method returns the iterator following the removed element.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); ms_iterator++; // Passing the iterator for the position // at which the value is to be erased multi_set.erase(ms_iterator); cout << \"Modified multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset: 1 3 4 5 6 7 8 9\n" }, { "code": null, "e": 30721, "s": 30676, "text": "void erase (iterator position_of_iterator);\n" }, { "code": null, "e": 30775, "s": 30721, "text": "Parameters: This method accepts following parameters:" }, { "code": null, "e": 30888, "s": 30775, "text": "position_of_iterator: It refers to the position of the specific element to be removed with the help of iterator." }, { "code": null, "e": 30966, "s": 30888, "text": "Return value: This method returns the iterator following the removed element." }, { "code": null, "e": 31033, "s": 30966, "text": "Below examples illustrate the working of multiset::erase() method:" }, { "code": "// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); ms_iterator++; // Passing the iterator for the position // at which the value is to be erased multi_set.erase(ms_iterator); cout << \"Modified multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; return 0;}", "e": 31948, "s": 31033, "text": null }, { "code": null, "e": 32023, "s": 31948, "text": "Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset: 1 3 4 5 6 7 8 9\n" }, { "code": null, "e": 33438, "s": 32023, "text": "Syntax:size_type erase (const value_type& contant_value);\nParameters: This method accepts following parameters:constant_value: It refers to the specific element to be removed from the multiset with the help of its value. It must be constant. All instances of this value is erased by this method.Return value: This method returns the no. of values that is/are removed.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); // Passing constant value to be erased int num = multi_set.erase(2); cout << \"Modified multiset: \" << \"(\" << num << \")\" << \"removed\"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset:(1)removed 1 3 4 5 6 7 8 9\n" }, { "code": null, "e": 33490, "s": 33438, "text": "size_type erase (const value_type& contant_value);\n" }, { "code": null, "e": 33544, "s": 33490, "text": "Parameters: This method accepts following parameters:" }, { "code": null, "e": 33729, "s": 33544, "text": "constant_value: It refers to the specific element to be removed from the multiset with the help of its value. It must be constant. All instances of this value is erased by this method." }, { "code": null, "e": 33802, "s": 33729, "text": "Return value: This method returns the no. of values that is/are removed." }, { "code": null, "e": 33869, "s": 33802, "text": "Below examples illustrate the working of multiset::erase() method:" }, { "code": "// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); // Passing constant value to be erased int num = multi_set.erase(2); cout << \"Modified multiset: \" << \"(\" << num << \")\" << \"removed\"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; return 0;}", "e": 34760, "s": 33869, "text": null }, { "code": null, "e": 34845, "s": 34760, "text": "Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset:(1)removed 1 3 4 5 6 7 8 9\n" }, { "code": null, "e": 36564, "s": 34845, "text": "Syntax:void erase (iterator starting_iterator, iterator ending_iterator);\nParameters: This method accepts following parameters:starting_iterator: It refers to the starting iterator of the range of values to be removed from the multiset.ending_iterator: It refers to the ending iterator of the range of values to be removed from the multiset.Return value: This method returns the iterator following the last removed element or end iterator.Below examples illustrate the working of multiset::erase() method:// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); ms_iterator++; ms_iterator++; // Passing the iterator range for the positions // at which the values are to be erased auto ir = multi_set.erase(ms_iterator, multi_set.end()); cout << \"Modified multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; (ir == multi_set.end()) ? cout << \"Return value is: multi_set.end()\\n \" : cout << \"Return value is not multi_set.end()\\n\"; return 0;}Output:Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset: 1 2\nReturn value is: multi_set.end();\n" }, { "code": null, "e": 36632, "s": 36564, "text": "void erase (iterator starting_iterator, iterator ending_iterator);\n" }, { "code": null, "e": 36686, "s": 36632, "text": "Parameters: This method accepts following parameters:" }, { "code": null, "e": 36796, "s": 36686, "text": "starting_iterator: It refers to the starting iterator of the range of values to be removed from the multiset." }, { "code": null, "e": 36902, "s": 36796, "text": "ending_iterator: It refers to the ending iterator of the range of values to be removed from the multiset." }, { "code": null, "e": 37001, "s": 36902, "text": "Return value: This method returns the iterator following the last removed element or end iterator." }, { "code": null, "e": 37068, "s": 37001, "text": "Below examples illustrate the working of multiset::erase() method:" }, { "code": "// C++ program to demonstrate// multiset::erase() method #include <bits/stdc++.h>using namespace std; int main(){ // Initialise the multiset multiset<int> multi_set; multiset<int>::iterator ms_iterator; // Add values to the multiset for (int i = 1; i < 10; i++) { multi_set.insert(i); } cout << \"Original multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; ms_iterator = multi_set.begin(); ms_iterator++; ms_iterator++; // Passing the iterator range for the positions // at which the values are to be erased auto ir = multi_set.erase(ms_iterator, multi_set.end()); cout << \"Modified multiset: \"; for (ms_iterator = multi_set.begin(); ms_iterator != multi_set.end(); ++ms_iterator) cout << ' ' << *ms_iterator; cout << '\\n'; (ir == multi_set.end()) ? cout << \"Return value is: multi_set.end()\\n \" : cout << \"Return value is not multi_set.end()\\n\"; return 0;}", "e": 38179, "s": 37068, "text": null }, { "code": null, "e": 38276, "s": 38179, "text": "Original multiset: 1 2 3 4 5 6 7 8 9\nModified multiset: 1 2\nReturn value is: multi_set.end();\n" }, { "code": null, "e": 38291, "s": 38276, "text": "vaibhavkpatel1" }, { "code": null, "e": 38305, "s": 38291, "text": "CPP-Functions" }, { "code": null, "e": 38318, "s": 38305, "text": "cpp-multiset" }, { "code": null, "e": 38322, "s": 38318, "text": "STL" }, { "code": null, "e": 38326, "s": 38322, "text": "C++" }, { "code": null, "e": 38339, "s": 38326, "text": "C++ Programs" }, { "code": null, "e": 38343, "s": 38339, "text": "STL" }, { "code": null, "e": 38347, "s": 38343, "text": "CPP" }, { "code": null, "e": 38445, "s": 38347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38464, "s": 38445, "text": "Inheritance in C++" }, { "code": null, "e": 38488, "s": 38464, "text": "C++ Classes and Objects" }, { "code": null, "e": 38515, "s": 38488, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 38543, "s": 38515, "text": "Operator Overloading in C++" }, { "code": null, "e": 38571, "s": 38543, "text": "Socket Programming in C/C++" }, { "code": null, "e": 38606, "s": 38571, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 38665, "s": 38606, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 38691, "s": 38665, "text": "C++ Program for QuickSort" }, { "code": null, "e": 38735, "s": 38691, "text": "Program to print ASCII Value of a character" } ]
Customer Satisfaction Prediction Using Machine Learning | by Paritosh Mahto | Towards Data Science
Predicting Customer Satisfaction for the purchase made from the Brazilian e-commerce site Olist. This Article Includes:1.Introduction2.Business Problem3.Problem Statement4.Bussiness objectives and constraints5.Machine Learning Formulation i Data Overview ii.Data Description iii.Machine Learning Problem iv.Performance Metrics6.Exploratory Data Analysis(EDA) a.Data Cleaning and Deduplication b.High Level Statistics c.Univariate Analysis d.Bivariate Analysis e.Multivariate Analysis f.RFM Analysis g.Conclusion7.Data Preprocessing and Feature Engineering8.Model Selection 9.Summary10.Deployment11.Improvements to Existing Approach12.Future Work13.Reference The e-commerce sector is rapidly evolving as internet accessibility is increasing in different parts of the world over the years. This sector is redefining commercial activities worldwide and plays a vital role in daily lives nowadays. It has been also observed that the top categories of goods that are frequently ordered by the consumers are clothing, groceries, home improvement materials e.t.c and the percentage of these products may significantly increase in the future. In general, we can say e-commerce is a medium powered by the internet, where customers can access an online store to browse through, and place orders for products or services via their own devices(computers, tablets, or smartphones). Examples- e-commerce transactions, including books, groceries, music, plane tickets, and financial services such as stock investing and online banking. There are mainly four types of e-commerce; these are shown in figure 1. The main advantages of e-commerce are it is available 24 hours a day, seven days a week, a wider array of products are available on a single platform. The disadvantages are limited consumer services as it is very difficult to demonstrate each product to the consumer online, time taken to deliver the product. Machine Learning can play a vital role in e-commerce like sales prediction, prediction of the next order of the consumer, review prediction, sentiment analysis, product recommendations e.t.c.It can also provide services through e-commerce like voice search, image search, chatbot, in-store experience(augmented reality) e.t.c. Olist is an e-commerce site of Brazil which provides a better platform to connect merchants and their product to the main marketplace of Brazil. Olist released this dataset on Kaggle in Nov 2018. The data-set has information of 100k orders from 2016 to 2018 made at multiple marketplaces in Brazil. Its features allow viewing orders from multiple dimensions: from order status, price, payment, and freight performance to customer location, product attributes and finally reviews written by customers. A Geo-location data-set that relates Brazilian zip codes to lat/long coordinates has also been released. This business is based on the interaction between consumers, Olist store, and the seller. At first, an order is made by the consumer on the Olist site. This order is received by Olist store, based on the information of the order (like the product category, geolocation, mode of payment e.t.c) a notification is forwarded to the sellers. After that product is received from the seller and delivered to the consumer within the estimated delivery time. Once the customer receives the product, or if the estimated delivery date is due, the customer gets a satisfaction survey by email where he can give a note for the purchase experience and write down some comments. For a given historical data of the customer predict the review score for the next order or purchase. This problem statement can be further modified to predict customer satisfaction (positive or negative) for the purchase made from the Brazilian e-commerce site Olist. No latency-latency requirement. Interpretability of the model can be useful for understanding customer’s behaviour. Here, the objective is to predict the customer satisfaction score for a given order based on the given features like price, item description, on-time delivery, delivery status, etc. The given problem can be solved either by multiclass classification problem(predict score [1,2,3,4,5] ), binary classification problem(0 as negative of 1 as positive), or Regression problem(for predicting scores) 5.i Data Overview Source:- https://www.kaggle.com/olistbr/brazilian-ecommerceUploaded In the Year : 2018provided by : Olist Store The data is divided into multiple datasets for better understanding and organization. Data is available in 9 csv files:1. olist_customers_dataset.csv (data)2. olist_geolocation_dataset.csv(geo_data)3. olist_order_items_dataset.csv(order_itemdata)4. olist_order_payments_dataset.csv(pay_data)5. olist_order_reviews_dataset.csv(rev_data)6. olist_orders_dataset.csv(orders)7. olist_products_dataset.csv(order_prddata)8. olist_sellers_dataset.csv(order_selldata)9. product_category_name_translation.csv(order_prd_catdata) The olist_orders_dataset has the order data for each purchase connected with other data using order_id and customer_id. The olist_order_reviews_dataset has the labelled review data for each order in the order data table labelled as [1,2,3,4,5] where 5 being the highest and 1 being the lowest. We will use reviews greater than 3 as positive and less than equal to 3 as negative reviews. The data will be merged accordingly to get the final data needed for the analysis, feature selection, and model training. 5.ii. Data Description The number of columns and rows with columns name of each .csv file are shown in this data frame: Description About all columns/features are shown below: Each feature or columns of different csv files are described below: The olist_customers_dataset.csv contain following features: The olist_sellers_dataset.csv contains following features: The olist_order_items_dataset.csv contain following features: The olist_order_payments_dataset.csv contain following features: The olist_orders_dataset.csv contain following features: The olist_order_reviews_dataset.csv contain following features: The olist_products_dataset.csv contain following features: 5.iii. Machine Learning Problem The above problem can be formulated as a binary classification problem i.e for a given order and purchase data of a consumer predict the review will be positive or negative. 5.iv. Performance Metrics Macro f1-score- Confusion Matrix As far as we have understood the business problem and formulated the machine learning problem statement. We also understood about the datasets and most of the features. Now, we will do Exploratory Data Analysis on this dataset and to get more insights into the features. The first step that I followed is to read all the .csv files and checked the columns in each CSV file and their datatypes. After this, all the data are merged according to the given data schema. Further, I performed the data cleaning and did different analyses on the dataset. 6.a Data Cleaning Handling missing values df.isnull().sum() order_id 0 customer_id 0 order_status 0 order_purchase_timestamp 0 order_approved_at 14 order_delivered_carrier_date 1213 order_delivered_customer_date 2515 order_estimated_delivery_date 0 payment_sequential 0 payment_type 0 payment_installments 0 payment_value 0 customer_unique_id 0 customer_zip_code_prefix 0 customer_city 0 customer_state 0 order_item_id 0 product_id 0 seller_id 0 shipping_limit_date 0 price 0 freight_value 0 product_category_name 0 product_name_lenght 0 product_description_lenght 0 product_photos_qty 0 product_weight_g 1 product_length_cm 1 product_height_cm 1 product_width_cm 1 product_category_name_english 0 review_score 0 review_comment_message 66703 dtype: int64 The merged final data have many null values. The maximum number of null values are present in the column review_comment_message which is of object dtype.Columns like order_approved_at , order_delivered_carrier_date and order_delivered_customer_date are also, have null values. These missing values are either replaced and dropped. The codes are shown below. Data Deduplication As you can observe the duplicate rows like the row with order_id 82bce245b1c9148f8d19a55b9ff70644 all the columns are the same. we can drop these rows keeping the first. 5.b High label Statistics The final data after merging, cleaning, and deduplication has the following features - The merged data has 32 columns and it has categorical features like order_status,payment_type, customer_state, and product_ category _name_english. One column named review_comment_message has text data that is in Portuguese. There are few numerical features also. The description of the numerical features are shown below- We can observe from the above table that- For the price and freight value of an order. The maximum price of an order is 6735 while the max freight is around 410 Brazilian real. The average price of an order is around 125 Brazilian real and freight value is around 20 Brazilian real. The order with a minimum price of 0.85 Brazilian real has been made. For payment_value, the maximum payment value of an order is 13664 Brazilian real. Also, We can observe the statistics like percentile values, mean and standard deviation values, count, min, and a max of other numerical features. Correlation Matrix- Now let us observe the target variable i.e review score, the scores greater than or equal to 3 are considered as 1(positive) and otherwise 0(negative). From the distribution of the target variable, we can observe 85.5% of the total reviews are positive and 14.5% are negative. From this, we can conclude that the given dataset is skewed or imbalanced. 5.c Univariate Analysis In this eCommerce dataset, there are mainly four types of payment methods are used these are credit card, baleto, voucher, and debit card. Note: Baleto ==> Boleto Bancário, simply referred to as Boleto (English: Ticket) is a payment method in Brazil regulated by FEBRABAN, short for Brazilian Federation of Banks.It can be paid at ATMs, branch facilities and internet banking of any Bank, Post Office, Lottery Agent and some supermarkets until its due date. from the above plots, we can observe that most of the orders are paid using a credit card and the second most used payment method is boleto. The percentage of each mode of payment is shown in the pie chart which shows amongst all payments made by the user the credit card is used by 75.9% of the users, baleto is used by 19.9% of the user and 3.2% of the user used voucher and debit card. We can observe from the above Pareto plot also that 96% of the customers had used a credit card and baleto. lets us see how this feature is related to our target variable. We can observe from the above-stacked plot that most of the customers who used credit cards have given positive reviews. Also, for the boleto, voucher, and debit card users, it is the same. From this, we can conclude that this can be our important categorical feature for the problem. Now let's do a univariate analysis on the column customer_state. This column contains state codes for the corresponding customer_id. The name of the states and the state codes are shown below on the map of Brazil. The top three populous states of Brazil are São Paulo, Minas Gerais, and Rio de Janeiro and we can also observe from the plot shown below that 66.6 % of the orders are received from these states which mean most of the customers are from these states. Also from the stack plot of reviews per state shown below, we can conclude that most consumers from each state have given positive reviews. In SP state from the total reviews of 40800, 35791 reviews are positive and for RJ state 9968 reviews are positive from the total reviews 12569. The consumer_state can be our important feature for the problem. As we know product categories are one of the important features in this business to know the top-selling product categories I plotted a bar graph shown below- As we can observe, the most ordered products are from the bed_bath_table category, health beauty, and sports_leisure between 2016 and 2018. There are few timestamp features also in this dataset like order_purchase_timestamp ,order_purchase_timestamp ,order_approved_at ,order_delivered_customer_date ,order_estimated_delivery_date e.t.c. I did a univariate analysis on the timestamps after extracting attributes like a month, year, day, day of week e.t.c. The data given is of 699 days and the timestamp between which data is collected is 2016–10–04 09:43:32 -2018–09–03 17:40:06 . The evolution of the total orders received is shown above, the maximum number of orders are received in 201711. Also, we can observe the growth of Olist from 201609 to 201808.The analysis of the orders and reviews based on the attributes extracted from order_purchase_timestamp has been concluded. From the subplot titled Total Reviews by Month, we can observe that the highest % of positive reviews amongst the total reviews between 2016 to 2018 are given Feb i.e 9.8%.In May and July amongst the total reviews, there are more than 9.0% of reviews are positive. From the second subplot titled Total Reviews by Time of the day, we can conclude that a maximum number of orders are received in the afternoon and the highest % of positive reviews are given at that time i.e 32.8%. From the third subplot titled Total Reviews by day of the week, we can conclude that a maximum number of orders are received on Monday and the highest % of positive reviews are given on that day and Tuesday i.e 13.9%. Univariate Analysis on numerical features- Distribution of product price per class Distribution of frieght_value per class Distribution of product_height per class Distribution of product_weight_g per class The above distribution plots show the distribution of each numerical feature for both the positive and negative classes. We can observe that there is an almost complete overlap of both the distribution for the positive and negative classes which suggests that it is not possible to classify them based only on these features. 6.d Bivariate Analysis There are more than 10 numerical features in this dataset but from the correlation matrix shown above, we can observe most of the features are cont linearly related. For bivariate analysis, only four features are selected and plotted in a scatter plot. From the two scatter plots titled Distribution of price vs freight_value per class and Distribution of price vs freight_value per class respectively, we can observe It is very hard to say anything about the reviews based on these plots as data points are not separable based on reviews these are completely mixed data. Distribution of price vs freight_value per class Distribution of price vs product_weight_g per class Pair Plots A pair plot is plotted shown below for the features product_photos_qty, product_name_length,product_description_length as these have negative correlation values with the review_score column. All the scatter plots between the features are completely mixed up not separable based on reviews. We can say that none of these features is helpful for classification. 6.e Multivariate Analysis In a multivariate analysis, The evolution of sales and orders between 2016 and 2108 has been plotted. From the plot, we can observe that there is the same pattern of total sales and the total order per month between 2016 and 2018. 6.f RFM Analysis For the given data of customers, I did an RFM analysis on this data.RFM analysis is basically a data-driven customer behaviour segmentation technique.RFM stands for recency, frequency, and monetary value. RFM stands for-Recency — number of days since the last purchaseFrequency — number of transactions made over a given periodMonetary — the amount spent over a given period of time Python code for calculating recency, frequency, and monetary- Output after creating RFM is shown below- To know more about this behaviour segmentation technique you can visit here- www.barilliance.com The distribution recency, frequency, and monetary of all the customers are shown below. From the first plot of recency, we can observe that most of the users stayed with Olist for a long duration which is a positive thing but the order frequency is less. from the second plot of frequency, the most number of transaction or order is less than 5. from the third plot of monetary the maximum amount spent over the given very period is seems to less than 1500 approx. The square plot of the behaviour segmentation of the customers shown below. Based on the RFM_Score_s calculated for all the customers I categorized the customers into 7 categories : 'Can\'t Loose Them' ==== RMF_Score_s ≥ 9'Champions' ==== 8 ≤ RMF_Score_s < 9'Loyal' ==== 7 ≤ RMF_Score_s <8'Needs Attention' ==== 6 ≤ RMF_Score_s <7'Potential' ==== 5 ≤ RMF_Score_s < 6'Promising' ==== 4 ≤ RMF_Score_s < 5 'Require Activation' RMF_Score_s <4 From the above square plot, the highest percentage of customers lies within the area of category potential. Few areas are also there with coloured in blue scale which shows the percentage of consumers who require more attention so that they can retain in Olist. We can use either RMF_Score_s or RMF_Level as a feature to solve this problem. After merging, data cleaning, and data analysis of data we will get the final data which can be used further for preprocessing and feature extraction. 6.g Conclusion * The target variable/class-label is imbalanced.We should be carefull while choosing the performance metric of the models.* From the univariate analysis of payment_type we observed that 96 % of the user used credit card and boleto and concluded that this can be our important feature.* Also,from the univariate analysis of consumer_state we found that 42% of total consumers are from the SP(São Paulo), 12.9 % are from RJ(Rio de Janeiro) and 11.7 % are from MG(Minas Gerais).* After analyzing the product_category feature we observed that the most ordered products are from the bed_bath_table category, health beauty, and sports_leisure between 2016 and 2018. The least ordered products are from security_and_services.* The different timestamps seem to be important features as many new features can be explored from these. we observed within 2016–18 the total number of orders received is increasing till 2017–11 and after that their a small decrement. from the month, day and time we observed the most number of orders are received in the month of Feb, on Monday and afternoon time.* The numerical features like price, payment_value, freight_value,product_height_cm,product_length_cm doesnot seems to be helpful for this classification problem as observed from univariate and bivarate analysis.Also we can say linear model like KNN, Naive Bayes might not work well.* RMF Analysis is also done to understand whether new features can be created from this or not and we found that one numerical feature or categorical feature can be extracted from this. After the data analysis, we came to know about different categorical and numerical features. All categorical features seem to be preprocessed, we need not do preprocessing for these features. But, there is also a column named review_comment_message which contains text data. We have to do text preprocessing before the featurization of these data. Preprocessing of Review Text Since we have text data in the Portuguese Language, we have to be careful while choosing stemmer, stopwords, and while replacing and removing any special character or any word. I selected nltk library for this and from this I have imported stopword using from nltk.corpus import stopwords and imported RSLP steamer using RSLPStemmer() . As we replaced the null values in the reviews data with 'nao_reveja' we have to remove words like 'não' & 'nem' from the stopwords. After this, we have to remove or replace links, currency symbols, dates, digits, extra space, and tab e.t.c. The preprocess function is shown below- Review text column before and after preprocessing is shown below- Before After Vectorization of text data Now, we have preprocessed text, for converting these text data I used FastText from gensim library to convert words into a vector with TF-IDF vectorizer().tfidf values give more weight to the most frequent words. The code snippet is shown below- for loading FastText model (for 300 dim) vectorizer function : After this, the features which are not useful are dropped from the final data. The columns which are dropped are shown below. col= ['order_id', 'customer_id', 'order_purchase_timestamp', 'order_approved_at', 'order_delivered_customer_date', 'order_estimated_delivery_date', 'customer_unique_id', 'order_item_id', 'product_id', 'seller_id', 'shipping_limit_date', 'order_purchase_month_name', 'order_purchase_year_month', 'order_purchase_date', 'order_purchase_month_yr', 'order_purchase_day', 'order_purchase_dayofweek', 'order_purchase_dayofweek_name', 'order_purchase_hour','order_purchase_time_day','customer_city','customer_zip_code_prefix','product_category_name'] Now, we have our final data with preprocessed text data, categorical and numerical features. we can split the data using from sklearn.model_selection import train_test_split with stratify=y as we have imbalanced data. we also have categorical features which are not encoded yet. for encoding categorical features I used CountVectorizer(binary= True) function, encoding of order_status feature is shown below. The numerical features are also scaled using from sklearn.preprocessing import Normalizer .All the vectorized features are stacked using from scipy.sparse import hstack to form X_train and X_test. Baseline Model Selection We have existing vectorized features now we will build few basic models and we will choose the one for our baseline model. After this, we will try to improve on the baseline by adding new features and to add new features I will again do some EDA. The models which are used are the random model, the Naive Bayes Model, and Logistic Regression Model. The output scores and confusion matrix are shown below. Random Model Train f1-score 0.42757018716907186Test f1-score 0.4261466361217526 Naive Bayes Train f1 score: 0.7424119484527338Test f1 score: 0.7472580717762947 Logistic Regression Train f1 score: 0.8165306456031154Test f1 score: 0.8062989397776499 The logistic Regression Model is performing better than the other models. The logistic Regression Model is chosen as a baseline model. From both the train and test confusion matrix, we can observe that the False Positive and False Negative values are still very large let's try to reduce these values by adding some features and through feature selection methods. Feature Engineering Along with the existing features,16 new features are added to the data. The details about these features are shown below. After adding new features, we have a total of 29 numerical features and 5 categorical features, and text data(300 dim). we will again run the selected baseline model i.e Logistic Regression Model and check the output from it. The output is shown below. Train f1 score: 0.8258929671475947Test f1 score: 0.8167104393178897 We got the better train and test f1-scores but still, we have high FP and FN values. To reduce these values and increase the scores I tried Autoencoder Model for feature selection. Feature Extraction/Selection using AutoEncoder Model Autoencoder is a type of neural network that can be used to learn a compressed(reduced dimension) representation of raw data. An autoencoder is composed of an encoder and a decoder sub-models. The encoder compresses the input and the decoder attempts to recreate the input from the compressed version provided by the encoder. After training, the encoder model is saved and the decoder is discarded. The encoder can then be used as a data preparation technique to perform feature extraction on raw data that can be used to train a different machine learning model. source-https://machinelearningmastery.com/autoencoder-for-classification/ The architecture of the model is shown below. I used a dense layer, BatchNormalisation Layer, and leakyRelu as an activation layer. I ran this model for 10 epochs, and after running the model I saved the encoder part. Loss Vs Epoch graph Then, important features are extracted from the encoder model. code snippet: The baseline line model is run again with the extracted features. The output is shown below. Train f1 score: 0.8457608492913875Test f1 score: 0.8117963347711852 The f1-score is increased and also we got decreased FP and FN values. We will now run different machine learning and deep learning models and select the best model for our problem. Model selection is the process of choosing one of the models as the final model that addresses the problem. As we have seen the baseline model performance, now to improve the scores we will try the model selection process for both different types of models (e.g. logistic regression, SVM, KNN, Decision Trees, Ensembles, etc.) and models of the same type configured with different model hyperparameters (e.g. different kernels in an SVM). Machine Learning Models We start with different classification models to Neural Network models. The models that we are experimented with within this case study are as follows:- Logistic RegressionLinear Support Vector MachineDecision Tree ClassifierRandom Forest ClassifierBoosting Classifier (XGBoost/LightGBM/AdaBoost/CATBoost)Stacking/Voting Ensemble techniques Logistic Regression Linear Support Vector Machine Decision Tree Classifier Random Forest Classifier Boosting Classifier (XGBoost/LightGBM/AdaBoost/CATBoost) Stacking/Voting Ensemble techniques For each model, I did hyperparameter tuning using RandomizedSearchCV .The summary of all the outputs with the best hyperparameters of all the models is shown below. We can observe the best model based on the test f1-score is vot_hard the code snippet and the output is shown below. Code snippet of all the models can be found here- jovian.ai Deep Learning Models As we have seen different machine learning models, now we will try different neural network models. I tried 5 different models and used these models to form deep learning stacking models. Model-1 In Model-1 I build a simple model with 5 dense layers as hidden layers and 1 dense layer as output layer. At the output layer sigmoid as the activation function is used. The input given is the extracted features from the encoder model. I used a custom f1-score metric to evaluate these models. Model Architecture Epoch Vs Loss Plot Output Train f1_score: 0.8632763852422476Test f1_score: 0.8218909906703276 Model-2 In Model- 2 I used 4 CONV1D layers,2 MaxPooling1D layers with one dropout and one flatten layer as hidden layers, and 1 dense layer as output layer. At the output layer sigmoid as the activation function is used. The input given is the extracted features from the encoder model but with the reshaped array. Model Architecture Epoch Vs Loss Output Train f1_score: 0.8610270746182962 Test f1_score: 0.8253479131333611 Model-3 In Model -3 I used LSTM Layer, embedding layer, BatchNormalisation layer, dense layer, dropout, and flatten layer to build the model with multiple inputs and one output. The input data are explained below. Input_seq_total_text_data- I used the Embedding layer to get word vectors for the text data columns. I also used predefined fasttext word vectors for creating an embedding matrix. After this used LSTM and got the LSTM output and Flatten that output. Input_order_status- given order_status column as input to embedding layer and then trained the Keras Embedding layer. payment_type- given payment_type column as input to embedding layer and trained the Keras Embedding layer. Input_customer_state- given customer_state column as input to embedding layer and trained the Keras Embedding layer. Input_product_category- given product_category column as input to embedding layer and trained the Keras Embedding layer. Input_rfm - given RFM_Level column as input to embedding layer and trained the Keras Embedding layer. Input_numerical- concatenate remaining columns i.e numerical features and added a Dense layer after that. All these are concatenated at the end and passed through different dense layers. Model Architecture Epoch Vs Loss Output Train f1_score: 0.860330602322043 Test f1_score: 0.8327277576694923 Model-4 Model -4 also used LSTM Layer, Conv1D, embedding layer, BatchNormalisation layer, dense layer, dropout, and flatten layer to build the model but with two inputs and one output. The input data are explained below. Input_seq_total_text_data- I used the Embedding layer to get word vectors for the text data columns. I also used predefined fast text word vectors for creating an embedding matrix. After this used LSTM and got the LSTM output and Flatten that output. Other_than_text_data- All categorical features are converted to a one-hot encoded vector and then concatenated along with numerical features using np. hstack Model Architecture Epoch Vs Loss Output Train f1_score: 0.8815188513597205 Test f1_score: 0.8218441232242646 Model-5 Model -5 also used LSTM Layer, Conv1D, embedding layer, BatchNormalisation layer, dense layer, dropout, and flatten layer to build the model but with two inputs and one output. The input data are the same as model 4. Model Architecture Epoch Vs Loss Output Train f1_score: 0.8508463263785984Test f1_score: 0.8287339894123904 Deep Learning Stacking Model As we have seen 5 deep learning models now we will use an ensemble method where the above 5 models are used as sub-models and each will contribute equally to the combined prediction and XGBClassifier is used as the final model i.e meta-model. We will build two stacking models one with hard stacking another with soft stacking and the output will be compared with the above model’s output. The code snippet for each step for building both hard and stacking is shown below. step-1 Loading five sub-models step-2 Predictions From each model step-3 Stacking the Predictions and passed through the meta-classifier Hard Stacking Output : Soft Stacking Output: As we can observe the outputs of both stacking models are performing better than the above deep learning models. The code snippets of all the deep learning models can be found here — jovian.ai From EDA we concluded that the given dataset is skewed and with correlation values, we have seen most of the numerical features are not linearly related which means that simple ml classification might not work well. The review data are in text form we did preprocess of these data and also the addition of new features helped improve the scores. The autoencoder model helped more in feature selection and performance enhancement. In the model selection part, we have gone through different ml model and dl model performances. After comparing all the results we can conclude that the model is a deep learning stacking model i.e soft stacking model. Now we will use this model while the deployment process. The best stacked deep learning model is deployed using streamlit and Github. Using streamlit uploader function I created a CSV file input section where you can give raw data. After that, you have to choose the unique customer id and corresponding order ids and the prediction will be shown as an image. webpage link- https://share.streamlit.io/paritoshmahto07/customer-satisfaction-prediction/main/app.py Deployment Video- In the Existing approach, two regression models are used with nine new features for the prediction of review scores got RMSE of 0.58. In the existing approach, different models are also not used, and also limited features are used. In our approach that we followed had achieved a very good result than the existing approach and also we used a new text featurization method along with an autoencoder model for feature selection due to which the performance of the models increased. The vectorization of the Portuguese text data with different methods can improve the result. Also, the Addition of new features and parameter tuning of the DL models can be done to achieve a better result. My LinkedIn Profile https://www.linkedin.com/in/paritosh07/ My Github Profile github.com i.Existing Solution- www.kaggle.com ii. Data Analysis and Visualisation- www.kaggle.com iii. RFM Analysis- towardsdatascience.com iv. Autoencoder Model machinelearningmastery.com v. Stacking ML Models machinelearningmastery.com vi. Stacking DL Models machinelearningmastery.com vii. Mentorship www.appliedaicourse.com Thanks for reading, have a good day! 🙂
[ { "code": null, "e": 269, "s": 172, "text": "Predicting Customer Satisfaction for the purchase made from the Brazilian e-commerce site Olist." }, { "code": null, "e": 872, "s": 269, "text": "This Article Includes:1.Introduction2.Business Problem3.Problem Statement4.Bussiness objectives and constraints5.Machine Learning Formulation i Data Overview ii.Data Description iii.Machine Learning Problem iv.Performance Metrics6.Exploratory Data Analysis(EDA) a.Data Cleaning and Deduplication b.High Level Statistics c.Univariate Analysis d.Bivariate Analysis e.Multivariate Analysis f.RFM Analysis g.Conclusion7.Data Preprocessing and Feature Engineering8.Model Selection 9.Summary10.Deployment11.Improvements to Existing Approach12.Future Work13.Reference" }, { "code": null, "e": 1349, "s": 872, "text": "The e-commerce sector is rapidly evolving as internet accessibility is increasing in different parts of the world over the years. This sector is redefining commercial activities worldwide and plays a vital role in daily lives nowadays. It has been also observed that the top categories of goods that are frequently ordered by the consumers are clothing, groceries, home improvement materials e.t.c and the percentage of these products may significantly increase in the future." }, { "code": null, "e": 1583, "s": 1349, "text": "In general, we can say e-commerce is a medium powered by the internet, where customers can access an online store to browse through, and place orders for products or services via their own devices(computers, tablets, or smartphones)." }, { "code": null, "e": 1735, "s": 1583, "text": "Examples- e-commerce transactions, including books, groceries, music, plane tickets, and financial services such as stock investing and online banking." }, { "code": null, "e": 1807, "s": 1735, "text": "There are mainly four types of e-commerce; these are shown in figure 1." }, { "code": null, "e": 2117, "s": 1807, "text": "The main advantages of e-commerce are it is available 24 hours a day, seven days a week, a wider array of products are available on a single platform. The disadvantages are limited consumer services as it is very difficult to demonstrate each product to the consumer online, time taken to deliver the product." }, { "code": null, "e": 2444, "s": 2117, "text": "Machine Learning can play a vital role in e-commerce like sales prediction, prediction of the next order of the consumer, review prediction, sentiment analysis, product recommendations e.t.c.It can also provide services through e-commerce like voice search, image search, chatbot, in-store experience(augmented reality) e.t.c." }, { "code": null, "e": 2640, "s": 2444, "text": "Olist is an e-commerce site of Brazil which provides a better platform to connect merchants and their product to the main marketplace of Brazil. Olist released this dataset on Kaggle in Nov 2018." }, { "code": null, "e": 3050, "s": 2640, "text": "The data-set has information of 100k orders from 2016 to 2018 made at multiple marketplaces in Brazil. Its features allow viewing orders from multiple dimensions: from order status, price, payment, and freight performance to customer location, product attributes and finally reviews written by customers. A Geo-location data-set that relates Brazilian zip codes to lat/long coordinates has also been released." }, { "code": null, "e": 3140, "s": 3050, "text": "This business is based on the interaction between consumers, Olist store, and the seller." }, { "code": null, "e": 3387, "s": 3140, "text": "At first, an order is made by the consumer on the Olist site. This order is received by Olist store, based on the information of the order (like the product category, geolocation, mode of payment e.t.c) a notification is forwarded to the sellers." }, { "code": null, "e": 3500, "s": 3387, "text": "After that product is received from the seller and delivered to the consumer within the estimated delivery time." }, { "code": null, "e": 3714, "s": 3500, "text": "Once the customer receives the product, or if the estimated delivery date is due, the customer gets a satisfaction survey by email where he can give a note for the purchase experience and write down some comments." }, { "code": null, "e": 3815, "s": 3714, "text": "For a given historical data of the customer predict the review score for the next order or purchase." }, { "code": null, "e": 3982, "s": 3815, "text": "This problem statement can be further modified to predict customer satisfaction (positive or negative) for the purchase made from the Brazilian e-commerce site Olist." }, { "code": null, "e": 4014, "s": 3982, "text": "No latency-latency requirement." }, { "code": null, "e": 4098, "s": 4014, "text": "Interpretability of the model can be useful for understanding customer’s behaviour." }, { "code": null, "e": 4280, "s": 4098, "text": "Here, the objective is to predict the customer satisfaction score for a given order based on the given features like price, item description, on-time delivery, delivery status, etc." }, { "code": null, "e": 4493, "s": 4280, "text": "The given problem can be solved either by multiclass classification problem(predict score [1,2,3,4,5] ), binary classification problem(0 as negative of 1 as positive), or Regression problem(for predicting scores)" }, { "code": null, "e": 4511, "s": 4493, "text": "5.i Data Overview" }, { "code": null, "e": 4623, "s": 4511, "text": "Source:- https://www.kaggle.com/olistbr/brazilian-ecommerceUploaded In the Year : 2018provided by : Olist Store" }, { "code": null, "e": 4709, "s": 4623, "text": "The data is divided into multiple datasets for better understanding and organization." }, { "code": null, "e": 5141, "s": 4709, "text": "Data is available in 9 csv files:1. olist_customers_dataset.csv (data)2. olist_geolocation_dataset.csv(geo_data)3. olist_order_items_dataset.csv(order_itemdata)4. olist_order_payments_dataset.csv(pay_data)5. olist_order_reviews_dataset.csv(rev_data)6. olist_orders_dataset.csv(orders)7. olist_products_dataset.csv(order_prddata)8. olist_sellers_dataset.csv(order_selldata)9. product_category_name_translation.csv(order_prd_catdata)" }, { "code": null, "e": 5261, "s": 5141, "text": "The olist_orders_dataset has the order data for each purchase connected with other data using order_id and customer_id." }, { "code": null, "e": 5435, "s": 5261, "text": "The olist_order_reviews_dataset has the labelled review data for each order in the order data table labelled as [1,2,3,4,5] where 5 being the highest and 1 being the lowest." }, { "code": null, "e": 5528, "s": 5435, "text": "We will use reviews greater than 3 as positive and less than equal to 3 as negative reviews." }, { "code": null, "e": 5650, "s": 5528, "text": "The data will be merged accordingly to get the final data needed for the analysis, feature selection, and model training." }, { "code": null, "e": 5673, "s": 5650, "text": "5.ii. Data Description" }, { "code": null, "e": 5770, "s": 5673, "text": "The number of columns and rows with columns name of each .csv file are shown in this data frame:" }, { "code": null, "e": 5826, "s": 5770, "text": "Description About all columns/features are shown below:" }, { "code": null, "e": 5894, "s": 5826, "text": "Each feature or columns of different csv files are described below:" }, { "code": null, "e": 5955, "s": 5894, "text": "The olist_customers_dataset.csv contain following features:" }, { "code": null, "e": 6014, "s": 5955, "text": "The olist_sellers_dataset.csv contains following features:" }, { "code": null, "e": 6077, "s": 6014, "text": "The olist_order_items_dataset.csv contain following features:" }, { "code": null, "e": 6142, "s": 6077, "text": "The olist_order_payments_dataset.csv contain following features:" }, { "code": null, "e": 6200, "s": 6142, "text": "The olist_orders_dataset.csv contain following features:" }, { "code": null, "e": 6265, "s": 6200, "text": "The olist_order_reviews_dataset.csv contain following features:" }, { "code": null, "e": 6324, "s": 6265, "text": "The olist_products_dataset.csv contain following features:" }, { "code": null, "e": 6356, "s": 6324, "text": "5.iii. Machine Learning Problem" }, { "code": null, "e": 6530, "s": 6356, "text": "The above problem can be formulated as a binary classification problem i.e for a given order and purchase data of a consumer predict the review will be positive or negative." }, { "code": null, "e": 6556, "s": 6530, "text": "5.iv. Performance Metrics" }, { "code": null, "e": 6572, "s": 6556, "text": "Macro f1-score-" }, { "code": null, "e": 6589, "s": 6572, "text": "Confusion Matrix" }, { "code": null, "e": 6860, "s": 6589, "text": "As far as we have understood the business problem and formulated the machine learning problem statement. We also understood about the datasets and most of the features. Now, we will do Exploratory Data Analysis on this dataset and to get more insights into the features." }, { "code": null, "e": 7137, "s": 6860, "text": "The first step that I followed is to read all the .csv files and checked the columns in each CSV file and their datatypes. After this, all the data are merged according to the given data schema. Further, I performed the data cleaning and did different analyses on the dataset." }, { "code": null, "e": 7155, "s": 7137, "text": "6.a Data Cleaning" }, { "code": null, "e": 7179, "s": 7155, "text": "Handling missing values" }, { "code": null, "e": 7197, "s": 7179, "text": "df.isnull().sum()" }, { "code": null, "e": 8497, "s": 7197, "text": "order_id 0\ncustomer_id 0\norder_status 0\norder_purchase_timestamp 0\norder_approved_at 14\norder_delivered_carrier_date 1213\norder_delivered_customer_date 2515\norder_estimated_delivery_date 0\npayment_sequential 0\npayment_type 0\npayment_installments 0\npayment_value 0\ncustomer_unique_id 0\ncustomer_zip_code_prefix 0\ncustomer_city 0\ncustomer_state 0\norder_item_id 0\nproduct_id 0\nseller_id 0\nshipping_limit_date 0\nprice 0\nfreight_value 0\nproduct_category_name 0\nproduct_name_lenght 0\nproduct_description_lenght 0\nproduct_photos_qty 0\nproduct_weight_g 1\nproduct_length_cm 1\nproduct_height_cm 1\nproduct_width_cm 1\nproduct_category_name_english 0\nreview_score 0\nreview_comment_message 66703\ndtype: int64" }, { "code": null, "e": 8855, "s": 8497, "text": "The merged final data have many null values. The maximum number of null values are present in the column review_comment_message which is of object dtype.Columns like order_approved_at , order_delivered_carrier_date and order_delivered_customer_date are also, have null values. These missing values are either replaced and dropped. The codes are shown below." }, { "code": null, "e": 8874, "s": 8855, "text": "Data Deduplication" }, { "code": null, "e": 9044, "s": 8874, "text": "As you can observe the duplicate rows like the row with order_id 82bce245b1c9148f8d19a55b9ff70644 all the columns are the same. we can drop these rows keeping the first." }, { "code": null, "e": 9070, "s": 9044, "text": "5.b High label Statistics" }, { "code": null, "e": 9157, "s": 9070, "text": "The final data after merging, cleaning, and deduplication has the following features -" }, { "code": null, "e": 9480, "s": 9157, "text": "The merged data has 32 columns and it has categorical features like order_status,payment_type, customer_state, and product_ category _name_english. One column named review_comment_message has text data that is in Portuguese. There are few numerical features also. The description of the numerical features are shown below-" }, { "code": null, "e": 9522, "s": 9480, "text": "We can observe from the above table that-" }, { "code": null, "e": 9832, "s": 9522, "text": "For the price and freight value of an order. The maximum price of an order is 6735 while the max freight is around 410 Brazilian real. The average price of an order is around 125 Brazilian real and freight value is around 20 Brazilian real. The order with a minimum price of 0.85 Brazilian real has been made." }, { "code": null, "e": 10061, "s": 9832, "text": "For payment_value, the maximum payment value of an order is 13664 Brazilian real. Also, We can observe the statistics like percentile values, mean and standard deviation values, count, min, and a max of other numerical features." }, { "code": null, "e": 10081, "s": 10061, "text": "Correlation Matrix-" }, { "code": null, "e": 10433, "s": 10081, "text": "Now let us observe the target variable i.e review score, the scores greater than or equal to 3 are considered as 1(positive) and otherwise 0(negative). From the distribution of the target variable, we can observe 85.5% of the total reviews are positive and 14.5% are negative. From this, we can conclude that the given dataset is skewed or imbalanced." }, { "code": null, "e": 10457, "s": 10433, "text": "5.c Univariate Analysis" }, { "code": null, "e": 10596, "s": 10457, "text": "In this eCommerce dataset, there are mainly four types of payment methods are used these are credit card, baleto, voucher, and debit card." }, { "code": null, "e": 10916, "s": 10596, "text": "Note: Baleto ==> Boleto Bancário, simply referred to as Boleto (English: Ticket) is a payment method in Brazil regulated by FEBRABAN, short for Brazilian Federation of Banks.It can be paid at ATMs, branch facilities and internet banking of any Bank, Post Office, Lottery Agent and some supermarkets until its due date." }, { "code": null, "e": 11057, "s": 10916, "text": "from the above plots, we can observe that most of the orders are paid using a credit card and the second most used payment method is boleto." }, { "code": null, "e": 11305, "s": 11057, "text": "The percentage of each mode of payment is shown in the pie chart which shows amongst all payments made by the user the credit card is used by 75.9% of the users, baleto is used by 19.9% of the user and 3.2% of the user used voucher and debit card." }, { "code": null, "e": 11477, "s": 11305, "text": "We can observe from the above Pareto plot also that 96% of the customers had used a credit card and baleto. lets us see how this feature is related to our target variable." }, { "code": null, "e": 11762, "s": 11477, "text": "We can observe from the above-stacked plot that most of the customers who used credit cards have given positive reviews. Also, for the boleto, voucher, and debit card users, it is the same. From this, we can conclude that this can be our important categorical feature for the problem." }, { "code": null, "e": 11976, "s": 11762, "text": "Now let's do a univariate analysis on the column customer_state. This column contains state codes for the corresponding customer_id. The name of the states and the state codes are shown below on the map of Brazil." }, { "code": null, "e": 12228, "s": 11976, "text": "The top three populous states of Brazil are São Paulo, Minas Gerais, and Rio de Janeiro and we can also observe from the plot shown below that 66.6 % of the orders are received from these states which mean most of the customers are from these states." }, { "code": null, "e": 12578, "s": 12228, "text": "Also from the stack plot of reviews per state shown below, we can conclude that most consumers from each state have given positive reviews. In SP state from the total reviews of 40800, 35791 reviews are positive and for RJ state 9968 reviews are positive from the total reviews 12569. The consumer_state can be our important feature for the problem." }, { "code": null, "e": 12737, "s": 12578, "text": "As we know product categories are one of the important features in this business to know the top-selling product categories I plotted a bar graph shown below-" }, { "code": null, "e": 12877, "s": 12737, "text": "As we can observe, the most ordered products are from the bed_bath_table category, health beauty, and sports_leisure between 2016 and 2018." }, { "code": null, "e": 13319, "s": 12877, "text": "There are few timestamp features also in this dataset like order_purchase_timestamp ,order_purchase_timestamp ,order_approved_at ,order_delivered_customer_date ,order_estimated_delivery_date e.t.c. I did a univariate analysis on the timestamps after extracting attributes like a month, year, day, day of week e.t.c. The data given is of 699 days and the timestamp between which data is collected is 2016–10–04 09:43:32 -2018–09–03 17:40:06 ." }, { "code": null, "e": 13617, "s": 13319, "text": "The evolution of the total orders received is shown above, the maximum number of orders are received in 201711. Also, we can observe the growth of Olist from 201609 to 201808.The analysis of the orders and reviews based on the attributes extracted from order_purchase_timestamp has been concluded." }, { "code": null, "e": 13882, "s": 13617, "text": "From the subplot titled Total Reviews by Month, we can observe that the highest % of positive reviews amongst the total reviews between 2016 to 2018 are given Feb i.e 9.8%.In May and July amongst the total reviews, there are more than 9.0% of reviews are positive." }, { "code": null, "e": 14097, "s": 13882, "text": "From the second subplot titled Total Reviews by Time of the day, we can conclude that a maximum number of orders are received in the afternoon and the highest % of positive reviews are given at that time i.e 32.8%." }, { "code": null, "e": 14315, "s": 14097, "text": "From the third subplot titled Total Reviews by day of the week, we can conclude that a maximum number of orders are received on Monday and the highest % of positive reviews are given on that day and Tuesday i.e 13.9%." }, { "code": null, "e": 14358, "s": 14315, "text": "Univariate Analysis on numerical features-" }, { "code": null, "e": 14398, "s": 14358, "text": "Distribution of product price per class" }, { "code": null, "e": 14438, "s": 14398, "text": "Distribution of frieght_value per class" }, { "code": null, "e": 14479, "s": 14438, "text": "Distribution of product_height per class" }, { "code": null, "e": 14522, "s": 14479, "text": "Distribution of product_weight_g per class" }, { "code": null, "e": 14848, "s": 14522, "text": "The above distribution plots show the distribution of each numerical feature for both the positive and negative classes. We can observe that there is an almost complete overlap of both the distribution for the positive and negative classes which suggests that it is not possible to classify them based only on these features." }, { "code": null, "e": 14871, "s": 14848, "text": "6.d Bivariate Analysis" }, { "code": null, "e": 15124, "s": 14871, "text": "There are more than 10 numerical features in this dataset but from the correlation matrix shown above, we can observe most of the features are cont linearly related. For bivariate analysis, only four features are selected and plotted in a scatter plot." }, { "code": null, "e": 15443, "s": 15124, "text": "From the two scatter plots titled Distribution of price vs freight_value per class and Distribution of price vs freight_value per class respectively, we can observe It is very hard to say anything about the reviews based on these plots as data points are not separable based on reviews these are completely mixed data." }, { "code": null, "e": 15492, "s": 15443, "text": "Distribution of price vs freight_value per class" }, { "code": null, "e": 15544, "s": 15492, "text": "Distribution of price vs product_weight_g per class" }, { "code": null, "e": 15555, "s": 15544, "text": "Pair Plots" }, { "code": null, "e": 15915, "s": 15555, "text": "A pair plot is plotted shown below for the features product_photos_qty, product_name_length,product_description_length as these have negative correlation values with the review_score column. All the scatter plots between the features are completely mixed up not separable based on reviews. We can say that none of these features is helpful for classification." }, { "code": null, "e": 15941, "s": 15915, "text": "6.e Multivariate Analysis" }, { "code": null, "e": 16172, "s": 15941, "text": "In a multivariate analysis, The evolution of sales and orders between 2016 and 2108 has been plotted. From the plot, we can observe that there is the same pattern of total sales and the total order per month between 2016 and 2018." }, { "code": null, "e": 16189, "s": 16172, "text": "6.f RFM Analysis" }, { "code": null, "e": 16394, "s": 16189, "text": "For the given data of customers, I did an RFM analysis on this data.RFM analysis is basically a data-driven customer behaviour segmentation technique.RFM stands for recency, frequency, and monetary value." }, { "code": null, "e": 16572, "s": 16394, "text": "RFM stands for-Recency — number of days since the last purchaseFrequency — number of transactions made over a given periodMonetary — the amount spent over a given period of time" }, { "code": null, "e": 16634, "s": 16572, "text": "Python code for calculating recency, frequency, and monetary-" }, { "code": null, "e": 16676, "s": 16634, "text": "Output after creating RFM is shown below-" }, { "code": null, "e": 16753, "s": 16676, "text": "To know more about this behaviour segmentation technique you can visit here-" }, { "code": null, "e": 16773, "s": 16753, "text": "www.barilliance.com" }, { "code": null, "e": 16861, "s": 16773, "text": "The distribution recency, frequency, and monetary of all the customers are shown below." }, { "code": null, "e": 17028, "s": 16861, "text": "From the first plot of recency, we can observe that most of the users stayed with Olist for a long duration which is a positive thing but the order frequency is less." }, { "code": null, "e": 17238, "s": 17028, "text": "from the second plot of frequency, the most number of transaction or order is less than 5. from the third plot of monetary the maximum amount spent over the given very period is seems to less than 1500 approx." }, { "code": null, "e": 17314, "s": 17238, "text": "The square plot of the behaviour segmentation of the customers shown below." }, { "code": null, "e": 17420, "s": 17314, "text": "Based on the RFM_Score_s calculated for all the customers I categorized the customers into 7 categories :" }, { "code": null, "e": 17680, "s": 17420, "text": "'Can\\'t Loose Them' ==== RMF_Score_s ≥ 9'Champions' ==== 8 ≤ RMF_Score_s < 9'Loyal' ==== 7 ≤ RMF_Score_s <8'Needs Attention' ==== 6 ≤ RMF_Score_s <7'Potential' ==== 5 ≤ RMF_Score_s < 6'Promising' ==== 4 ≤ RMF_Score_s < 5 'Require Activation' RMF_Score_s <4" }, { "code": null, "e": 17942, "s": 17680, "text": "From the above square plot, the highest percentage of customers lies within the area of category potential. Few areas are also there with coloured in blue scale which shows the percentage of consumers who require more attention so that they can retain in Olist." }, { "code": null, "e": 18021, "s": 17942, "text": "We can use either RMF_Score_s or RMF_Level as a feature to solve this problem." }, { "code": null, "e": 18172, "s": 18021, "text": "After merging, data cleaning, and data analysis of data we will get the final data which can be used further for preprocessing and feature extraction." }, { "code": null, "e": 18187, "s": 18172, "text": "6.g Conclusion" }, { "code": null, "e": 19741, "s": 18187, "text": "* The target variable/class-label is imbalanced.We should be carefull while choosing the performance metric of the models.* From the univariate analysis of payment_type we observed that 96 % of the user used credit card and boleto and concluded that this can be our important feature.* Also,from the univariate analysis of consumer_state we found that 42% of total consumers are from the SP(São Paulo), 12.9 % are from RJ(Rio de Janeiro) and 11.7 % are from MG(Minas Gerais).* After analyzing the product_category feature we observed that the most ordered products are from the bed_bath_table category, health beauty, and sports_leisure between 2016 and 2018. The least ordered products are from security_and_services.* The different timestamps seem to be important features as many new features can be explored from these. we observed within 2016–18 the total number of orders received is increasing till 2017–11 and after that their a small decrement. from the month, day and time we observed the most number of orders are received in the month of Feb, on Monday and afternoon time.* The numerical features like price, payment_value, freight_value,product_height_cm,product_length_cm doesnot seems to be helpful for this classification problem as observed from univariate and bivarate analysis.Also we can say linear model like KNN, Naive Bayes might not work well.* RMF Analysis is also done to understand whether new features can be created from this or not and we found that one numerical feature or categorical feature can be extracted from this." }, { "code": null, "e": 20089, "s": 19741, "text": "After the data analysis, we came to know about different categorical and numerical features. All categorical features seem to be preprocessed, we need not do preprocessing for these features. But, there is also a column named review_comment_message which contains text data. We have to do text preprocessing before the featurization of these data." }, { "code": null, "e": 20118, "s": 20089, "text": "Preprocessing of Review Text" }, { "code": null, "e": 20455, "s": 20118, "text": "Since we have text data in the Portuguese Language, we have to be careful while choosing stemmer, stopwords, and while replacing and removing any special character or any word. I selected nltk library for this and from this I have imported stopword using from nltk.corpus import stopwords and imported RSLP steamer using RSLPStemmer() ." }, { "code": null, "e": 20737, "s": 20455, "text": "As we replaced the null values in the reviews data with 'nao_reveja' we have to remove words like 'não' & 'nem' from the stopwords. After this, we have to remove or replace links, currency symbols, dates, digits, extra space, and tab e.t.c. The preprocess function is shown below-" }, { "code": null, "e": 20803, "s": 20737, "text": "Review text column before and after preprocessing is shown below-" }, { "code": null, "e": 20810, "s": 20803, "text": "Before" }, { "code": null, "e": 20816, "s": 20810, "text": "After" }, { "code": null, "e": 20843, "s": 20816, "text": "Vectorization of text data" }, { "code": null, "e": 21056, "s": 20843, "text": "Now, we have preprocessed text, for converting these text data I used FastText from gensim library to convert words into a vector with TF-IDF vectorizer().tfidf values give more weight to the most frequent words." }, { "code": null, "e": 21089, "s": 21056, "text": "The code snippet is shown below-" }, { "code": null, "e": 21130, "s": 21089, "text": "for loading FastText model (for 300 dim)" }, { "code": null, "e": 21152, "s": 21130, "text": "vectorizer function :" }, { "code": null, "e": 21278, "s": 21152, "text": "After this, the features which are not useful are dropped from the final data. The columns which are dropped are shown below." }, { "code": null, "e": 21823, "s": 21278, "text": "col= ['order_id', 'customer_id', 'order_purchase_timestamp', 'order_approved_at', 'order_delivered_customer_date', 'order_estimated_delivery_date', 'customer_unique_id', 'order_item_id', 'product_id', 'seller_id', 'shipping_limit_date', 'order_purchase_month_name', 'order_purchase_year_month', 'order_purchase_date', 'order_purchase_month_yr', 'order_purchase_day', 'order_purchase_dayofweek', 'order_purchase_dayofweek_name', 'order_purchase_hour','order_purchase_time_day','customer_city','customer_zip_code_prefix','product_category_name']" }, { "code": null, "e": 22232, "s": 21823, "text": "Now, we have our final data with preprocessed text data, categorical and numerical features. we can split the data using from sklearn.model_selection import train_test_split with stratify=y as we have imbalanced data. we also have categorical features which are not encoded yet. for encoding categorical features I used CountVectorizer(binary= True) function, encoding of order_status feature is shown below." }, { "code": null, "e": 22429, "s": 22232, "text": "The numerical features are also scaled using from sklearn.preprocessing import Normalizer .All the vectorized features are stacked using from scipy.sparse import hstack to form X_train and X_test." }, { "code": null, "e": 22454, "s": 22429, "text": "Baseline Model Selection" }, { "code": null, "e": 22859, "s": 22454, "text": "We have existing vectorized features now we will build few basic models and we will choose the one for our baseline model. After this, we will try to improve on the baseline by adding new features and to add new features I will again do some EDA. The models which are used are the random model, the Naive Bayes Model, and Logistic Regression Model. The output scores and confusion matrix are shown below." }, { "code": null, "e": 22872, "s": 22859, "text": "Random Model" }, { "code": null, "e": 22939, "s": 22872, "text": "Train f1-score 0.42757018716907186Test f1-score 0.4261466361217526" }, { "code": null, "e": 22951, "s": 22939, "text": "Naive Bayes" }, { "code": null, "e": 23021, "s": 22951, "text": "Train f1 score: 0.7424119484527338Test f1 score: 0.7472580717762947" }, { "code": null, "e": 23041, "s": 23021, "text": "Logistic Regression" }, { "code": null, "e": 23111, "s": 23041, "text": "Train f1 score: 0.8165306456031154Test f1 score: 0.8062989397776499" }, { "code": null, "e": 23475, "s": 23111, "text": "The logistic Regression Model is performing better than the other models. The logistic Regression Model is chosen as a baseline model. From both the train and test confusion matrix, we can observe that the False Positive and False Negative values are still very large let's try to reduce these values by adding some features and through feature selection methods." }, { "code": null, "e": 23495, "s": 23475, "text": "Feature Engineering" }, { "code": null, "e": 23617, "s": 23495, "text": "Along with the existing features,16 new features are added to the data. The details about these features are shown below." }, { "code": null, "e": 23870, "s": 23617, "text": "After adding new features, we have a total of 29 numerical features and 5 categorical features, and text data(300 dim). we will again run the selected baseline model i.e Logistic Regression Model and check the output from it. The output is shown below." }, { "code": null, "e": 23940, "s": 23870, "text": "Train f1 score: 0.8258929671475947Test f1 score: 0.8167104393178897" }, { "code": null, "e": 24121, "s": 23940, "text": "We got the better train and test f1-scores but still, we have high FP and FN values. To reduce these values and increase the scores I tried Autoencoder Model for feature selection." }, { "code": null, "e": 24174, "s": 24121, "text": "Feature Extraction/Selection using AutoEncoder Model" }, { "code": null, "e": 24573, "s": 24174, "text": "Autoencoder is a type of neural network that can be used to learn a compressed(reduced dimension) representation of raw data. An autoencoder is composed of an encoder and a decoder sub-models. The encoder compresses the input and the decoder attempts to recreate the input from the compressed version provided by the encoder. After training, the encoder model is saved and the decoder is discarded." }, { "code": null, "e": 24812, "s": 24573, "text": "The encoder can then be used as a data preparation technique to perform feature extraction on raw data that can be used to train a different machine learning model. source-https://machinelearningmastery.com/autoencoder-for-classification/" }, { "code": null, "e": 24944, "s": 24812, "text": "The architecture of the model is shown below. I used a dense layer, BatchNormalisation Layer, and leakyRelu as an activation layer." }, { "code": null, "e": 25030, "s": 24944, "text": "I ran this model for 10 epochs, and after running the model I saved the encoder part." }, { "code": null, "e": 25050, "s": 25030, "text": "Loss Vs Epoch graph" }, { "code": null, "e": 25113, "s": 25050, "text": "Then, important features are extracted from the encoder model." }, { "code": null, "e": 25127, "s": 25113, "text": "code snippet:" }, { "code": null, "e": 25220, "s": 25127, "text": "The baseline line model is run again with the extracted features. The output is shown below." }, { "code": null, "e": 25290, "s": 25220, "text": "Train f1 score: 0.8457608492913875Test f1 score: 0.8117963347711852" }, { "code": null, "e": 25471, "s": 25290, "text": "The f1-score is increased and also we got decreased FP and FN values. We will now run different machine learning and deep learning models and select the best model for our problem." }, { "code": null, "e": 25910, "s": 25471, "text": "Model selection is the process of choosing one of the models as the final model that addresses the problem. As we have seen the baseline model performance, now to improve the scores we will try the model selection process for both different types of models (e.g. logistic regression, SVM, KNN, Decision Trees, Ensembles, etc.) and models of the same type configured with different model hyperparameters (e.g. different kernels in an SVM)." }, { "code": null, "e": 25934, "s": 25910, "text": "Machine Learning Models" }, { "code": null, "e": 26087, "s": 25934, "text": "We start with different classification models to Neural Network models. The models that we are experimented with within this case study are as follows:-" }, { "code": null, "e": 26275, "s": 26087, "text": "Logistic RegressionLinear Support Vector MachineDecision Tree ClassifierRandom Forest ClassifierBoosting Classifier (XGBoost/LightGBM/AdaBoost/CATBoost)Stacking/Voting Ensemble techniques" }, { "code": null, "e": 26295, "s": 26275, "text": "Logistic Regression" }, { "code": null, "e": 26325, "s": 26295, "text": "Linear Support Vector Machine" }, { "code": null, "e": 26350, "s": 26325, "text": "Decision Tree Classifier" }, { "code": null, "e": 26375, "s": 26350, "text": "Random Forest Classifier" }, { "code": null, "e": 26432, "s": 26375, "text": "Boosting Classifier (XGBoost/LightGBM/AdaBoost/CATBoost)" }, { "code": null, "e": 26468, "s": 26432, "text": "Stacking/Voting Ensemble techniques" }, { "code": null, "e": 26633, "s": 26468, "text": "For each model, I did hyperparameter tuning using RandomizedSearchCV .The summary of all the outputs with the best hyperparameters of all the models is shown below." }, { "code": null, "e": 26750, "s": 26633, "text": "We can observe the best model based on the test f1-score is vot_hard the code snippet and the output is shown below." }, { "code": null, "e": 26800, "s": 26750, "text": "Code snippet of all the models can be found here-" }, { "code": null, "e": 26810, "s": 26800, "text": "jovian.ai" }, { "code": null, "e": 26831, "s": 26810, "text": "Deep Learning Models" }, { "code": null, "e": 27019, "s": 26831, "text": "As we have seen different machine learning models, now we will try different neural network models. I tried 5 different models and used these models to form deep learning stacking models." }, { "code": null, "e": 27027, "s": 27019, "text": "Model-1" }, { "code": null, "e": 27321, "s": 27027, "text": "In Model-1 I build a simple model with 5 dense layers as hidden layers and 1 dense layer as output layer. At the output layer sigmoid as the activation function is used. The input given is the extracted features from the encoder model. I used a custom f1-score metric to evaluate these models." }, { "code": null, "e": 27340, "s": 27321, "text": "Model Architecture" }, { "code": null, "e": 27359, "s": 27340, "text": "Epoch Vs Loss Plot" }, { "code": null, "e": 27366, "s": 27359, "text": "Output" }, { "code": null, "e": 27434, "s": 27366, "text": "Train f1_score: 0.8632763852422476Test f1_score: 0.8218909906703276" }, { "code": null, "e": 27442, "s": 27434, "text": "Model-2" }, { "code": null, "e": 27749, "s": 27442, "text": "In Model- 2 I used 4 CONV1D layers,2 MaxPooling1D layers with one dropout and one flatten layer as hidden layers, and 1 dense layer as output layer. At the output layer sigmoid as the activation function is used. The input given is the extracted features from the encoder model but with the reshaped array." }, { "code": null, "e": 27768, "s": 27749, "text": "Model Architecture" }, { "code": null, "e": 27782, "s": 27768, "text": "Epoch Vs Loss" }, { "code": null, "e": 27789, "s": 27782, "text": "Output" }, { "code": null, "e": 27858, "s": 27789, "text": "Train f1_score: 0.8610270746182962 Test f1_score: 0.8253479131333611" }, { "code": null, "e": 27866, "s": 27858, "text": "Model-3" }, { "code": null, "e": 28072, "s": 27866, "text": "In Model -3 I used LSTM Layer, embedding layer, BatchNormalisation layer, dense layer, dropout, and flatten layer to build the model with multiple inputs and one output. The input data are explained below." }, { "code": null, "e": 28322, "s": 28072, "text": "Input_seq_total_text_data- I used the Embedding layer to get word vectors for the text data columns. I also used predefined fasttext word vectors for creating an embedding matrix. After this used LSTM and got the LSTM output and Flatten that output." }, { "code": null, "e": 28440, "s": 28322, "text": "Input_order_status- given order_status column as input to embedding layer and then trained the Keras Embedding layer." }, { "code": null, "e": 28547, "s": 28440, "text": "payment_type- given payment_type column as input to embedding layer and trained the Keras Embedding layer." }, { "code": null, "e": 28664, "s": 28547, "text": "Input_customer_state- given customer_state column as input to embedding layer and trained the Keras Embedding layer." }, { "code": null, "e": 28785, "s": 28664, "text": "Input_product_category- given product_category column as input to embedding layer and trained the Keras Embedding layer." }, { "code": null, "e": 28887, "s": 28785, "text": "Input_rfm - given RFM_Level column as input to embedding layer and trained the Keras Embedding layer." }, { "code": null, "e": 28993, "s": 28887, "text": "Input_numerical- concatenate remaining columns i.e numerical features and added a Dense layer after that." }, { "code": null, "e": 29074, "s": 28993, "text": "All these are concatenated at the end and passed through different dense layers." }, { "code": null, "e": 29093, "s": 29074, "text": "Model Architecture" }, { "code": null, "e": 29107, "s": 29093, "text": "Epoch Vs Loss" }, { "code": null, "e": 29114, "s": 29107, "text": "Output" }, { "code": null, "e": 29182, "s": 29114, "text": "Train f1_score: 0.860330602322043 Test f1_score: 0.8327277576694923" }, { "code": null, "e": 29190, "s": 29182, "text": "Model-4" }, { "code": null, "e": 29403, "s": 29190, "text": "Model -4 also used LSTM Layer, Conv1D, embedding layer, BatchNormalisation layer, dense layer, dropout, and flatten layer to build the model but with two inputs and one output. The input data are explained below." }, { "code": null, "e": 29654, "s": 29403, "text": "Input_seq_total_text_data- I used the Embedding layer to get word vectors for the text data columns. I also used predefined fast text word vectors for creating an embedding matrix. After this used LSTM and got the LSTM output and Flatten that output." }, { "code": null, "e": 29812, "s": 29654, "text": "Other_than_text_data- All categorical features are converted to a one-hot encoded vector and then concatenated along with numerical features using np. hstack" }, { "code": null, "e": 29831, "s": 29812, "text": "Model Architecture" }, { "code": null, "e": 29845, "s": 29831, "text": "Epoch Vs Loss" }, { "code": null, "e": 29852, "s": 29845, "text": "Output" }, { "code": null, "e": 29921, "s": 29852, "text": "Train f1_score: 0.8815188513597205 Test f1_score: 0.8218441232242646" }, { "code": null, "e": 29929, "s": 29921, "text": "Model-5" }, { "code": null, "e": 30146, "s": 29929, "text": "Model -5 also used LSTM Layer, Conv1D, embedding layer, BatchNormalisation layer, dense layer, dropout, and flatten layer to build the model but with two inputs and one output. The input data are the same as model 4." }, { "code": null, "e": 30165, "s": 30146, "text": "Model Architecture" }, { "code": null, "e": 30179, "s": 30165, "text": "Epoch Vs Loss" }, { "code": null, "e": 30186, "s": 30179, "text": "Output" }, { "code": null, "e": 30254, "s": 30186, "text": "Train f1_score: 0.8508463263785984Test f1_score: 0.8287339894123904" }, { "code": null, "e": 30283, "s": 30254, "text": "Deep Learning Stacking Model" }, { "code": null, "e": 30756, "s": 30283, "text": "As we have seen 5 deep learning models now we will use an ensemble method where the above 5 models are used as sub-models and each will contribute equally to the combined prediction and XGBClassifier is used as the final model i.e meta-model. We will build two stacking models one with hard stacking another with soft stacking and the output will be compared with the above model’s output. The code snippet for each step for building both hard and stacking is shown below." }, { "code": null, "e": 30787, "s": 30756, "text": "step-1 Loading five sub-models" }, { "code": null, "e": 30822, "s": 30787, "text": "step-2 Predictions From each model" }, { "code": null, "e": 30893, "s": 30822, "text": "step-3 Stacking the Predictions and passed through the meta-classifier" }, { "code": null, "e": 30907, "s": 30893, "text": "Hard Stacking" }, { "code": null, "e": 30916, "s": 30907, "text": "Output :" }, { "code": null, "e": 30930, "s": 30916, "text": "Soft Stacking" }, { "code": null, "e": 30938, "s": 30930, "text": "Output:" }, { "code": null, "e": 31121, "s": 30938, "text": "As we can observe the outputs of both stacking models are performing better than the above deep learning models. The code snippets of all the deep learning models can be found here —" }, { "code": null, "e": 31131, "s": 31121, "text": "jovian.ai" }, { "code": null, "e": 31347, "s": 31131, "text": "From EDA we concluded that the given dataset is skewed and with correlation values, we have seen most of the numerical features are not linearly related which means that simple ml classification might not work well." }, { "code": null, "e": 31561, "s": 31347, "text": "The review data are in text form we did preprocess of these data and also the addition of new features helped improve the scores. The autoencoder model helped more in feature selection and performance enhancement." }, { "code": null, "e": 31836, "s": 31561, "text": "In the model selection part, we have gone through different ml model and dl model performances. After comparing all the results we can conclude that the model is a deep learning stacking model i.e soft stacking model. Now we will use this model while the deployment process." }, { "code": null, "e": 32139, "s": 31836, "text": "The best stacked deep learning model is deployed using streamlit and Github. Using streamlit uploader function I created a CSV file input section where you can give raw data. After that, you have to choose the unique customer id and corresponding order ids and the prediction will be shown as an image." }, { "code": null, "e": 32153, "s": 32139, "text": "webpage link-" }, { "code": null, "e": 32241, "s": 32153, "text": "https://share.streamlit.io/paritoshmahto07/customer-satisfaction-prediction/main/app.py" }, { "code": null, "e": 32259, "s": 32241, "text": "Deployment Video-" }, { "code": null, "e": 32740, "s": 32259, "text": "In the Existing approach, two regression models are used with nine new features for the prediction of review scores got RMSE of 0.58. In the existing approach, different models are also not used, and also limited features are used. In our approach that we followed had achieved a very good result than the existing approach and also we used a new text featurization method along with an autoencoder model for feature selection due to which the performance of the models increased." }, { "code": null, "e": 32946, "s": 32740, "text": "The vectorization of the Portuguese text data with different methods can improve the result. Also, the Addition of new features and parameter tuning of the DL models can be done to achieve a better result." }, { "code": null, "e": 32966, "s": 32946, "text": "My LinkedIn Profile" }, { "code": null, "e": 33006, "s": 32966, "text": "https://www.linkedin.com/in/paritosh07/" }, { "code": null, "e": 33024, "s": 33006, "text": "My Github Profile" }, { "code": null, "e": 33035, "s": 33024, "text": "github.com" }, { "code": null, "e": 33056, "s": 33035, "text": "i.Existing Solution-" }, { "code": null, "e": 33071, "s": 33056, "text": "www.kaggle.com" }, { "code": null, "e": 33108, "s": 33071, "text": "ii. Data Analysis and Visualisation-" }, { "code": null, "e": 33123, "s": 33108, "text": "www.kaggle.com" }, { "code": null, "e": 33142, "s": 33123, "text": "iii. RFM Analysis-" }, { "code": null, "e": 33165, "s": 33142, "text": "towardsdatascience.com" }, { "code": null, "e": 33187, "s": 33165, "text": "iv. Autoencoder Model" }, { "code": null, "e": 33214, "s": 33187, "text": "machinelearningmastery.com" }, { "code": null, "e": 33236, "s": 33214, "text": "v. Stacking ML Models" }, { "code": null, "e": 33263, "s": 33236, "text": "machinelearningmastery.com" }, { "code": null, "e": 33286, "s": 33263, "text": "vi. Stacking DL Models" }, { "code": null, "e": 33313, "s": 33286, "text": "machinelearningmastery.com" }, { "code": null, "e": 33329, "s": 33313, "text": "vii. Mentorship" }, { "code": null, "e": 33353, "s": 33329, "text": "www.appliedaicourse.com" } ]
How to maximize and minimize browsers in Selenium with python?
We can maximize and minimize the browser while we are testing an application in Selenium. For maximizing the browser, maximize() method is to be used. For minimizing the browser, minimize() method is to be used. Both these methods can be used simultaneously in the same program. Code Implementation from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/index.htm") #to refresh the browser driver.refresh() # to minimize the browser window driver.minimize_window() #to close the browser driver.close()
[ { "code": null, "e": 1152, "s": 1062, "text": "We can maximize and minimize the browser while we are testing an application in Selenium." }, { "code": null, "e": 1213, "s": 1152, "text": "For maximizing the browser, maximize() method is to be used." }, { "code": null, "e": 1274, "s": 1213, "text": "For minimizing the browser, minimize() method is to be used." }, { "code": null, "e": 1341, "s": 1274, "text": "Both these methods can be used simultaneously in the same program." }, { "code": null, "e": 1361, "s": 1341, "text": "Code Implementation" }, { "code": null, "e": 1870, "s": 1361, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# to minimize the browser window\ndriver.minimize_window()\n#to close the browser\ndriver.close()" } ]
Assign multiple variables with a Python list values
Depending on the need of the program we may an requirement of assigning the values in a list to many variables at once. So that they can be further used for calculations in the rest of the part of the program. In this article we will explore various approaches to achieve this. The for loop can help us iterate through the elements of the given list while assigning them to the variables declared in a given sequence.We have to mention the index position of values which will get assigned to the variables. Live Demo listA = ['Mon', ' 2pm', 1.5, '11 miles'] # Given list print("Given list A: " ,listA) # using for in vDay, vHrs, vDist = [listA[i] for i in (0, 2, 3)] # Result print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist) Running the above code gives us the following result − Given list A: ['Mon', ' 2pm', 1.5, '11 miles'] The variables : Mon, 1.5, 11 miles The itergetter function from the operator module will fetch the item for specified indexes. We directly assign them to the variables. Live Demo from operator import itemgetter listA = ['Mon', ' 2pm', 1.5, '11 miles'] # Given list print("Given list A: " ,listA) # using itemgetter vDay, vHrs, vDist = itemgetter(0, 2, 3)(listA) # Result print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist) Running the above code gives us the following result − Given list A: ['Mon', ' 2pm', 1.5, '11 miles'] The variables : Mon, 1.5, 11 miles The compress function from itertools module will catch the elements by using the Boolean values for index positions. So for index position 0,2 and 3 we mention the value 1 in the compress function and then assign the fetched value to the variables. Live Demo from itertools import compress listA = ['Mon', ' 2pm', 1.5, '11 miles'] # Given list print("Given list A: " ,listA) # using itemgetter vDay, vHrs, vDist = compress(listA, (1, 0,1, 1)) # Result print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist) Running the above code gives us the following result − Given list A: ['Mon', ' 2pm', 1.5, '11 miles'] The variables : Mon, 1.5, 11 miles
[ { "code": null, "e": 1340, "s": 1062, "text": "Depending on the need of the program we may an requirement of assigning the values in a list to many variables at once. So that they can be further used for calculations in the rest of the part of the program. In this article we will explore various approaches to achieve this." }, { "code": null, "e": 1569, "s": 1340, "text": "The for loop can help us iterate through the elements of the given list while assigning them to the variables declared in a given sequence.We have to mention the index position of values which will get assigned to the variables." }, { "code": null, "e": 1580, "s": 1569, "text": " Live Demo" }, { "code": null, "e": 1809, "s": 1580, "text": "listA = ['Mon', ' 2pm', 1.5, '11 miles']\n\n# Given list\nprint(\"Given list A: \" ,listA)\n\n# using for in\nvDay, vHrs, vDist = [listA[i] for i in (0, 2, 3)]\n\n# Result\nprint (\"The variables : \" + vDay + \", \" + str(vHrs) + \", \" +vDist)" }, { "code": null, "e": 1864, "s": 1809, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1946, "s": 1864, "text": "Given list A: ['Mon', ' 2pm', 1.5, '11 miles']\nThe variables : Mon, 1.5, 11 miles" }, { "code": null, "e": 2080, "s": 1946, "text": "The itergetter function from the operator module will fetch the item for specified indexes. We directly assign them to the variables." }, { "code": null, "e": 2091, "s": 2080, "text": " Live Demo" }, { "code": null, "e": 2355, "s": 2091, "text": "from operator import itemgetter\n\nlistA = ['Mon', ' 2pm', 1.5, '11 miles']\n\n# Given list\nprint(\"Given list A: \" ,listA)\n\n\n# using itemgetter\nvDay, vHrs, vDist = itemgetter(0, 2, 3)(listA)\n\n# Result\nprint (\"The variables : \" + vDay + \", \" + str(vHrs) + \", \" +vDist)" }, { "code": null, "e": 2410, "s": 2355, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2492, "s": 2410, "text": "Given list A: ['Mon', ' 2pm', 1.5, '11 miles']\nThe variables : Mon, 1.5, 11 miles" }, { "code": null, "e": 2741, "s": 2492, "text": "The compress function from itertools module will catch the elements by using the Boolean values for index positions. So for index position 0,2 and 3 we mention the value 1 in the compress function and then assign the fetched value to the variables." }, { "code": null, "e": 2752, "s": 2741, "text": " Live Demo" }, { "code": null, "e": 3016, "s": 2752, "text": "from itertools import compress\n\nlistA = ['Mon', ' 2pm', 1.5, '11 miles']\n\n# Given list\nprint(\"Given list A: \" ,listA)\n\n# using itemgetter\nvDay, vHrs, vDist = compress(listA, (1, 0,1, 1))\n\n# Result\nprint (\"The variables : \" + vDay + \", \" + str(vHrs) + \", \" +vDist)" }, { "code": null, "e": 3071, "s": 3016, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3153, "s": 3071, "text": "Given list A: ['Mon', ' 2pm', 1.5, '11 miles']\nThe variables : Mon, 1.5, 11 miles" } ]
Print all permutation of a string using ArrayList in Java
In this problem, we are given a string of size n and we have to print all permutations of the string. But this time we have to print this permutation using ArrayList. Let’s take an example to understand the problem - Input − string = ‘XYZ’ Output − XYZ, XZY, YXZ, YZX, ZXY, ZYX To solve this problem, we will be generating all permutations of the character of the string. We will use a recursive function and will return arrayList. The following is ArrayList implementation of the algorithm − Live Demo import java.util.ArrayList; public class Main{ static void printArrayList(ArrayList<String> combo) { combo.remove(""); for (int i = 0; i < combo.size(); i++) System.out.print(combo.get(i)+"\t"); } public static ArrayList<String> generatePermutation(String str) { if (str.length() == 0) { ArrayList<String> empty = new ArrayList<>(); empty.add(""); return empty; } char ch = str.charAt(0); String subStr = str.substring(1); ArrayList<String> lastCombination = generatePermutation(subStr); ArrayList<String> newCombination = new ArrayList<>(); for (String val : lastCombination) { for (int i = 0; i <= val.length(); i++) { newCombination.add(val.substring(0, i) + ch + val.substring(i)); } } return newCombination; } public static void main(String[] args) { String str = "NOPQ"; System.out.println("Permutations of string are :"); printArrayList(generatePermutation(str)); } } Permutations of string are : NOPQ ONPQ OPNQ OPQN NPOQ PNOQ PONQ POQN NPQO PNQO PQNO PQON NOQP ONQP OQNP OQPN NQOP QNOP QONP QOPN NQPO QNPO QPNO QPON
[ { "code": null, "e": 1229, "s": 1062, "text": "In this problem, we are given a string of size n and we have to print all permutations of the string. But this time we have to print this permutation using ArrayList." }, { "code": null, "e": 1279, "s": 1229, "text": "Let’s take an example to understand the problem -" }, { "code": null, "e": 1302, "s": 1279, "text": "Input − string = ‘XYZ’" }, { "code": null, "e": 1340, "s": 1302, "text": "Output − XYZ, XZY, YXZ, YZX, ZXY, ZYX" }, { "code": null, "e": 1494, "s": 1340, "text": "To solve this problem, we will be generating all permutations of the character of the string. We will use a recursive function and will return arrayList." }, { "code": null, "e": 1555, "s": 1494, "text": "The following is ArrayList implementation of the algorithm −" }, { "code": null, "e": 1566, "s": 1555, "text": " Live Demo" }, { "code": null, "e": 2605, "s": 1566, "text": "import java.util.ArrayList;\npublic class Main{\n static void printArrayList(ArrayList<String> combo) {\n combo.remove(\"\");\n for (int i = 0; i < combo.size(); i++)\n System.out.print(combo.get(i)+\"\\t\");\n }\n public static ArrayList<String> generatePermutation(String str) {\n if (str.length() == 0) {\n ArrayList<String> empty = new ArrayList<>();\n empty.add(\"\");\n return empty;\n }\n char ch = str.charAt(0);\n String subStr = str.substring(1);\n ArrayList<String> lastCombination = generatePermutation(subStr);\n ArrayList<String> newCombination = new ArrayList<>();\n for (String val : lastCombination) {\n for (int i = 0; i <= val.length(); i++) {\n newCombination.add(val.substring(0, i) + ch + val.substring(i));\n }\n }\n return newCombination;\n }\n public static void main(String[] args) {\n String str = \"NOPQ\";\n System.out.println(\"Permutations of string are :\");\n printArrayList(generatePermutation(str));\n }\n}" }, { "code": null, "e": 2754, "s": 2605, "text": "Permutations of string are :\nNOPQ ONPQ OPNQ OPQN NPOQ PNOQ\nPONQ POQN NPQO PNQO PQNO\nPQON NOQP ONQP OQNP OQPN\nNQOP QNOP QONP QOPN NQPO\nQNPO QPNO QPON" } ]
SymPy - Entities
The geometry module in SymPy allows creation of two dimensional entities such as line, circle, etc. We can then obtain information about them such as checking colinearity or finding intersection. Point class represents a point in Euclidean space. Following example checks for collinearity of points − >>> from sympy.geometry import Point >>> from sympy import * >>> x=Point(0,0) >>> y=Point(2,2) >>> z=Point(4,4) >>> Point.is_collinear(x,y,z) Output True >>> a=Point(2,3) >>> Point.is_collinear(x,y,a) Output False The distance() method of Point class calculates distance between two points >>> x.distance(y) Output 22 The distance may also be represented in terms of symbols. Line entity is obtained from two Point objects. The intersection() method returns point of intersection if two lines intersect each other. >>> from sympy.geometry import Point, Line >>> p1, p2=Point(0,5), Point(5,0) >>> l1=Line(p1,p2) >>> l2=Line(Point(0,0), Point(5,5)) >>> l1.intersection(l2) Output [Point2D(5/2, 5/2)] >>> l1.intersection(Line(Point(0,0), Point(2,2))) Output [Point2D(5/2, 5/2)] >>> x,y=symbols('x y') >>> p=Point(x,y) >>> p.distance(Point(0,0)) Output x2+y2 This function builds a triangle entity from three point objects. Triangle(a,b,c) >>> t=Triangle(Point(0,0),Point(0,5), Point(5,0)) >>> t.area Output −252 An elliptical geometry entity is constructed by passing a Point object corresponding to center and two numbers each for horizontal and vertical radius. ellipse(center, hradius, vradius) >>> from sympy.geometry import Ellipse, Line >>> e=Ellipse(Point(0,0),8,3) >>> e.area Output 24π The vradius can be indirectly provided by using eccentricity parameter. >>> e1=Ellipse(Point(2,2), hradius=5, eccentricity=Rational(3,4)) >>> e1.vradius Output 574 The apoapsis of the ellipse is the greatest distance between the focus and the contour. >>> e1.apoapsis Output 354 Following statement calculates circumference of ellipse − >>> e1.circumference Output 20E(916) The equation method of ellipse returns equation of ellipse. >>> e1.equation(x,y) Output (x5−25)2+16(y−2)2175−1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2215, "s": 2019, "text": "The geometry module in SymPy allows creation of two dimensional entities such as line, circle, etc. We can then obtain information about them such as checking colinearity or finding intersection." }, { "code": null, "e": 2320, "s": 2215, "text": "Point class represents a point in Euclidean space. Following example checks for collinearity of points −" }, { "code": null, "e": 2468, "s": 2320, "text": ">>> from sympy.geometry import Point \n>>> from sympy import * \n>>> x=Point(0,0) \n>>> y=Point(2,2) \n>>> z=Point(4,4) \n>>> Point.is_collinear(x,y,z)\n" }, { "code": null, "e": 2475, "s": 2468, "text": "Output" }, { "code": null, "e": 2480, "s": 2475, "text": "True" }, { "code": null, "e": 2529, "s": 2480, "text": ">>> a=Point(2,3) \n>>> Point.is_collinear(x,y,a)\n" }, { "code": null, "e": 2536, "s": 2529, "text": "Output" }, { "code": null, "e": 2542, "s": 2536, "text": "False" }, { "code": null, "e": 2618, "s": 2542, "text": "The distance() method of Point class calculates distance between two points" }, { "code": null, "e": 2637, "s": 2618, "text": ">>> x.distance(y)\n" }, { "code": null, "e": 2644, "s": 2637, "text": "Output" }, { "code": null, "e": 2647, "s": 2644, "text": "22" }, { "code": null, "e": 2705, "s": 2647, "text": "The distance may also be represented in terms of symbols." }, { "code": null, "e": 2844, "s": 2705, "text": "Line entity is obtained from two Point objects. The intersection() method returns point of intersection if two lines intersect each other." }, { "code": null, "e": 3004, "s": 2844, "text": ">>> from sympy.geometry import Point, Line \n>>> p1, p2=Point(0,5), Point(5,0) \n>>> l1=Line(p1,p2)\n>>> l2=Line(Point(0,0), Point(5,5)) \n>>> l1.intersection(l2)\n" }, { "code": null, "e": 3011, "s": 3004, "text": "Output" }, { "code": null, "e": 3031, "s": 3011, "text": "[Point2D(5/2, 5/2)]" }, { "code": null, "e": 3082, "s": 3031, "text": ">>> l1.intersection(Line(Point(0,0), Point(2,2)))\n" }, { "code": null, "e": 3089, "s": 3082, "text": "Output" }, { "code": null, "e": 3109, "s": 3089, "text": "[Point2D(5/2, 5/2)]" }, { "code": null, "e": 3179, "s": 3109, "text": ">>> x,y=symbols('x y') \n>>> p=Point(x,y) \n>>> p.distance(Point(0,0))\n" }, { "code": null, "e": 3186, "s": 3179, "text": "Output" }, { "code": null, "e": 3192, "s": 3186, "text": "x2+y2" }, { "code": null, "e": 3257, "s": 3192, "text": "This function builds a triangle entity from three point objects." }, { "code": null, "e": 3273, "s": 3257, "text": "Triangle(a,b,c)" }, { "code": null, "e": 3336, "s": 3273, "text": ">>> t=Triangle(Point(0,0),Point(0,5), Point(5,0)) \n>>> t.area\n" }, { "code": null, "e": 3343, "s": 3336, "text": "Output" }, { "code": null, "e": 3348, "s": 3343, "text": "−252" }, { "code": null, "e": 3500, "s": 3348, "text": "An elliptical geometry entity is constructed by passing a Point object corresponding to center and two numbers each for horizontal and vertical radius." }, { "code": null, "e": 3534, "s": 3500, "text": "ellipse(center, hradius, vradius)" }, { "code": null, "e": 3623, "s": 3534, "text": ">>> from sympy.geometry import Ellipse, Line \n>>> e=Ellipse(Point(0,0),8,3) \n>>> e.area\n" }, { "code": null, "e": 3630, "s": 3623, "text": "Output" }, { "code": null, "e": 3634, "s": 3630, "text": "24π" }, { "code": null, "e": 3706, "s": 3634, "text": "The vradius can be indirectly provided by using eccentricity parameter." }, { "code": null, "e": 3789, "s": 3706, "text": ">>> e1=Ellipse(Point(2,2), hradius=5, eccentricity=Rational(3,4)) \n>>> e1.vradius\n" }, { "code": null, "e": 3796, "s": 3789, "text": "Output" }, { "code": null, "e": 3800, "s": 3796, "text": "574" }, { "code": null, "e": 3888, "s": 3800, "text": "The apoapsis of the ellipse is the greatest distance between the focus and the contour." }, { "code": null, "e": 3905, "s": 3888, "text": ">>> e1.apoapsis\n" }, { "code": null, "e": 3912, "s": 3905, "text": "Output" }, { "code": null, "e": 3916, "s": 3912, "text": "354" }, { "code": null, "e": 3974, "s": 3916, "text": "Following statement calculates circumference of ellipse −" }, { "code": null, "e": 3996, "s": 3974, "text": ">>> e1.circumference\n" }, { "code": null, "e": 4003, "s": 3996, "text": "Output" }, { "code": null, "e": 4012, "s": 4003, "text": "20E(916)" }, { "code": null, "e": 4072, "s": 4012, "text": "The equation method of ellipse returns equation of ellipse." }, { "code": null, "e": 4094, "s": 4072, "text": ">>> e1.equation(x,y)\n" }, { "code": null, "e": 4101, "s": 4094, "text": "Output" }, { "code": null, "e": 4124, "s": 4101, "text": "(x5−25)2+16(y−2)2175−1" }, { "code": null, "e": 4131, "s": 4124, "text": " Print" }, { "code": null, "e": 4142, "s": 4131, "text": " Add Notes" } ]
What is ({$natural: 1}) in MongoDB?
The ({$natural − 1}) works like LIFO(LAST IN FIRST OUT), that means last inserted document will be shown first. Let us create a collection with documents − > db.demo614.insertOne({"CountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5e988cddf6b89257f5584d8e") } > db.demo614.insertOne({"CountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5e988ce0f6b89257f5584d8f") } > db.demo614.insertOne({"CountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5e988ce3f6b89257f5584d90") } > db.demo614.insertOne({"CountryName":"IND"}); { "acknowledged" : true, "insertedId" : ObjectId("5e988cebf6b89257f5584d91") } Display all documents from a collection with the help of find() method − > db.demo614.find(); This will produce the following output − { "_id" : ObjectId("5e988cddf6b89257f5584d8e"), "CountryName" : "US" } { "_id" : ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName" : "UK" } { "_id" : ObjectId("5e988ce3f6b89257f5584d90"), "CountryName" : "AUS" } { "_id" : ObjectId("5e988cebf6b89257f5584d91"), "CountryName" : "IND" } Following is the query to work with ({$natural: 1}) − > db.demo614.find().sort({$natural:-1}) This will produce the following output − { "_id" : ObjectId("5e988cebf6b89257f5584d91"), "CountryName" : "IND" } { "_id" : ObjectId("5e988ce3f6b89257f5584d90"), "CountryName" : "AUS" } { "_id" : ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName" : "UK" } { "_id" : ObjectId("5e988cddf6b89257f5584d8e"), "CountryName" : "US" }
[ { "code": null, "e": 1174, "s": 1062, "text": "The ({$natural − 1}) works like LIFO(LAST IN FIRST OUT), that means last inserted document will be shown first." }, { "code": null, "e": 1218, "s": 1174, "text": "Let us create a collection with documents −" }, { "code": null, "e": 1744, "s": 1218, "text": "> db.demo614.insertOne({\"CountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e988cddf6b89257f5584d8e\")\n}\n> db.demo614.insertOne({\"CountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e988ce0f6b89257f5584d8f\")\n}\n> db.demo614.insertOne({\"CountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e988ce3f6b89257f5584d90\")\n}\n> db.demo614.insertOne({\"CountryName\":\"IND\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e988cebf6b89257f5584d91\")\n}" }, { "code": null, "e": 1817, "s": 1744, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1838, "s": 1817, "text": "> db.demo614.find();" }, { "code": null, "e": 1879, "s": 1838, "text": "This will produce the following output −" }, { "code": null, "e": 2165, "s": 1879, "text": "{ \"_id\" : ObjectId(\"5e988cddf6b89257f5584d8e\"), \"CountryName\" : \"US\" }\n{ \"_id\" : ObjectId(\"5e988ce0f6b89257f5584d8f\"), \"CountryName\" : \"UK\" }\n{ \"_id\" : ObjectId(\"5e988ce3f6b89257f5584d90\"), \"CountryName\" : \"AUS\" }\n{ \"_id\" : ObjectId(\"5e988cebf6b89257f5584d91\"), \"CountryName\" : \"IND\" }" }, { "code": null, "e": 2219, "s": 2165, "text": "Following is the query to work with ({$natural: 1}) −" }, { "code": null, "e": 2259, "s": 2219, "text": "> db.demo614.find().sort({$natural:-1})" }, { "code": null, "e": 2300, "s": 2259, "text": "This will produce the following output −" }, { "code": null, "e": 2586, "s": 2300, "text": "{ \"_id\" : ObjectId(\"5e988cebf6b89257f5584d91\"), \"CountryName\" : \"IND\" }\n{ \"_id\" : ObjectId(\"5e988ce3f6b89257f5584d90\"), \"CountryName\" : \"AUS\" }\n{ \"_id\" : ObjectId(\"5e988ce0f6b89257f5584d8f\"), \"CountryName\" : \"UK\" }\n{ \"_id\" : ObjectId(\"5e988cddf6b89257f5584d8e\"), \"CountryName\" : \"US\" }" } ]
Gson - First Application
Before going into the details of the Google Gson library, let's see an application in action. In this example, we've created a Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE. File − GsonTester.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonTester { public static void main(String[] args) { String jsonString = "{\"name\":\"Mahesh\", \"age\":21}"; GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create(); Student student = gson.fromJson(jsonString, Student.class); System.out.println(student); jsonString = gson.toJson(student); System.out.println(jsonString); } } class Student { private String name; private int age; public Student(){} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Student [ name: "+name+", age: "+ age+ " ]"; } } Compile the classes using javac compiler as follows − C:\GSON_WORKSPACE>javac GsonTester.java Now run the GsonTester to see the result − C:\GSON_WORKSPACE>java GsonTester Verify the output. Student [ name: Mahesh, age: 21 ] { "name" : "Mahesh", "age" : 21 } Following are the important steps to be considered here. Create a Gson object. It is a reusable object. GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create(); Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter. //Object to JSON Conversion Student student = gson.fromJson(jsonString, Student.class); Use toJson() method to get the JSON string representation of an object. //Object to JSON Conversion jsonString = gson.toJson(student); Print Add Notes Bookmark this page
[ { "code": null, "e": 2200, "s": 1932, "text": "Before going into the details of the Google Gson library, let's see an application in action. In this example, we've created a Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String." }, { "code": null, "e": 2265, "s": 2200, "text": "Create a Java class file named GsonTester in C:\\>GSON_WORKSPACE." }, { "code": null, "e": 2288, "s": 2265, "text": "File − GsonTester.java" }, { "code": null, "e": 3276, "s": 2288, "text": "import com.google.gson.Gson; \nimport com.google.gson.GsonBuilder; \n\npublic class GsonTester { \n public static void main(String[] args) { \n String jsonString = \"{\\\"name\\\":\\\"Mahesh\\\", \\\"age\\\":21}\"; \n \n GsonBuilder builder = new GsonBuilder(); \n builder.setPrettyPrinting(); \n \n Gson gson = builder.create(); \n Student student = gson.fromJson(jsonString, Student.class); \n System.out.println(student); \n \n jsonString = gson.toJson(student); \n System.out.println(jsonString); \n } \n} \n\nclass Student { \n private String name; \n private int age; \n public Student(){} \n \n public String getName() { \n return name; \n }\n \n public void setName(String name) { \n this.name = name; \n } \n \n public int getAge() { \n return age; \n }\n \n public void setAge(int age) { \n this.age = age; \n }\n \n public String toString() { \n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\"; \n } \n}" }, { "code": null, "e": 3330, "s": 3276, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 3371, "s": 3330, "text": "C:\\GSON_WORKSPACE>javac GsonTester.java\n" }, { "code": null, "e": 3414, "s": 3371, "text": "Now run the GsonTester to see the result −" }, { "code": null, "e": 3449, "s": 3414, "text": "C:\\GSON_WORKSPACE>java GsonTester\n" }, { "code": null, "e": 3468, "s": 3449, "text": "Verify the output." }, { "code": null, "e": 3547, "s": 3468, "text": "Student [ name: Mahesh, age: 21 ] \n{ \n \"name\" : \"Mahesh\", \n \"age\" : 21 \n}\n" }, { "code": null, "e": 3604, "s": 3547, "text": "Following are the important steps to be considered here." }, { "code": null, "e": 3651, "s": 3604, "text": "Create a Gson object. It is a reusable object." }, { "code": null, "e": 3754, "s": 3651, "text": "GsonBuilder builder = new GsonBuilder(); \nbuilder.setPrettyPrinting(); \nGson gson = builder.create();\n" }, { "code": null, "e": 3880, "s": 3754, "text": "Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter." }, { "code": null, "e": 3970, "s": 3880, "text": "//Object to JSON Conversion \nStudent student = gson.fromJson(jsonString, Student.class);\n" }, { "code": null, "e": 4042, "s": 3970, "text": "Use toJson() method to get the JSON string representation of an object." }, { "code": null, "e": 4110, "s": 4042, "text": "//Object to JSON Conversion \njsonString = gson.toJson(student); \n" }, { "code": null, "e": 4117, "s": 4110, "text": " Print" }, { "code": null, "e": 4128, "s": 4117, "text": " Add Notes" } ]
How to create a popup chat window with CSS and JavaScript?
To create popup chat window with CSS and JavaScript, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } * { box-sizing: border-box; } .openChatBtn { background-color: rgb(123, 28, 179); color: white; padding: 16px 20px; border: none; font-weight: 500; font-size: 18px; cursor: pointer; opacity: 0.8; position: fixed; bottom: 23px; right: 28px; width: 280px; } .openChat { display: none; position: fixed; bottom: 0; right: 15px; border: 3px solid #ff08086b; z-index: 9; } form { max-width: 300px; padding: 10px; background-color: white; } form textarea { width: 100%; font-size: 18px; padding: 15px; margin: 5px 0 22px 0; border: none; font-weight: 500; background: #d5e7ff; color: rgb(0, 0, 0); resize: none; min-height: 200px; } form textarea:focus { background-color: rgb(219, 255, 252); outline: none; } form .btn { background-color: rgb(34, 197, 107); color: white; padding: 16px 20px; font-weight: bold; border: none; cursor: pointer; width: 100%; margin-bottom: 10px; opacity: 0.8; } form .close { background-color: red; } form .btn:hover, .openChatBtn:hover { opacity: 1; } </style> </head> <body> <h1>Popup Chat Window Example</h1> <h2>Click the below button to start chatting</h2> <button class="openChatBtn" onclick="openForm()">Chat</button> <div class="openChat"> <form> <h1>Chat</h1> <label for="msg"><b>Message</b></label> <textarea placeholder="Type message.." name="msg" required></textarea> <button type="submit" class="btn">Send</button> <button type="button" class="btn close" onclick="closeForm()"> Close </button> </form> </div> <script> document .querySelector(".openChatBtn") .addEventListener("click", openForm); document.querySelector(".close").addEventListener("click", closeForm); function openForm() { document.querySelector(".openChat").style.display = "block"; } function closeForm() { document.querySelector(".openChat").style.display = "none"; } </script> </body> </html> The above code will produce the following output − On clicking the Chat button the chat window will popup as follows −
[ { "code": null, "e": 1140, "s": 1062, "text": "To create popup chat window with CSS and JavaScript, the code is as follows −" }, { "code": null, "e": 1151, "s": 1140, "text": " Live Demo" }, { "code": null, "e": 3497, "s": 1151, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n * {\n box-sizing: border-box;\n }\n .openChatBtn {\n background-color: rgb(123, 28, 179);\n color: white;\n padding: 16px 20px;\n border: none;\n font-weight: 500;\n font-size: 18px;\n cursor: pointer;\n opacity: 0.8;\n position: fixed;\n bottom: 23px;\n right: 28px;\n width: 280px;\n }\n .openChat {\n display: none;\n position: fixed;\n bottom: 0;\n right: 15px;\n border: 3px solid #ff08086b;\n z-index: 9;\n }\n form {\n max-width: 300px;\n padding: 10px;\n background-color: white;\n }\n form textarea {\n width: 100%;\n font-size: 18px;\n padding: 15px;\n margin: 5px 0 22px 0;\n border: none;\n font-weight: 500;\n background: #d5e7ff;\n color: rgb(0, 0, 0);\n resize: none;\n min-height: 200px;\n }\n form textarea:focus {\n background-color: rgb(219, 255, 252);\n outline: none;\n }\n form .btn {\n background-color: rgb(34, 197, 107);\n color: white;\n padding: 16px 20px;\n font-weight: bold;\n border: none;\n cursor: pointer;\n width: 100%;\n margin-bottom: 10px;\n opacity: 0.8;\n }\n form .close {\n background-color: red;\n }\n form .btn:hover, .openChatBtn:hover {\n opacity: 1;\n }\n</style>\n</head>\n<body>\n<h1>Popup Chat Window Example</h1>\n<h2>Click the below button to start chatting</h2>\n<button class=\"openChatBtn\" onclick=\"openForm()\">Chat</button>\n<div class=\"openChat\">\n<form>\n<h1>Chat</h1>\n<label for=\"msg\"><b>Message</b></label>\n<textarea placeholder=\"Type message..\" name=\"msg\" required></textarea>\n<button type=\"submit\" class=\"btn\">Send</button>\n<button type=\"button\" class=\"btn close\" onclick=\"closeForm()\">\nClose\n</button>\n</form>\n</div>\n<script>\n document .querySelector(\".openChatBtn\") .addEventListener(\"click\", openForm);\n document.querySelector(\".close\").addEventListener(\"click\", closeForm);\n function openForm() {\n document.querySelector(\".openChat\").style.display = \"block\";\n }\n function closeForm() {\n document.querySelector(\".openChat\").style.display = \"none\";\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 3548, "s": 3497, "text": "The above code will produce the following output −" }, { "code": null, "e": 3616, "s": 3548, "text": "On clicking the Chat button the chat window will popup as follows −" } ]
How to set python environment variable PYTHONPATH on Windows?
To set the PYTHONPATH on windows to point Python to look in other directories for module and package imports, go to: My Computer > Properties > Advanced System Settings > Environment Variables Then under system variables edit the PythonPath variable. At the end of the current PYTHONPATH, add a semicolon and then the directory you want to add to this path: C:\Python27;C:\foo , In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
[ { "code": null, "e": 1179, "s": 1062, "text": "To set the PYTHONPATH on windows to point Python to look in other directories for module and package imports, go to:" }, { "code": null, "e": 1255, "s": 1179, "text": "My Computer > Properties > Advanced System Settings > Environment Variables" }, { "code": null, "e": 1420, "s": 1255, "text": "Then under system variables edit the PythonPath variable. At the end of the current PYTHONPATH, add a semicolon and then the directory you want to add to this path:" }, { "code": null, "e": 1439, "s": 1420, "text": "C:\\Python27;C:\\foo" }, { "code": null, "e": 1715, "s": 1439, "text": ", In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble." } ]
round() in C++.
The round() function in C++ is used to round off the double, float or long double value passed to it as a parameter to the nearest integral value. The header file used to use the round() function in a c++ program is <cmath> or <tgmath>. Following are the overloaded versions of round() after C++ 11 standard double round( double D ) float round( float F ) long double round( long double LD ) double round ( T var ) Note − The value returned is the nearest integer represented as floating point, i.e for 2.3 nearest value returned will be 2.0 and not 2. Following program is used to demonstrate the usage of round function in a C++ program − Live Demo #include <cmath> #include <iostream> int main(){ double num1=10.5; double num2=10.3; double num3=9.7; std::cout << "Nearest integer after round("<<num1<<") :" << round(num1)<< "\n"; std::cout << "Nearest integer after round("<<num2<<") :" << round(num2)<< "\n"; std::cout << "Nearest integer after round("<<num3<<") :" << round(num3)<< "\n"; num1=-9.3; num2=-0.3; num3=-9.9; std::cout << "Nearest integer after round("<<num1<<") :" << round(num1)<< "\n"; std::cout << "Nearest integer after round("<<num2<<") :" << round(num2)<< "\n"; std::cout << "Nearest integer after round("<<num3<<") :" << round(num3)<< "\n"; return 0; } Nearest integer after round(10.5) :11 Nearest integer after round(10.3) :10 Nearest integer after round(9.7) :10 Nearest integer after round(-9.3) :-9 Nearest integer after round(-0.3) :-0 Nearest integer after round(-9.9) :-10
[ { "code": null, "e": 1299, "s": 1062, "text": "The round() function in C++ is used to round off the double, float or long double value passed to it as a parameter to the nearest integral value. The header file used to use the\nround() function in a c++ program is <cmath> or <tgmath>." }, { "code": null, "e": 1370, "s": 1299, "text": "Following are the overloaded versions of round() after C++ 11 standard" }, { "code": null, "e": 1395, "s": 1370, "text": "double round( double D )" }, { "code": null, "e": 1418, "s": 1395, "text": "float round( float F )" }, { "code": null, "e": 1454, "s": 1418, "text": "long double round( long double LD )" }, { "code": null, "e": 1477, "s": 1454, "text": "double round ( T var )" }, { "code": null, "e": 1615, "s": 1477, "text": "Note − The value returned is the nearest integer represented as floating point, i.e for 2.3 nearest value returned will be 2.0 and not 2." }, { "code": null, "e": 1703, "s": 1615, "text": "Following program is used to demonstrate the usage of round function in a C++ program −" }, { "code": null, "e": 1714, "s": 1703, "text": " Live Demo" }, { "code": null, "e": 2380, "s": 1714, "text": "#include <cmath>\n#include <iostream>\nint main(){\n double num1=10.5;\n double num2=10.3;\n double num3=9.7;\n std::cout << \"Nearest integer after round(\"<<num1<<\") :\" << round(num1)<< \"\\n\";\n std::cout << \"Nearest integer after round(\"<<num2<<\") :\" << round(num2)<< \"\\n\";\n std::cout << \"Nearest integer after round(\"<<num3<<\") :\" << round(num3)<< \"\\n\";\n num1=-9.3;\n num2=-0.3;\n num3=-9.9;\n std::cout << \"Nearest integer after round(\"<<num1<<\") :\" << round(num1)<< \"\\n\";\n std::cout << \"Nearest integer after round(\"<<num2<<\") :\" << round(num2)<< \"\\n\";\n std::cout << \"Nearest integer after round(\"<<num3<<\") :\" << round(num3)<< \"\\n\";\n return 0;\n}" }, { "code": null, "e": 2608, "s": 2380, "text": "Nearest integer after round(10.5) :11\nNearest integer after round(10.3) :10\nNearest integer after round(9.7) :10\nNearest integer after round(-9.3) :-9\nNearest integer after round(-0.3) :-0\nNearest integer after round(-9.9) :-10" } ]
A Practical Introduction to Grid Search, Random Search, and Bayes Search | by B. Chen | Towards Data Science
In Machine Learning, hyperparameters refer to the parameters that cannot be learned from data and need to be provided before training. The performance of machine learning models relies heavily on finding the optimal set of hyperparameters. Hyperparameter tuning basically refers to tweaking the hyperparameters of the model, which is basically a length process. In this article, you’ll learn the 3 most popular hyperparameter tuning techniques: Grid Search, Random Search, and Bayes Search. This article is structured as follows: Getting and preparing dataGrid SearchRandom SearchBayes SearchConclusion Getting and preparing data Grid Search Random Search Bayes Search Conclusion Please check out the Notebook for source code. More tutorials are available from Github Repo. For demonstration, we’ll be using the built-in breast cancer data from Scikit Learn to train a Support Vector Classifier (SVC). We can get the data with the load_breast_cancer function: from sklearn.datasets import load_breast_cancercancer = load_breast_cancer() Next, let’s create df_X and df_y for features and target label as follows: # Featuresdf_X = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])# Target labeldf_y = pd.DataFrame(cancer['target'], columns=['Cancer']) P.S. If you want to know more about the dataset, you can run print(cancer['DESCR']) to print out summary and feature information. After that, let’s split the dataset into a training set (70%) and a test set (30%) using training_test_split(): # Train test splitfrom sklearn.model_selection import train_test_splitimport numpy as npX_train, X_test, y_train, y_test = train_test_split(df_X, np.ravel(df_y), test_size=0.3) We will be training a Support Vector Classifier (SVC) model. The regularization parameter C and kernel coefficient gamma are the two most important hyperparameters in SVC: The regularization parameter C determines the strength of the regularization. The kernel coefficient gamma controls the width of the kernel. SVC uses radial basis function(RBF) kernel by default (also known as the Gaussian kernel). We will be tuning these 2 parameters in the following tutorial. It’s tricky to find the optimal value for C and gamma. The simplest solution is to try a bunch of combinations and see what works best. This idea of creating a “grid” of parameters and just trying out all the possible combinations is called a Grid Search. This method is common enough that Scikit-learn has this functionality built-in with GridSearchCV. The CV stands for Cross-Validation which is another technique to evaluate and improve our Machine Learning model. GridSearchCV takes a dictionary that describes the parameters that should be tried and a model to train. The grid of parameters is defined as a dictionary, where the keys are the parameters and the values are the settings to be tested. Let’s first define our candidate C and gamma as follows: param_grid = { 'C': [0.1, 1, 10, 100, 1000], 'gamma': [1, 0.1, 0.01, 0.001, 0.0001]} Next, let’s create a GridSearchCV object and fit it to the training data. from sklearn.model_selection import GridSearchCVfrom sklearn.svm import SVCgrid = GridSearchCV(SVC(), param_grid, refit=True, verbose=3)grid.fit(X_train,y_train) Once the training is completed, we can inspect the best parameters found by GridSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute: # Find the best paramters>>> grid.best_params_{'C': 1, 'gamma': 0.0001}# Find the best estimator>>> grid.best_estimator_SVC(C=1, gamma=0.0001) Now take that grid model and create some predictions using the test set and create classification reports and confusion matrices for them. Grid Search tries all combinations of hyperparameters hence increasing the time complexity of the computation and could result in an unfeasible computing cost. Providing a cheaper alternative, Random Search tests only as many tuples as you choose. The selection of the hyperparameter values is completely random. This method is also common enough that Scikit-learn has this functionality built-in with RandomizedSearchCV. The function API is very similar to GridSearchCV. First, let’s specify parameters C & gamma and distributions to sample from as follows: import scipy.stats as statsfrom sklearn.utils.fixes import loguniform# Specify parameters and distributions to sample fromparam_dist = { 'C': stats.uniform(0.1, 1e4), 'gamma': loguniform(1e-6, 1e+1),} Next, let’s create a RandomizedSearchCV object with argument n_iter_search and fit it to the training data. n_iter_search = 20random_search = RandomizedSearchCV( SVC(), param_distributions=param_dist, n_iter=n_iter_search, refit=True, verbose=3)random_search.fit(X_train, y_train) Similarly, once the training is completed, we can inspect the best parameters found by RandomizedSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute: >>> random_search.best_params_{'C': 559.3412579902997, 'gamma': 0.00022332416796205752}>>> random_search.best_estimator_SVC(C=559.3412579902997, gamma=0.00022332416796205752) Finally, we take that random search model and create some predictions using the test set and create classification reports and confusion matrices for them. Bayes Search uses the Bayesian optimization technique to model the search space to arrive at optimized parameter values as soon as possible. It uses the structure of search space to optimize the search time. Bayes Search approach uses the past evaluation results to sample new candidates that are most likely to give better results (shown in the figure below). Scikit-Optimize library comes with BayesSearchCV implementation. First, let’s specify parameters C & gamma and distributions to sample from as follows: from skopt import BayesSearchCV# parameter ranges are specified by one of belowfrom skopt.space import Real, Categorical, Integersearch_spaces = { 'C': Real(0.1, 1e+4), 'gamma': Real(1e-6, 1e+1, 'log-uniform'),} Next, let’s create a BayesSearchCV object with argument n_iter_search and fit it to the training data. n_iter_search = 20bayes_search = BayesSearchCV( SVC(), search_spaces, n_iter=n_iter_search, cv=5, verbose=3)bayes_search.fit(X_train, y_train) Similarly, once the training is completed, we can inspect the best parameters found by BayesSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute: >>> bayes_search.best_params_OrderedDict([('C', 0.25624177419852506), ('gamma', 0.00016576008531229226)])>>> bayes_search.best_estimator_SVC(C=0.25624177419852506, gamma=0.00016576008531229226) Finally, we take that Bayes search model and create some predictions using the test set and create classification reports and confusion matrices for them. In this article, we have covered the 3 most popular hyperparameter optimization techniques that are used to get the optimal set of hyperparameters leading to training a robust machine learning model. In general, if the number of combinations is limited enough, we can use the Grid Search technique. But when the number of combinations increases, we should try Random Search or Bayes Search as they are not computationally expensive. I hope this article will help you to save time in learning Machine Learning. I recommend you to check out their APIs [1, 2] and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. References: [1] Scikit-Learn docs: https://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html [2] Scikit-Optimize docs: https://scikit-optimize.github.io/stable/modules/generated/skopt.BayesSearchCV.html
[ { "code": null, "e": 411, "s": 171, "text": "In Machine Learning, hyperparameters refer to the parameters that cannot be learned from data and need to be provided before training. The performance of machine learning models relies heavily on finding the optimal set of hyperparameters." }, { "code": null, "e": 701, "s": 411, "text": "Hyperparameter tuning basically refers to tweaking the hyperparameters of the model, which is basically a length process. In this article, you’ll learn the 3 most popular hyperparameter tuning techniques: Grid Search, Random Search, and Bayes Search. This article is structured as follows:" }, { "code": null, "e": 774, "s": 701, "text": "Getting and preparing dataGrid SearchRandom SearchBayes SearchConclusion" }, { "code": null, "e": 801, "s": 774, "text": "Getting and preparing data" }, { "code": null, "e": 813, "s": 801, "text": "Grid Search" }, { "code": null, "e": 827, "s": 813, "text": "Random Search" }, { "code": null, "e": 840, "s": 827, "text": "Bayes Search" }, { "code": null, "e": 851, "s": 840, "text": "Conclusion" }, { "code": null, "e": 945, "s": 851, "text": "Please check out the Notebook for source code. More tutorials are available from Github Repo." }, { "code": null, "e": 1131, "s": 945, "text": "For demonstration, we’ll be using the built-in breast cancer data from Scikit Learn to train a Support Vector Classifier (SVC). We can get the data with the load_breast_cancer function:" }, { "code": null, "e": 1208, "s": 1131, "text": "from sklearn.datasets import load_breast_cancercancer = load_breast_cancer()" }, { "code": null, "e": 1283, "s": 1208, "text": "Next, let’s create df_X and df_y for features and target label as follows:" }, { "code": null, "e": 1433, "s": 1283, "text": "# Featuresdf_X = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])# Target labeldf_y = pd.DataFrame(cancer['target'], columns=['Cancer'])" }, { "code": null, "e": 1563, "s": 1433, "text": "P.S. If you want to know more about the dataset, you can run print(cancer['DESCR']) to print out summary and feature information." }, { "code": null, "e": 1675, "s": 1563, "text": "After that, let’s split the dataset into a training set (70%) and a test set (30%) using training_test_split():" }, { "code": null, "e": 1852, "s": 1675, "text": "# Train test splitfrom sklearn.model_selection import train_test_splitimport numpy as npX_train, X_test, y_train, y_test = train_test_split(df_X, np.ravel(df_y), test_size=0.3)" }, { "code": null, "e": 2024, "s": 1852, "text": "We will be training a Support Vector Classifier (SVC) model. The regularization parameter C and kernel coefficient gamma are the two most important hyperparameters in SVC:" }, { "code": null, "e": 2102, "s": 2024, "text": "The regularization parameter C determines the strength of the regularization." }, { "code": null, "e": 2256, "s": 2102, "text": "The kernel coefficient gamma controls the width of the kernel. SVC uses radial basis function(RBF) kernel by default (also known as the Gaussian kernel)." }, { "code": null, "e": 2320, "s": 2256, "text": "We will be tuning these 2 parameters in the following tutorial." }, { "code": null, "e": 2576, "s": 2320, "text": "It’s tricky to find the optimal value for C and gamma. The simplest solution is to try a bunch of combinations and see what works best. This idea of creating a “grid” of parameters and just trying out all the possible combinations is called a Grid Search." }, { "code": null, "e": 2788, "s": 2576, "text": "This method is common enough that Scikit-learn has this functionality built-in with GridSearchCV. The CV stands for Cross-Validation which is another technique to evaluate and improve our Machine Learning model." }, { "code": null, "e": 3081, "s": 2788, "text": "GridSearchCV takes a dictionary that describes the parameters that should be tried and a model to train. The grid of parameters is defined as a dictionary, where the keys are the parameters and the values are the settings to be tested. Let’s first define our candidate C and gamma as follows:" }, { "code": null, "e": 3170, "s": 3081, "text": "param_grid = { 'C': [0.1, 1, 10, 100, 1000], 'gamma': [1, 0.1, 0.01, 0.001, 0.0001]}" }, { "code": null, "e": 3244, "s": 3170, "text": "Next, let’s create a GridSearchCV object and fit it to the training data." }, { "code": null, "e": 3406, "s": 3244, "text": "from sklearn.model_selection import GridSearchCVfrom sklearn.svm import SVCgrid = GridSearchCV(SVC(), param_grid, refit=True, verbose=3)grid.fit(X_train,y_train)" }, { "code": null, "e": 3583, "s": 3406, "text": "Once the training is completed, we can inspect the best parameters found by GridSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute:" }, { "code": null, "e": 3726, "s": 3583, "text": "# Find the best paramters>>> grid.best_params_{'C': 1, 'gamma': 0.0001}# Find the best estimator>>> grid.best_estimator_SVC(C=1, gamma=0.0001)" }, { "code": null, "e": 3865, "s": 3726, "text": "Now take that grid model and create some predictions using the test set and create classification reports and confusion matrices for them." }, { "code": null, "e": 4178, "s": 3865, "text": "Grid Search tries all combinations of hyperparameters hence increasing the time complexity of the computation and could result in an unfeasible computing cost. Providing a cheaper alternative, Random Search tests only as many tuples as you choose. The selection of the hyperparameter values is completely random." }, { "code": null, "e": 4337, "s": 4178, "text": "This method is also common enough that Scikit-learn has this functionality built-in with RandomizedSearchCV. The function API is very similar to GridSearchCV." }, { "code": null, "e": 4424, "s": 4337, "text": "First, let’s specify parameters C & gamma and distributions to sample from as follows:" }, { "code": null, "e": 4627, "s": 4424, "text": "import scipy.stats as statsfrom sklearn.utils.fixes import loguniform# Specify parameters and distributions to sample fromparam_dist = { 'C': stats.uniform(0.1, 1e4), 'gamma': loguniform(1e-6, 1e+1),}" }, { "code": null, "e": 4735, "s": 4627, "text": "Next, let’s create a RandomizedSearchCV object with argument n_iter_search and fit it to the training data." }, { "code": null, "e": 4925, "s": 4735, "text": "n_iter_search = 20random_search = RandomizedSearchCV( SVC(), param_distributions=param_dist, n_iter=n_iter_search, refit=True, verbose=3)random_search.fit(X_train, y_train)" }, { "code": null, "e": 5119, "s": 4925, "text": "Similarly, once the training is completed, we can inspect the best parameters found by RandomizedSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute:" }, { "code": null, "e": 5294, "s": 5119, "text": ">>> random_search.best_params_{'C': 559.3412579902997, 'gamma': 0.00022332416796205752}>>> random_search.best_estimator_SVC(C=559.3412579902997, gamma=0.00022332416796205752)" }, { "code": null, "e": 5450, "s": 5294, "text": "Finally, we take that random search model and create some predictions using the test set and create classification reports and confusion matrices for them." }, { "code": null, "e": 5811, "s": 5450, "text": "Bayes Search uses the Bayesian optimization technique to model the search space to arrive at optimized parameter values as soon as possible. It uses the structure of search space to optimize the search time. Bayes Search approach uses the past evaluation results to sample new candidates that are most likely to give better results (shown in the figure below)." }, { "code": null, "e": 5876, "s": 5811, "text": "Scikit-Optimize library comes with BayesSearchCV implementation." }, { "code": null, "e": 5963, "s": 5876, "text": "First, let’s specify parameters C & gamma and distributions to sample from as follows:" }, { "code": null, "e": 6177, "s": 5963, "text": "from skopt import BayesSearchCV# parameter ranges are specified by one of belowfrom skopt.space import Real, Categorical, Integersearch_spaces = { 'C': Real(0.1, 1e+4), 'gamma': Real(1e-6, 1e+1, 'log-uniform'),}" }, { "code": null, "e": 6280, "s": 6177, "text": "Next, let’s create a BayesSearchCV object with argument n_iter_search and fit it to the training data." }, { "code": null, "e": 6441, "s": 6280, "text": "n_iter_search = 20bayes_search = BayesSearchCV( SVC(), search_spaces, n_iter=n_iter_search, cv=5, verbose=3)bayes_search.fit(X_train, y_train)" }, { "code": null, "e": 6630, "s": 6441, "text": "Similarly, once the training is completed, we can inspect the best parameters found by BayesSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute:" }, { "code": null, "e": 6824, "s": 6630, "text": ">>> bayes_search.best_params_OrderedDict([('C', 0.25624177419852506), ('gamma', 0.00016576008531229226)])>>> bayes_search.best_estimator_SVC(C=0.25624177419852506, gamma=0.00016576008531229226)" }, { "code": null, "e": 6979, "s": 6824, "text": "Finally, we take that Bayes search model and create some predictions using the test set and create classification reports and confusion matrices for them." }, { "code": null, "e": 7179, "s": 6979, "text": "In this article, we have covered the 3 most popular hyperparameter optimization techniques that are used to get the optimal set of hyperparameters leading to training a robust machine learning model." }, { "code": null, "e": 7412, "s": 7179, "text": "In general, if the number of combinations is limited enough, we can use the Grid Search technique. But when the number of combinations increases, we should try Random Search or Bayes Search as they are not computationally expensive." }, { "code": null, "e": 7579, "s": 7412, "text": "I hope this article will help you to save time in learning Machine Learning. I recommend you to check out their APIs [1, 2] and to know about other things you can do." }, { "code": null, "e": 7731, "s": 7579, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 7743, "s": 7731, "text": "References:" }, { "code": null, "e": 7856, "s": 7743, "text": "[1] Scikit-Learn docs: https://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html" } ]
A Data Scientist's Dream: Python, Big Data, Multi-Processing, and PyCaret | by Fahad Akbar | Towards Data Science
Let me put it simply: the ability to tackle large data has become an absolute need if you are in data analytics or the data science domain. In this article, we will learn to design a solution that you can simply create using your laptop/desktop. No fancy cloud solution is needed! Today, we will learn the following: 1️⃣ What is Map Reduce2️⃣ What is Python’s Multiprocessing Module 3️⃣ How to Train & Predict Multiple Models in Parallel 📓 Note: There are multiple tools and solutions available to handle big data. The aim here is to understand the basics and then move on to more sophisticated tools. I also assume that the reader has basic knowledge of data science, PyCaret (an open-source low code library), and is able to code in Python. What naturally comes into our mind when we think of dealing with lots of data? An obvious solution is to get a more powerful machine. This idea is called “Vertical Scaling.” You have one machine but have more power. This, however, turns out to be not a very practical solution. The alternate is “Horizontal Scaling,” where multiple small machines are put together and we hope to use their combined resources to solve our problem. To achieve this, we first need to make a network between the machines/computers. You don't need to worry about creating this network for now. However, In today’s world, it is much easier to create and inexpensive to maintain such networks, especially with all the cloud solutions available. This really isn't hard. As I mentioned above, creating a network (although it is easy) is out of the scope of this article, and we can still learn and apply the concept with our own personal desktop or laptop. We can use the cores available in our computer in the same fashion as we would use them in a network, as long as we have more than one core. After all, your own computer is a mini horizontally scaled solution; actually a network or multiple cores! Once we have the network (horizontal scaling) in place, all we need is to distribute our data to these machines, use these resources to process our data and finally collect the results back. This distribution is equivalent to “map” and collection is equivalent to “Reduce”. That is your map-reduce! All the famous big data solutions are actually built upon this concept. If you ask me, “map” is the hardest part of it. That is where one has to devise a strategy/logic to distribute the data to the entire network so that you can solve the problem at hand. Some problems are easy to solve and some are even harder, and some are even impossible. Let us understand this with a very simple example. Say we have an array/list of numbers of size 16. We want to calculate the mean of it. In normal circumstances, we will do something like: mean = np.mean([8,1,4,3,2,5,1,2,2,9,7,6,2,4,2,1]) The result would be 3.6875. Now imagine, for some reason, our computer does not have enough power to compute it in one go. Well, can you think of a way to distribute/map this array to all the cores and then solve for the mean? It is simple. We know that the “mean of means is same as the mean” (as long as the sample size is kept the same). So we can break our array into smaller arrays of equal size, send them to different cores, have every core calculate the mean of the smaller array, return the array of means, and then calculate the mean of the array of means! We just implemented map (breaking & distribution of array to cores) reduce ( shrinking the arrays to a number and getting it back). In step 1, we break the array into subsets of arrays and send them to different cores. In step 2, every core calculates (📓Note: all the cores are performing the calculation at the same time & not like a loop fashion!) the mean of sub-set it got. We save these results into another array, which is now of size 4. In step 3, We ask any core to perform another mean calculation on this array. We return the final mean to capture/display the result. (📓Note: if we had a virtual network of computers, step 3 would be more complicated as the results would be collected from every computer and submitted back to the main computer.). That is a small example of map-reduce. You can now extrapolate this example to some real-time big data issues. Think of applying some aggregation function (aka group by operations) to a huge data set. Without horizontal integration / map-reduce, it will be executed very slowly. We can perform the same aggregation function by chopping the data and then going through some logic to obtain what we want. That will be much quicker. Another use-case would be a situation where you need to perform some operations in a “loop”, e.g. say you have thousands of separate CSV files that you want to convert to any other file format say XLSX. Or you have to train separate models for every customer you have data for. With vertical integration, you will have to run everything in a loop, one by one, and you can imagine the time it will take to perform the entire task. On the other hand, if you apply map-reduce, you will be able to “parallelize” the operation and the procedure will be executed much, much faster! In fact, in our example, we will solve and implement the exact same issue. 📓 Note: There could be the data size issue, i.e. data is so huge that it doesn’t fit into a single machine’s memory. In this case, you will need a network of computers rather than a single machine. That solution is out of the scope of this article. Nonetheless, map-reduce will still be involved. The built-in multiprocessing module/library helps us implement the map-reduce strategy we just discussed. Simple as that! Through this library, we will instruct python to run independent parallel procedures that would save us a lot of time. The multiprocessing library is a great resource, but later on, another library called “concurrent” was added. This is built on top of the multiprocessing library and just makes things much simpler to handle. Although I would recommend checking the multiprocessing library here, for the sake of simplicity I will use the “concurrent” library. To use these libraries we need to understand a few important points. 👉 The first thing is the structure of the code we are going to run. We will use map() function from the concurrent module, and we will provide this function with two parameters: 1️⃣ Target function: The function we want to execute w.r.t to our data processing. In the context of our previous example, you can think of it as numpy.mean(). 2️⃣ An iterator object: a list/array-like object, that contains unique values, through which the data can be indexed. You can think of it as a slicer/divider of the data. In the context of our previous example, it will be a list [1,2,3,4] through which we sliced the data into 4 equal chunks. map function will distribute the target function and single element of the iterator to every core. Since our original data is in the global namespace (meaning all the cores can access it anytime) we can slice the data (using the single element) and apply the target function to it inside every core. This distribution of function and elements to all the cores is automatically managed by the concurrent module. 👉 The second thing we need to understand is the handling of input (or the data being used), output (the result we want), and all the variables that we may need to use during the process. In the absence of multiprocessing, we use this stuff all the time without having any issues. With multiprocessing, things are different. Every core processing the slice of data with the target function, can not really share any information /piece of the process with other cores. The impact of this limitation is that we can not update the value of a variable/output “easily”. Fortunately, there are some workarounds available. There is a “shared” dictionary available through the multiprocessing module, which we can use to collect updated information as every core does its job. Alternatively (if your process allows) we can make an empty CSV file and then keep appending the results obtained from each core to it. Please note that this method will only work if you are deploying this solution to one machine. If you have a network of computers, this trick will not work. However, this method provides much more flexibility to us. 👉 The list thing we need t know is that this code structure can not be run through Jupyter Notebooks. We will need to write the entire code in the python module, which is merely writing python script in a .py file instead of a .ipynb file. Before we go to an example, a short video I made would help us understand the structure: Let us do a simple project and apply the concepts I explained above. Say I have sales data of five different stores. I want to calculate the mean of daily sales by store. It is the same as if I want to apply a group by clause with the mean function. Only this time, we will use the concurrent module to get the same result. Let us create our dataset. Our dataset will contain five stores, and every store will have five daily sales points. At your end, you can increase the data amount and number of stores as you like: If you print the data set, you will see something like this : We want to transform this data to get the mean of the daily sales per store, and end result should look like this: The next step is to create the function that will achieve this transformation. Conceptually, this is the hardest part, the more advanced transformation you want, the harder the function be. In our case, it is a simple mean. This function should be constructed as if you are doing an ith step of a “for loop”. Additionally, we need to get the shared dictionary and a CSV placeholder as discussed above. All we need is to “execute” this function through the concurrent module we have, by calling the map function. map the function will take the target function and an iterable (list in our case) that it can use to slice and distribute the data and function to all the cores. For our example, it's no other than the unique list of stores we have. We can also count the time it takes to run the parallel procedure. Remember, we need to run all these snippets in one python module, and then run the module through the command line. The complete code, that you can run yourself in your terminal is below: Once you run this file in your terminal, you should see the following output: We also created a placeholder CSV file, read it from the directory where you ran the module and have a look at it. You should get something like this: That’s it. You successfully ran the multi-processing job and obtained the results. For your experimentation purposes, you can increase the number of stores and the daily sales. ⚠️Warning: Unfortunately, for Windows users the above process will not run as expected. But we can achieve the same with couple of easy ways. First one is to change the structure of the code. Shared Dictionary and place holder CSV file will not store any thing for us. In order to get the results back, we need to return the desired object from the target function (and you can return anything! float, array, dictionary or any other object). When we run the executer , it will give us back a generator, and all we need is to run it with a loop or list comprehension. Below are the changes that you will need to make : The second way , which I like the most (because of its flexibility) is to simply use Window’s Subsystem for Linux (WSL). This is a very handy and easy way to have Linux on your Windows without making so mush mess. I have a separate article on it and you can access it here. For the rest of the article I will assume that you have the Lunix /Mac system one way or the other. If you have followed along and have understood everything up until here, you should be able to design and run your own solutions in a parallel way. You can simply stop, and start building your own. However, the article goes on to the final part where we handle a real-world example involving concurrent futures and PyCaret. We have data for a retail business that owns many stores. Every store has daily sales records. In the real world, there would be many items in the store, but for simplicity let us assume that there is only one item to sell. Our job is to predict the sales of each store. I have prepared some dummy data that you can have access to through the repository. In the training data, I have sales of 20 stores, where each store has 30 daily sales records. Let us have a look at the data: We need to predict “sales_qty” and can use all other columns as “features”. The data is clean and has no missing values. In the test dataset, we have to predict the “sales_qty” column. Here is how test data looks like: 📓: You can download the data and python modules from my repository. In the usual circumstances, we will simply make a loop by store, train separate models for every store & save the trained model for later use. But we don't want to do the loop, because a large number of stores and large daily sales records could become too much for the poor loop. We want to get this done in a parallel / concurrent fashion. 🔆Strategy: Our strategy is simple, and like before. We will make a training function (target function) and make an iterable (unique list of stores). The training function will contain everything that you would want to have to completely train a model for a single store. We will then save the trained model in the shared dictionary and save the prediction results on a CSV placeholder file, on the fly. I am assuming that you are familiar with the PyCaret and I do not need to explain the functionality, if not, you can start learning here. It is very easy! Below is the code that will do the trick. It is nothing more than what we have already seen in our previous example plus I have elaborated it with comments to make it easy as you read. While you are running this code in Linux / Mac terminal, you can check the status of all the cores to see if the code has made them busy. In your terminal type htop and you should see something like this: Once the process ends, it should give you the time in which it completed training. On my end, it took 70 seconds to train models for 20 stores, with 10 folds cross-validation, while choosing every model from a list of more than 20 models. That's fast! You should have the “predictions_place_holder.csv” file at the end, and it should look like this : You should also be able to read the shared dictionary, which we saved as a pickle file to our working directory as a pickle file. If you load the pickle file: with open("saved_models.p","rb") as fp:models = pickle.load(fp) and examine it, you will notice that we have a trained pipeline for every store, where the store number is the key. We can access it through indexing model[1092] and you should get something like this: This is a scikit-learn learn pipeline object containing the transformers and estimators in the end (see “trained_model” ), which means you can use the dot predict method model[1092].predict() to get the prediction for store 1092 anytime you want! This brings us to the end of the article. We learnt about map-reduce, Python’s multiprocessing module and how it works, and lastly how we can use the concurrent module to train and save multiple models through PyCaret in parallel. This is just the beginning, and you can fine-tune the processing, factorize the functions and go into the details of the multiprocessing module as you gain more experience. However, hopefully, you are now better equipped to deal with some of the big data solutions. I will appreciate your comments, thoughts & insights! ➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖You can follow me on medium & connect with me on LinkedIn & visit my GitHub➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖ 👉 Make your data science life easy with Docker👉 Custom Estimator With PyCaret, Part 1👉 Custom Estimator With PyCaret, Part 2👉Get Linux Inside Windows The Easy Way
[ { "code": null, "e": 453, "s": 172, "text": "Let me put it simply: the ability to tackle large data has become an absolute need if you are in data analytics or the data science domain. In this article, we will learn to design a solution that you can simply create using your laptop/desktop. No fancy cloud solution is needed!" }, { "code": null, "e": 489, "s": 453, "text": "Today, we will learn the following:" }, { "code": null, "e": 610, "s": 489, "text": "1️⃣ What is Map Reduce2️⃣ What is Python’s Multiprocessing Module 3️⃣ How to Train & Predict Multiple Models in Parallel" }, { "code": null, "e": 915, "s": 610, "text": "📓 Note: There are multiple tools and solutions available to handle big data. The aim here is to understand the basics and then move on to more sophisticated tools. I also assume that the reader has basic knowledge of data science, PyCaret (an open-source low code library), and is able to code in Python." }, { "code": null, "e": 1660, "s": 915, "text": "What naturally comes into our mind when we think of dealing with lots of data? An obvious solution is to get a more powerful machine. This idea is called “Vertical Scaling.” You have one machine but have more power. This, however, turns out to be not a very practical solution. The alternate is “Horizontal Scaling,” where multiple small machines are put together and we hope to use their combined resources to solve our problem. To achieve this, we first need to make a network between the machines/computers. You don't need to worry about creating this network for now. However, In today’s world, it is much easier to create and inexpensive to maintain such networks, especially with all the cloud solutions available. This really isn't hard." }, { "code": null, "e": 2094, "s": 1660, "text": "As I mentioned above, creating a network (although it is easy) is out of the scope of this article, and we can still learn and apply the concept with our own personal desktop or laptop. We can use the cores available in our computer in the same fashion as we would use them in a network, as long as we have more than one core. After all, your own computer is a mini horizontally scaled solution; actually a network or multiple cores!" }, { "code": null, "e": 2738, "s": 2094, "text": "Once we have the network (horizontal scaling) in place, all we need is to distribute our data to these machines, use these resources to process our data and finally collect the results back. This distribution is equivalent to “map” and collection is equivalent to “Reduce”. That is your map-reduce! All the famous big data solutions are actually built upon this concept. If you ask me, “map” is the hardest part of it. That is where one has to devise a strategy/logic to distribute the data to the entire network so that you can solve the problem at hand. Some problems are easy to solve and some are even harder, and some are even impossible." }, { "code": null, "e": 2927, "s": 2738, "text": "Let us understand this with a very simple example. Say we have an array/list of numbers of size 16. We want to calculate the mean of it. In normal circumstances, we will do something like:" }, { "code": null, "e": 2977, "s": 2927, "text": "mean = np.mean([8,1,4,3,2,5,1,2,2,9,7,6,2,4,2,1])" }, { "code": null, "e": 3204, "s": 2977, "text": "The result would be 3.6875. Now imagine, for some reason, our computer does not have enough power to compute it in one go. Well, can you think of a way to distribute/map this array to all the cores and then solve for the mean?" }, { "code": null, "e": 3676, "s": 3204, "text": "It is simple. We know that the “mean of means is same as the mean” (as long as the sample size is kept the same). So we can break our array into smaller arrays of equal size, send them to different cores, have every core calculate the mean of the smaller array, return the array of means, and then calculate the mean of the array of means! We just implemented map (breaking & distribution of array to cores) reduce ( shrinking the arrays to a number and getting it back)." }, { "code": null, "e": 4341, "s": 3676, "text": "In step 1, we break the array into subsets of arrays and send them to different cores. In step 2, every core calculates (📓Note: all the cores are performing the calculation at the same time & not like a loop fashion!) the mean of sub-set it got. We save these results into another array, which is now of size 4. In step 3, We ask any core to perform another mean calculation on this array. We return the final mean to capture/display the result. (📓Note: if we had a virtual network of computers, step 3 would be more complicated as the results would be collected from every computer and submitted back to the main computer.). That is a small example of map-reduce." }, { "code": null, "e": 4732, "s": 4341, "text": "You can now extrapolate this example to some real-time big data issues. Think of applying some aggregation function (aka group by operations) to a huge data set. Without horizontal integration / map-reduce, it will be executed very slowly. We can perform the same aggregation function by chopping the data and then going through some logic to obtain what we want. That will be much quicker." }, { "code": null, "e": 5383, "s": 4732, "text": "Another use-case would be a situation where you need to perform some operations in a “loop”, e.g. say you have thousands of separate CSV files that you want to convert to any other file format say XLSX. Or you have to train separate models for every customer you have data for. With vertical integration, you will have to run everything in a loop, one by one, and you can imagine the time it will take to perform the entire task. On the other hand, if you apply map-reduce, you will be able to “parallelize” the operation and the procedure will be executed much, much faster! In fact, in our example, we will solve and implement the exact same issue." }, { "code": null, "e": 5680, "s": 5383, "text": "📓 Note: There could be the data size issue, i.e. data is so huge that it doesn’t fit into a single machine’s memory. In this case, you will need a network of computers rather than a single machine. That solution is out of the scope of this article. Nonetheless, map-reduce will still be involved." }, { "code": null, "e": 6332, "s": 5680, "text": "The built-in multiprocessing module/library helps us implement the map-reduce strategy we just discussed. Simple as that! Through this library, we will instruct python to run independent parallel procedures that would save us a lot of time. The multiprocessing library is a great resource, but later on, another library called “concurrent” was added. This is built on top of the multiprocessing library and just makes things much simpler to handle. Although I would recommend checking the multiprocessing library here, for the sake of simplicity I will use the “concurrent” library. To use these libraries we need to understand a few important points." }, { "code": null, "e": 6510, "s": 6332, "text": "👉 The first thing is the structure of the code we are going to run. We will use map() function from the concurrent module, and we will provide this function with two parameters:" }, { "code": null, "e": 6670, "s": 6510, "text": "1️⃣ Target function: The function we want to execute w.r.t to our data processing. In the context of our previous example, you can think of it as numpy.mean()." }, { "code": null, "e": 6963, "s": 6670, "text": "2️⃣ An iterator object: a list/array-like object, that contains unique values, through which the data can be indexed. You can think of it as a slicer/divider of the data. In the context of our previous example, it will be a list [1,2,3,4] through which we sliced the data into 4 equal chunks." }, { "code": null, "e": 7374, "s": 6963, "text": "map function will distribute the target function and single element of the iterator to every core. Since our original data is in the global namespace (meaning all the cores can access it anytime) we can slice the data (using the single element) and apply the target function to it inside every core. This distribution of function and elements to all the cores is automatically managed by the concurrent module." }, { "code": null, "e": 8494, "s": 7374, "text": "👉 The second thing we need to understand is the handling of input (or the data being used), output (the result we want), and all the variables that we may need to use during the process. In the absence of multiprocessing, we use this stuff all the time without having any issues. With multiprocessing, things are different. Every core processing the slice of data with the target function, can not really share any information /piece of the process with other cores. The impact of this limitation is that we can not update the value of a variable/output “easily”. Fortunately, there are some workarounds available. There is a “shared” dictionary available through the multiprocessing module, which we can use to collect updated information as every core does its job. Alternatively (if your process allows) we can make an empty CSV file and then keep appending the results obtained from each core to it. Please note that this method will only work if you are deploying this solution to one machine. If you have a network of computers, this trick will not work. However, this method provides much more flexibility to us." }, { "code": null, "e": 8734, "s": 8494, "text": "👉 The list thing we need t know is that this code structure can not be run through Jupyter Notebooks. We will need to write the entire code in the python module, which is merely writing python script in a .py file instead of a .ipynb file." }, { "code": null, "e": 8823, "s": 8734, "text": "Before we go to an example, a short video I made would help us understand the structure:" }, { "code": null, "e": 9147, "s": 8823, "text": "Let us do a simple project and apply the concepts I explained above. Say I have sales data of five different stores. I want to calculate the mean of daily sales by store. It is the same as if I want to apply a group by clause with the mean function. Only this time, we will use the concurrent module to get the same result." }, { "code": null, "e": 9343, "s": 9147, "text": "Let us create our dataset. Our dataset will contain five stores, and every store will have five daily sales points. At your end, you can increase the data amount and number of stores as you like:" }, { "code": null, "e": 9405, "s": 9343, "text": "If you print the data set, you will see something like this :" }, { "code": null, "e": 9520, "s": 9405, "text": "We want to transform this data to get the mean of the daily sales per store, and end result should look like this:" }, { "code": null, "e": 9922, "s": 9520, "text": "The next step is to create the function that will achieve this transformation. Conceptually, this is the hardest part, the more advanced transformation you want, the harder the function be. In our case, it is a simple mean. This function should be constructed as if you are doing an ith step of a “for loop”. Additionally, we need to get the shared dictionary and a CSV placeholder as discussed above." }, { "code": null, "e": 10332, "s": 9922, "text": "All we need is to “execute” this function through the concurrent module we have, by calling the map function. map the function will take the target function and an iterable (list in our case) that it can use to slice and distribute the data and function to all the cores. For our example, it's no other than the unique list of stores we have. We can also count the time it takes to run the parallel procedure." }, { "code": null, "e": 10520, "s": 10332, "text": "Remember, we need to run all these snippets in one python module, and then run the module through the command line. The complete code, that you can run yourself in your terminal is below:" }, { "code": null, "e": 10598, "s": 10520, "text": "Once you run this file in your terminal, you should see the following output:" }, { "code": null, "e": 10749, "s": 10598, "text": "We also created a placeholder CSV file, read it from the directory where you ran the module and have a look at it. You should get something like this:" }, { "code": null, "e": 10926, "s": 10749, "text": "That’s it. You successfully ran the multi-processing job and obtained the results. For your experimentation purposes, you can increase the number of stores and the daily sales." }, { "code": null, "e": 11544, "s": 10926, "text": "⚠️Warning: Unfortunately, for Windows users the above process will not run as expected. But we can achieve the same with couple of easy ways. First one is to change the structure of the code. Shared Dictionary and place holder CSV file will not store any thing for us. In order to get the results back, we need to return the desired object from the target function (and you can return anything! float, array, dictionary or any other object). When we run the executer , it will give us back a generator, and all we need is to run it with a loop or list comprehension. Below are the changes that you will need to make :" }, { "code": null, "e": 11918, "s": 11544, "text": "The second way , which I like the most (because of its flexibility) is to simply use Window’s Subsystem for Linux (WSL). This is a very handy and easy way to have Linux on your Windows without making so mush mess. I have a separate article on it and you can access it here. For the rest of the article I will assume that you have the Lunix /Mac system one way or the other." }, { "code": null, "e": 12242, "s": 11918, "text": "If you have followed along and have understood everything up until here, you should be able to design and run your own solutions in a parallel way. You can simply stop, and start building your own. However, the article goes on to the final part where we handle a real-world example involving concurrent futures and PyCaret." }, { "code": null, "e": 12513, "s": 12242, "text": "We have data for a retail business that owns many stores. Every store has daily sales records. In the real world, there would be many items in the store, but for simplicity let us assume that there is only one item to sell. Our job is to predict the sales of each store." }, { "code": null, "e": 12723, "s": 12513, "text": "I have prepared some dummy data that you can have access to through the repository. In the training data, I have sales of 20 stores, where each store has 30 daily sales records. Let us have a look at the data:" }, { "code": null, "e": 12942, "s": 12723, "text": "We need to predict “sales_qty” and can use all other columns as “features”. The data is clean and has no missing values. In the test dataset, we have to predict the “sales_qty” column. Here is how test data looks like:" }, { "code": null, "e": 13010, "s": 12942, "text": "📓: You can download the data and python modules from my repository." }, { "code": null, "e": 13352, "s": 13010, "text": "In the usual circumstances, we will simply make a loop by store, train separate models for every store & save the trained model for later use. But we don't want to do the loop, because a large number of stores and large daily sales records could become too much for the poor loop. We want to get this done in a parallel / concurrent fashion." }, { "code": null, "e": 13910, "s": 13352, "text": "🔆Strategy: Our strategy is simple, and like before. We will make a training function (target function) and make an iterable (unique list of stores). The training function will contain everything that you would want to have to completely train a model for a single store. We will then save the trained model in the shared dictionary and save the prediction results on a CSV placeholder file, on the fly. I am assuming that you are familiar with the PyCaret and I do not need to explain the functionality, if not, you can start learning here. It is very easy!" }, { "code": null, "e": 14095, "s": 13910, "text": "Below is the code that will do the trick. It is nothing more than what we have already seen in our previous example plus I have elaborated it with comments to make it easy as you read." }, { "code": null, "e": 14300, "s": 14095, "text": "While you are running this code in Linux / Mac terminal, you can check the status of all the cores to see if the code has made them busy. In your terminal type htop and you should see something like this:" }, { "code": null, "e": 14552, "s": 14300, "text": "Once the process ends, it should give you the time in which it completed training. On my end, it took 70 seconds to train models for 20 stores, with 10 folds cross-validation, while choosing every model from a list of more than 20 models. That's fast!" }, { "code": null, "e": 14651, "s": 14552, "text": "You should have the “predictions_place_holder.csv” file at the end, and it should look like this :" }, { "code": null, "e": 14810, "s": 14651, "text": "You should also be able to read the shared dictionary, which we saved as a pickle file to our working directory as a pickle file. If you load the pickle file:" }, { "code": null, "e": 14874, "s": 14810, "text": "with open(\"saved_models.p\",\"rb\") as fp:models = pickle.load(fp)" }, { "code": null, "e": 15076, "s": 14874, "text": "and examine it, you will notice that we have a trained pipeline for every store, where the store number is the key. We can access it through indexing model[1092] and you should get something like this:" }, { "code": null, "e": 15323, "s": 15076, "text": "This is a scikit-learn learn pipeline object containing the transformers and estimators in the end (see “trained_model” ), which means you can use the dot predict method model[1092].predict() to get the prediction for store 1092 anytime you want!" }, { "code": null, "e": 15874, "s": 15323, "text": "This brings us to the end of the article. We learnt about map-reduce, Python’s multiprocessing module and how it works, and lastly how we can use the concurrent module to train and save multiple models through PyCaret in parallel. This is just the beginning, and you can fine-tune the processing, factorize the functions and go into the details of the multiprocessing module as you gain more experience. However, hopefully, you are now better equipped to deal with some of the big data solutions. I will appreciate your comments, thoughts & insights!" }, { "code": null, "e": 15996, "s": 15874, "text": "➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖You can follow me on medium & connect with me on LinkedIn & visit my GitHub➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖" } ]
Sort the array of strings according to alphabetical order defined by another string in C++
Suppose we have an array of strings, and another string is there for the reference. We have to take the reference string and using the order of the characters in the reference string we will sort the string array. Here we are considering the strings in the array, and the reference string is in lower case letters. Suppose the string array is like: [“hello”, “programming”, “science”, “computer”, “india”], the reference string is like: “pigvxbskyhqzelutoacfjrndmw”, After sorting the output string will be like [“programming”, “india”, “science”, “hello”, “computer”] The task is simple. We have to traverse the reference string, then store the character into the map as key, and the index as value. Now to sort the string, we have to compare the strings based on that map, not the ASCII character ordering. Compare the values mapped to those particular characters in the map, if the character c1 appears before c2, then c1 < c2. Live Demo #include <iostream> #include <algorithm> #include <unordered_map> #include <vector> using namespace std; unordered_map<char, int> char_map; bool compare(string c1, string c2) { for (int i = 0; i < min(c1.size(), c2.size()); i++) { if (char_map[c1[i]] == char_map[c2[i]]) continue; return char_map[c1[i]] < char_map[c2[i]]; } return c1.size() < c2.size(); } int main() { string str = "pigvxbskyhqzelutoacfjrndmw"; vector<string> v{ "hello", "programming", "science", "computer", "india" }; char_map.clear(); for (int i = 0; i < str.size(); i++) char_map[str[i]] = i; sort(v.begin(), v.end(), compare); // Print the strings after sorting for (auto x : v) cout << x << " "; } programming india science hello computer
[ { "code": null, "e": 1377, "s": 1062, "text": "Suppose we have an array of strings, and another string is there for the reference. We have to take the reference string and using the order of the characters in the reference string we will sort the string array. Here we are considering the strings in the array, and the reference string is in lower case letters." }, { "code": null, "e": 1631, "s": 1377, "text": "Suppose the string array is like: [“hello”, “programming”, “science”, “computer”, “india”], the reference string is like: “pigvxbskyhqzelutoacfjrndmw”, After sorting the output string will be like [“programming”, “india”, “science”, “hello”, “computer”]" }, { "code": null, "e": 1993, "s": 1631, "text": "The task is simple. We have to traverse the reference string, then store the character into the map as key, and the index as value. Now to sort the string, we have to compare the strings based on that map, not the ASCII character ordering. Compare the values mapped to those particular characters in the map, if the character c1 appears before c2, then c1 < c2." }, { "code": null, "e": 2004, "s": 1993, "text": " Live Demo" }, { "code": null, "e": 2734, "s": 2004, "text": "#include <iostream>\n#include <algorithm>\n#include <unordered_map>\n#include <vector>\nusing namespace std;\nunordered_map<char, int> char_map;\nbool compare(string c1, string c2) {\n for (int i = 0; i < min(c1.size(), c2.size()); i++) {\n if (char_map[c1[i]] == char_map[c2[i]])\n continue;\n return char_map[c1[i]] < char_map[c2[i]];\n }\n return c1.size() < c2.size();\n}\nint main() {\n string str = \"pigvxbskyhqzelutoacfjrndmw\";\n vector<string> v{ \"hello\", \"programming\", \"science\", \"computer\", \"india\" };\n char_map.clear();\n for (int i = 0; i < str.size(); i++)\n char_map[str[i]] = i;\n sort(v.begin(), v.end(), compare);\n // Print the strings after sorting\n for (auto x : v)\n cout << x << \" \";\n}" }, { "code": null, "e": 2775, "s": 2734, "text": "programming india science hello computer" } ]
PLSQL | INSTR Function - GeeksforGeeks
20 Sep, 2019 The PLSQL INSTR function is used for returning the location of a substring in a string.The PLSQL INSTR function searches a string for a substring specified by the user using characters and returns the position in the string that is the first character of a specified occurrence of the substring.The PLSQL INSTR function accepts four parameters which are string, substring, start position and the nth appearance.The string and substring can be of any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Syntax: INSTR(string, substring [, start_position [, nth_appearance ]]) Parameters Used string –It is used to specify the string in which the substring needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.substring –It is used to specify the substring which needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.start_position –It is an optional parameter which is used to specify the position in the string from where the search will start. The default value is 1. The INSTR function counts back to start_position the number of characters from the end of the string and then searches towards the beginning of string if the value inserted is negative.nth appearance –It is an optional parameter which is used to specify the nth appearance of substring. The default value is 1. string –It is used to specify the string in which the substring needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. substring –It is used to specify the substring which needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. start_position –It is an optional parameter which is used to specify the position in the string from where the search will start. The default value is 1. The INSTR function counts back to start_position the number of characters from the end of the string and then searches towards the beginning of string if the value inserted is negative. nth appearance –It is an optional parameter which is used to specify the nth appearance of substring. The default value is 1. Supported Versions of Oracle/PLSQL: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: Using Character to Search Forward to Find the Position of a Substring. DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(INSTR(Test_String, 'e')); END; Output: 2 Example-2: Using Character Position to Search Forward to Find the Position of a Substring. DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(INSTR(Test_String, 'e', 1, 1)); END; Output: 2 Example-3: Using Character Position to Search Forward to Find the Position of a Substring in the 3rd position. DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(INSTR(Test_String, 'e', 1, 3)); END; Output: 10 Example-4: Using Character Position to Search Backward to Find the Position of a Substring. DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(INSTR(Test_String, 'e', -2, 1)); END; Output: 11 Example-5: Using a Triple-Byte Character Set to Find the Position of a Substring. DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(INSTR(Test_String, 'for', 1, 1)); END; Output: 6 SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database CTE in SQL SQL | Views How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
[ { "code": null, "e": 23948, "s": 23920, "text": "\n20 Sep, 2019" }, { "code": null, "e": 24473, "s": 23948, "text": "The PLSQL INSTR function is used for returning the location of a substring in a string.The PLSQL INSTR function searches a string for a substring specified by the user using characters and returns the position in the string that is the first character of a specified occurrence of the substring.The PLSQL INSTR function accepts four parameters which are string, substring, start position and the nth appearance.The string and substring can be of any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB." }, { "code": null, "e": 24481, "s": 24473, "text": "Syntax:" }, { "code": null, "e": 24545, "s": 24481, "text": "INSTR(string, substring [, start_position [, nth_appearance ]])" }, { "code": null, "e": 24561, "s": 24545, "text": "Parameters Used" }, { "code": null, "e": 25347, "s": 24561, "text": "string –It is used to specify the string in which the substring needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.substring –It is used to specify the substring which needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.start_position –It is an optional parameter which is used to specify the position in the string from where the search will start. The default value is 1. The INSTR function counts back to start_position the number of characters from the end of the string and then searches towards the beginning of string if the value inserted is negative.nth appearance –It is an optional parameter which is used to specify the nth appearance of substring. The default value is 1." }, { "code": null, "e": 25514, "s": 25347, "text": "string –It is used to specify the string in which the substring needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB." }, { "code": null, "e": 25670, "s": 25514, "text": "substring –It is used to specify the substring which needs to be searched. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB." }, { "code": null, "e": 26010, "s": 25670, "text": "start_position –It is an optional parameter which is used to specify the position in the string from where the search will start. The default value is 1. The INSTR function counts back to start_position the number of characters from the end of the string and then searches towards the beginning of string if the value inserted is negative." }, { "code": null, "e": 26136, "s": 26010, "text": "nth appearance –It is an optional parameter which is used to specify the nth appearance of substring. The default value is 1." }, { "code": null, "e": 26172, "s": 26136, "text": "Supported Versions of Oracle/PLSQL:" }, { "code": null, "e": 26221, "s": 26172, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 26232, "s": 26221, "text": "Oracle 12c" }, { "code": null, "e": 26243, "s": 26232, "text": "Oracle 11g" }, { "code": null, "e": 26254, "s": 26243, "text": "Oracle 10g" }, { "code": null, "e": 26264, "s": 26254, "text": "Oracle 9i" }, { "code": null, "e": 26274, "s": 26264, "text": "Oracle 8i" }, { "code": null, "e": 26356, "s": 26274, "text": "Example-1: Using Character to Search Forward to Find the Position of a Substring." }, { "code": null, "e": 26489, "s": 26356, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \n \nBEGIN \n dbms_output.put_line(INSTR(Test_String, 'e')); \n \nEND; " }, { "code": null, "e": 26497, "s": 26489, "text": "Output:" }, { "code": null, "e": 26500, "s": 26497, "text": "2 " }, { "code": null, "e": 26591, "s": 26500, "text": "Example-2: Using Character Position to Search Forward to Find the Position of a Substring." }, { "code": null, "e": 26729, "s": 26591, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(INSTR(Test_String, 'e', 1, 1)); \n \nEND; " }, { "code": null, "e": 26737, "s": 26729, "text": "Output:" }, { "code": null, "e": 26739, "s": 26737, "text": "2" }, { "code": null, "e": 26850, "s": 26739, "text": "Example-3: Using Character Position to Search Forward to Find the Position of a Substring in the 3rd position." }, { "code": null, "e": 26983, "s": 26850, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(INSTR(Test_String, 'e', 1, 3)); \n \nEND; " }, { "code": null, "e": 26991, "s": 26983, "text": "Output:" }, { "code": null, "e": 26995, "s": 26991, "text": "10 " }, { "code": null, "e": 27087, "s": 26995, "text": "Example-4: Using Character Position to Search Backward to Find the Position of a Substring." }, { "code": null, "e": 27222, "s": 27087, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(INSTR(Test_String, 'e', -2, 1)); \n \nEND; " }, { "code": null, "e": 27230, "s": 27222, "text": "Output:" }, { "code": null, "e": 27234, "s": 27230, "text": "11 " }, { "code": null, "e": 27316, "s": 27234, "text": "Example-5: Using a Triple-Byte Character Set to Find the Position of a Substring." }, { "code": null, "e": 27452, "s": 27316, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(INSTR(Test_String, 'for', 1, 1)); \n \nEND; " }, { "code": null, "e": 27460, "s": 27452, "text": "Output:" }, { "code": null, "e": 27463, "s": 27460, "text": "6 " }, { "code": null, "e": 27474, "s": 27463, "text": "SQL-PL/SQL" }, { "code": null, "e": 27478, "s": 27474, "text": "SQL" }, { "code": null, "e": 27482, "s": 27478, "text": "SQL" }, { "code": null, "e": 27580, "s": 27482, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27611, "s": 27580, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 27622, "s": 27611, "text": "CTE in SQL" }, { "code": null, "e": 27634, "s": 27622, "text": "SQL | Views" }, { "code": null, "e": 27700, "s": 27634, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27724, "s": 27700, "text": "SQL Interview Questions" }, { "code": null, "e": 27763, "s": 27724, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27808, "s": 27763, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27840, "s": 27808, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27872, "s": 27840, "text": "What is Temporary Table in SQL?" } ]
9 Reasons Why You Should Start Using Python Dataclasses | by Ahmed Besbes | Towards Data Science
Starting from version 3.7, Python has introduced dataclasses (see PEP 557), a new feature that defines classes that contain and encapsulate data. I recently started using this module in a couple of data science projects and I’m really enjoying it. Off the top of my head, I can think of two reasons: Less boilerplate codeMore readability and better code maintainability Less boilerplate code More readability and better code maintainability This post is a wrap-up of my first impressions: I’ll use it to introduce dataclasses and what problems they’re designed to solve and go through 9 nice features they provide. I’ll sometimes compare classes written with dataclasses to native Python implementations and spot the differences. Less talk, more code. Let’s have a look 🔍 PS: I won’t cover everything about dataclasses, but the features we’ll go through should get you up to speed. Nevertheless, if you want an in-depth overview, have a look at the links in the resources section at the end. Dataclasses, as the name clearly suggests, are classes that are meant to hold data. The motivation behind this module is that we sometimes define classes that only act as data containers and when we do that, we spend a consequent amount of time writing boilerplate code with tons of arguments, an ugly __init__ method and many overridden functions. Dataclasses alleviates this problem while providing additional useful methods under the hood. Moreover, since dataclasses is relatively new in the Python ecosystem, it enforces modern practices such as type annotations. 👉 dataclasses remain classes. Therefore, you can implement any custom methods in them just like you’d do in a normal class. Ok, let’s see them in action now. When we define a class to store some attributes, it usually goes something like this. This is the standard Python syntax. When you use dataclasses, you first have to import dataclass and then use it as a decorator before the class you define. And here’s what the previous code looks like using dataclasses. A few things to notice about this syntax: There is less boilerplate code: we define each attribute once and we don’t repeat ourselves We use type annotation for each attribute. Although this doesn’t enforce type validation, it helps your text editor provide better linting if you use a type checker like mypy.Your code would still work if you don’t respect the types but your code editor will signal the inconsistencies. dataclasses doesn’t just allow you to write more compact code. The dataclass decorator is actually a code generator that automatically adds other methods under the hood. If we use the inspectmodule to check what methods have been added to the Person class, we can see the __init__ , __eq__ and __repr__ methods: these methods are responsible for setting the attribute values, testing for equality and representing objects in a nice string format. If we allowed the Personclass to support order (see Tip number 9 about comparison), we’d have these methods as well. __ge__ : greater or equal __gt__ : greater than __le__ : lower or equal __lt__ : lower than You can add default values to each attribute while preserving the annotation. 👉 Keep in mind that fields without default values cannot appear after fields with default values. For example, the following code won’t work: Thanks to the __repr__ method already added by dataclasses, instances have a nice, human-readable representation when they are printed to the screen. This makes it easier for debugging. This representation can be overridden to implement any custom message you want. Instances can easily be serialized into dicts or tuples. This is very useful when your code interacts with other programs that expect these formats. Using dataclasses, you can create objects that are read-only. All you have to do is set the frozen argument to True inside the @dataclass decorator. When you do this, you prevent anyone from modifying the values of the attributes once the object is instantiated. If you try to set a frozen object’s attribute to a new value, a FrozenInstanceError error will be raised. When you define a class using the standard Python syntax and test for the equality between two instances that have the same attribute values, here’s what you’d get: These two objects are not equal, which is normal because the Personclass doesn’t actually implement a method for testing equality. To add equality, you’d have to implement the __eq__ method yourself. And this may look like this: This method first checks that the two objects are instances of the same class and then tests the equality between tuples of attributes. Now if you decide to add new attributes to your class, you’d have to update the __eq__ method again. The same goes for __ge__ , __gt__ ,__le__ and __lt__ if they’re used. This seems like unnecessary code typing, right? Fortunately, dataclasses removes this struggle. In some situations, you may need to create an attribute that is only defined internally, not when the class is instantiated. This may be the case when the attribute has a value that depends on previously-set attributes. Here’s where you’d use the field function from dataclasses. By using this function and setting itsinit and repr arguments to False to create a new field called full_name, we can still instantiate the Person class without setting the full_name attribute. This attribute doesn’t exist yet in the instance. If we try to access it, an AttributeError is thrown. How can we set the value of full_name and still keep it out of the constructor of the class? To do this, we’ll have to use the __post_init__method. dataclasses has a special method called __post_init__ . As the name clearly suggests, this method is called right after the __init__ method is called. Going back to the previous example, we can see how this method can be called to initialize an internal attribute that depends on previously set attributes. Note that the repr argument inside the field function has been set to True to make it visible when the object is printed. We couldn’t set this argument to True in the previous example because the attribute full_name has not been created yet. One useful feature to have when you deal with objects that contain data is the ability to compare them and sort them in any order you intend. By default, dataclasses implements __eq__ . To allow the other types of comparison (__lt__ (less than), __le__ (less or equal), __gt__ (greater than) and __ge__ (greater or equal)), we have to set the order argument to True in the@dataclass decorator. @dataclasses(order=True) The way these comparison methods are implemented take every defined field and compare them in the order they are defined until there’s a value that’s not equal. Let’s get back to the Person class. Say we want to compare the instances of this class based on the age attribute (which makes sense, right?). To do this, we’ll have to add a field, which we’ll call sort_index and set its value to the ageattribute’s value. And the way we’d do this is by calling the __post_init__ method we saw in the previous example. Now instances from the Person a class can be sorted with respect to the age attribute. Dataclasses provides many features that allow you to easily work with classes that act as data containers. In particular, this module helps to: write less boilerplate code represent objects in a readable format implement custom ordering and comparisons quickly access attributes and inspect them use special methods such as __post_init__ to perform initialization of attributes that depend on others define internal fields... While learning about dataclasses, I went through many resources (blog posts, Youtube videos, PEP, the official python documentation)Here’s a curated list of the most interesting posts and videos I’ve found. https://docs.python.org/3/library/dataclasses.html https://realpython.com/python-data-classes/ https://dev.to/dbanty/you-should-use-python-dataclass-lkc https://dev.to/isabelcmdcosta/dataclasses-in-python-are-nice-1fff https://youtu.be/vBH6GRJ1REM https://youtu.be/vRVVyl9uaZc https://medium.com/mindorks/understanding-python-dataclasses-part-1-c3ccd4355c34 (french blog post) https://www.invivoo.com/dataclasses-python/ https://florimond.dev/en/posts/2018/10/reconciling-dataclasses-and-properties-in-python/ If you’ve made it this far, I really thank you for your time. I hope I’ve shed some light on the different features that make dataclasses great and that I’ve convinced you to start using it. If you’re still not convinced, feel free to tell me what alternatives you use. I’d really love to hear about them. That’ll be all for me today. Until next time 👋
[ { "code": null, "e": 318, "s": 172, "text": "Starting from version 3.7, Python has introduced dataclasses (see PEP 557), a new feature that defines classes that contain and encapsulate data." }, { "code": null, "e": 472, "s": 318, "text": "I recently started using this module in a couple of data science projects and I’m really enjoying it. Off the top of my head, I can think of two reasons:" }, { "code": null, "e": 542, "s": 472, "text": "Less boilerplate codeMore readability and better code maintainability" }, { "code": null, "e": 564, "s": 542, "text": "Less boilerplate code" }, { "code": null, "e": 613, "s": 564, "text": "More readability and better code maintainability" }, { "code": null, "e": 902, "s": 613, "text": "This post is a wrap-up of my first impressions: I’ll use it to introduce dataclasses and what problems they’re designed to solve and go through 9 nice features they provide. I’ll sometimes compare classes written with dataclasses to native Python implementations and spot the differences." }, { "code": null, "e": 944, "s": 902, "text": "Less talk, more code. Let’s have a look 🔍" }, { "code": null, "e": 1164, "s": 944, "text": "PS: I won’t cover everything about dataclasses, but the features we’ll go through should get you up to speed. Nevertheless, if you want an in-depth overview, have a look at the links in the resources section at the end." }, { "code": null, "e": 1513, "s": 1164, "text": "Dataclasses, as the name clearly suggests, are classes that are meant to hold data. The motivation behind this module is that we sometimes define classes that only act as data containers and when we do that, we spend a consequent amount of time writing boilerplate code with tons of arguments, an ugly __init__ method and many overridden functions." }, { "code": null, "e": 1733, "s": 1513, "text": "Dataclasses alleviates this problem while providing additional useful methods under the hood. Moreover, since dataclasses is relatively new in the Python ecosystem, it enforces modern practices such as type annotations." }, { "code": null, "e": 1857, "s": 1733, "text": "👉 dataclasses remain classes. Therefore, you can implement any custom methods in them just like you’d do in a normal class." }, { "code": null, "e": 1891, "s": 1857, "text": "Ok, let’s see them in action now." }, { "code": null, "e": 1977, "s": 1891, "text": "When we define a class to store some attributes, it usually goes something like this." }, { "code": null, "e": 2013, "s": 1977, "text": "This is the standard Python syntax." }, { "code": null, "e": 2134, "s": 2013, "text": "When you use dataclasses, you first have to import dataclass and then use it as a decorator before the class you define." }, { "code": null, "e": 2198, "s": 2134, "text": "And here’s what the previous code looks like using dataclasses." }, { "code": null, "e": 2240, "s": 2198, "text": "A few things to notice about this syntax:" }, { "code": null, "e": 2332, "s": 2240, "text": "There is less boilerplate code: we define each attribute once and we don’t repeat ourselves" }, { "code": null, "e": 2619, "s": 2332, "text": "We use type annotation for each attribute. Although this doesn’t enforce type validation, it helps your text editor provide better linting if you use a type checker like mypy.Your code would still work if you don’t respect the types but your code editor will signal the inconsistencies." }, { "code": null, "e": 3066, "s": 2619, "text": "dataclasses doesn’t just allow you to write more compact code. The dataclass decorator is actually a code generator that automatically adds other methods under the hood. If we use the inspectmodule to check what methods have been added to the Person class, we can see the __init__ , __eq__ and __repr__ methods: these methods are responsible for setting the attribute values, testing for equality and representing objects in a nice string format." }, { "code": null, "e": 3183, "s": 3066, "text": "If we allowed the Personclass to support order (see Tip number 9 about comparison), we’d have these methods as well." }, { "code": null, "e": 3209, "s": 3183, "text": "__ge__ : greater or equal" }, { "code": null, "e": 3231, "s": 3209, "text": "__gt__ : greater than" }, { "code": null, "e": 3255, "s": 3231, "text": "__le__ : lower or equal" }, { "code": null, "e": 3275, "s": 3255, "text": "__lt__ : lower than" }, { "code": null, "e": 3353, "s": 3275, "text": "You can add default values to each attribute while preserving the annotation." }, { "code": null, "e": 3495, "s": 3353, "text": "👉 Keep in mind that fields without default values cannot appear after fields with default values. For example, the following code won’t work:" }, { "code": null, "e": 3645, "s": 3495, "text": "Thanks to the __repr__ method already added by dataclasses, instances have a nice, human-readable representation when they are printed to the screen." }, { "code": null, "e": 3681, "s": 3645, "text": "This makes it easier for debugging." }, { "code": null, "e": 3761, "s": 3681, "text": "This representation can be overridden to implement any custom message you want." }, { "code": null, "e": 3910, "s": 3761, "text": "Instances can easily be serialized into dicts or tuples. This is very useful when your code interacts with other programs that expect these formats." }, { "code": null, "e": 4059, "s": 3910, "text": "Using dataclasses, you can create objects that are read-only. All you have to do is set the frozen argument to True inside the @dataclass decorator." }, { "code": null, "e": 4173, "s": 4059, "text": "When you do this, you prevent anyone from modifying the values of the attributes once the object is instantiated." }, { "code": null, "e": 4279, "s": 4173, "text": "If you try to set a frozen object’s attribute to a new value, a FrozenInstanceError error will be raised." }, { "code": null, "e": 4444, "s": 4279, "text": "When you define a class using the standard Python syntax and test for the equality between two instances that have the same attribute values, here’s what you’d get:" }, { "code": null, "e": 4673, "s": 4444, "text": "These two objects are not equal, which is normal because the Personclass doesn’t actually implement a method for testing equality. To add equality, you’d have to implement the __eq__ method yourself. And this may look like this:" }, { "code": null, "e": 4809, "s": 4673, "text": "This method first checks that the two objects are instances of the same class and then tests the equality between tuples of attributes." }, { "code": null, "e": 4980, "s": 4809, "text": "Now if you decide to add new attributes to your class, you’d have to update the __eq__ method again. The same goes for __ge__ , __gt__ ,__le__ and __lt__ if they’re used." }, { "code": null, "e": 5076, "s": 4980, "text": "This seems like unnecessary code typing, right? Fortunately, dataclasses removes this struggle." }, { "code": null, "e": 5296, "s": 5076, "text": "In some situations, you may need to create an attribute that is only defined internally, not when the class is instantiated. This may be the case when the attribute has a value that depends on previously-set attributes." }, { "code": null, "e": 5356, "s": 5296, "text": "Here’s where you’d use the field function from dataclasses." }, { "code": null, "e": 5550, "s": 5356, "text": "By using this function and setting itsinit and repr arguments to False to create a new field called full_name, we can still instantiate the Person class without setting the full_name attribute." }, { "code": null, "e": 5653, "s": 5550, "text": "This attribute doesn’t exist yet in the instance. If we try to access it, an AttributeError is thrown." }, { "code": null, "e": 5801, "s": 5653, "text": "How can we set the value of full_name and still keep it out of the constructor of the class? To do this, we’ll have to use the __post_init__method." }, { "code": null, "e": 5857, "s": 5801, "text": "dataclasses has a special method called __post_init__ ." }, { "code": null, "e": 5952, "s": 5857, "text": "As the name clearly suggests, this method is called right after the __init__ method is called." }, { "code": null, "e": 6108, "s": 5952, "text": "Going back to the previous example, we can see how this method can be called to initialize an internal attribute that depends on previously set attributes." }, { "code": null, "e": 6350, "s": 6108, "text": "Note that the repr argument inside the field function has been set to True to make it visible when the object is printed. We couldn’t set this argument to True in the previous example because the attribute full_name has not been created yet." }, { "code": null, "e": 6492, "s": 6350, "text": "One useful feature to have when you deal with objects that contain data is the ability to compare them and sort them in any order you intend." }, { "code": null, "e": 6744, "s": 6492, "text": "By default, dataclasses implements __eq__ . To allow the other types of comparison (__lt__ (less than), __le__ (less or equal), __gt__ (greater than) and __ge__ (greater or equal)), we have to set the order argument to True in the@dataclass decorator." }, { "code": null, "e": 6769, "s": 6744, "text": "@dataclasses(order=True)" }, { "code": null, "e": 6930, "s": 6769, "text": "The way these comparison methods are implemented take every defined field and compare them in the order they are defined until there’s a value that’s not equal." }, { "code": null, "e": 7073, "s": 6930, "text": "Let’s get back to the Person class. Say we want to compare the instances of this class based on the age attribute (which makes sense, right?)." }, { "code": null, "e": 7187, "s": 7073, "text": "To do this, we’ll have to add a field, which we’ll call sort_index and set its value to the ageattribute’s value." }, { "code": null, "e": 7283, "s": 7187, "text": "And the way we’d do this is by calling the __post_init__ method we saw in the previous example." }, { "code": null, "e": 7370, "s": 7283, "text": "Now instances from the Person a class can be sorted with respect to the age attribute." }, { "code": null, "e": 7477, "s": 7370, "text": "Dataclasses provides many features that allow you to easily work with classes that act as data containers." }, { "code": null, "e": 7514, "s": 7477, "text": "In particular, this module helps to:" }, { "code": null, "e": 7542, "s": 7514, "text": "write less boilerplate code" }, { "code": null, "e": 7581, "s": 7542, "text": "represent objects in a readable format" }, { "code": null, "e": 7623, "s": 7581, "text": "implement custom ordering and comparisons" }, { "code": null, "e": 7666, "s": 7623, "text": "quickly access attributes and inspect them" }, { "code": null, "e": 7770, "s": 7666, "text": "use special methods such as __post_init__ to perform initialization of attributes that depend on others" }, { "code": null, "e": 7796, "s": 7770, "text": "define internal fields..." }, { "code": null, "e": 8003, "s": 7796, "text": "While learning about dataclasses, I went through many resources (blog posts, Youtube videos, PEP, the official python documentation)Here’s a curated list of the most interesting posts and videos I’ve found." }, { "code": null, "e": 8054, "s": 8003, "text": "https://docs.python.org/3/library/dataclasses.html" }, { "code": null, "e": 8098, "s": 8054, "text": "https://realpython.com/python-data-classes/" }, { "code": null, "e": 8156, "s": 8098, "text": "https://dev.to/dbanty/you-should-use-python-dataclass-lkc" }, { "code": null, "e": 8222, "s": 8156, "text": "https://dev.to/isabelcmdcosta/dataclasses-in-python-are-nice-1fff" }, { "code": null, "e": 8251, "s": 8222, "text": "https://youtu.be/vBH6GRJ1REM" }, { "code": null, "e": 8280, "s": 8251, "text": "https://youtu.be/vRVVyl9uaZc" }, { "code": null, "e": 8361, "s": 8280, "text": "https://medium.com/mindorks/understanding-python-dataclasses-part-1-c3ccd4355c34" }, { "code": null, "e": 8424, "s": 8361, "text": "(french blog post) https://www.invivoo.com/dataclasses-python/" }, { "code": null, "e": 8513, "s": 8424, "text": "https://florimond.dev/en/posts/2018/10/reconciling-dataclasses-and-properties-in-python/" }, { "code": null, "e": 8575, "s": 8513, "text": "If you’ve made it this far, I really thank you for your time." }, { "code": null, "e": 8704, "s": 8575, "text": "I hope I’ve shed some light on the different features that make dataclasses great and that I’ve convinced you to start using it." }, { "code": null, "e": 8819, "s": 8704, "text": "If you’re still not convinced, feel free to tell me what alternatives you use. I’d really love to hear about them." } ]
numpy string operations | rjust() function - GeeksforGeeks
05 Feb, 2019 numpy.core.defchararray.rjust(arr, width, fillchar=' ') is another function for doing string operations in numpy. It returns an array with the elements of arr right-justified in a string of length width.It fills remaining space of each array element using fillchr parameter.If fillchr is not passed then it fills remaining spaces with blank space. Parameters:arr : array_like of str or unicode.Input array.width : The final width of the each string .fillchar : The character to fill in remaining space. Returns : [ndarray] Output right justified array of str or unicode, depending on input type. Code #1 : # Python program explaining# numpy.char.rjust() method # importing numpy import numpy as geek # input array in_arr = geek.array(['Numpy', 'Python', 'Pandas'])print ("Input array : ", in_arr) # setting the width of each string to 8width = 8 # output array when fillchar is not passedout_arr = geek.char.rjust(in_arr, width)print ("Output right justified array: ", out_arr) Input array : ['Numpy' 'Python' 'Pandas'] Output right justified array: [' Numpy' ' Python' ' Pandas'] Code #2 : # Python program explaining# numpy.char.rjust() method # importing numpy import numpy as geek # input array in_arr = geek.array(['Numpy', 'Python', 'Pandas'])print ("Input array : ", in_arr) # setting the width of each string to 8width = 8 # output array out_arr = geek.char.rjust(in_arr, width, fillchar ='*')print ("Output right justified array: ", out_arr) Input array : ['Numpy' 'Python' 'Pandas'] Output right justified array: ['***Numpy' '**Python' '**Pandas'] Code #3 : # Python program explaining# numpy.char.rjust() method # importing numpy import numpy as geek # input array in_arr = geek.array(['1', '11', '111'])print ("Input array : ", in_arr) # setting the width of each string to 5width = 5 # output arrayout_arr = geek.char.rjust(in_arr, width, fillchar ='-')print ("Output right justified array: ", out_arr) Input array : ['1' '11' '111'] Output right justified array: ['----1' '---11' '--111'] Python numpy-String Operation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 25344, "s": 25316, "text": "\n05 Feb, 2019" }, { "code": null, "e": 25692, "s": 25344, "text": "numpy.core.defchararray.rjust(arr, width, fillchar=' ') is another function for doing string operations in numpy. It returns an array with the elements of arr right-justified in a string of length width.It fills remaining space of each array element using fillchr parameter.If fillchr is not passed then it fills remaining spaces with blank space." }, { "code": null, "e": 25847, "s": 25692, "text": "Parameters:arr : array_like of str or unicode.Input array.width : The final width of the each string .fillchar : The character to fill in remaining space." }, { "code": null, "e": 25940, "s": 25847, "text": "Returns : [ndarray] Output right justified array of str or unicode, depending on input type." }, { "code": null, "e": 25950, "s": 25940, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.char.rjust() method # importing numpy import numpy as geek # input array in_arr = geek.array(['Numpy', 'Python', 'Pandas'])print (\"Input array : \", in_arr) # setting the width of each string to 8width = 8 # output array when fillchar is not passedout_arr = geek.char.rjust(in_arr, width)print (\"Output right justified array: \", out_arr) ", "e": 26330, "s": 25950, "text": null }, { "code": null, "e": 26440, "s": 26330, "text": "Input array : ['Numpy' 'Python' 'Pandas']\nOutput right justified array: [' Numpy' ' Python' ' Pandas']\n" }, { "code": null, "e": 26452, "s": 26442, "text": "Code #2 :" }, { "code": "# Python program explaining# numpy.char.rjust() method # importing numpy import numpy as geek # input array in_arr = geek.array(['Numpy', 'Python', 'Pandas'])print (\"Input array : \", in_arr) # setting the width of each string to 8width = 8 # output array out_arr = geek.char.rjust(in_arr, width, fillchar ='*')print (\"Output right justified array: \", out_arr) ", "e": 26820, "s": 26452, "text": null }, { "code": null, "e": 26930, "s": 26820, "text": "Input array : ['Numpy' 'Python' 'Pandas']\nOutput right justified array: ['***Numpy' '**Python' '**Pandas']\n" }, { "code": null, "e": 26942, "s": 26932, "text": "Code #3 :" }, { "code": "# Python program explaining# numpy.char.rjust() method # importing numpy import numpy as geek # input array in_arr = geek.array(['1', '11', '111'])print (\"Input array : \", in_arr) # setting the width of each string to 5width = 5 # output arrayout_arr = geek.char.rjust(in_arr, width, fillchar ='-')print (\"Output right justified array: \", out_arr) ", "e": 27297, "s": 26942, "text": null }, { "code": null, "e": 27387, "s": 27297, "text": "Input array : ['1' '11' '111']\nOutput right justified array: ['----1' '---11' '--111']\n" }, { "code": null, "e": 27417, "s": 27387, "text": "Python numpy-String Operation" }, { "code": null, "e": 27430, "s": 27417, "text": "Python-numpy" }, { "code": null, "e": 27437, "s": 27430, "text": "Python" }, { "code": null, "e": 27535, "s": 27437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27553, "s": 27535, "text": "Python Dictionary" }, { "code": null, "e": 27588, "s": 27553, "text": "Read a file line by line in Python" }, { "code": null, "e": 27610, "s": 27588, "text": "Enumerate() in Python" }, { "code": null, "e": 27642, "s": 27610, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27672, "s": 27642, "text": "Iterate over a list in Python" }, { "code": null, "e": 27714, "s": 27672, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27751, "s": 27714, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27794, "s": 27751, "text": "Python program to convert a list to string" }, { "code": null, "e": 27838, "s": 27794, "text": "Reading and Writing to text files in Python" } ]
How to call a function after a delay in Kotlin?
Kotlin is based on Java, hence we can use Java-based library functions to delay a function call. In this article, we will be using a Java library function to delay the function call using Timer() and schedule(). import java.util.Timer import kotlin.concurrent.schedule fun main(args: Array<String>) { // Execution starting point println("Hello world!!") // Delay of 5 sec Timer().schedule(5000){ //calling a function newMethod() } } fun newMethod(){ println("Delayed method call!") } Once executed, the above piece of code will yield the following output − Hello world!! Delayed method call!
[ { "code": null, "e": 1274, "s": 1062, "text": "Kotlin is based on Java, hence we can use Java-based library functions to delay a function call. In this article, we will be using a Java library function to delay the function call using Timer() and schedule()." }, { "code": null, "e": 1581, "s": 1274, "text": "import java.util.Timer\nimport kotlin.concurrent.schedule\n\nfun main(args: Array<String>) {\n\n // Execution starting point\n println(\"Hello world!!\")\n\n // Delay of 5 sec\n Timer().schedule(5000){\n\n //calling a function\n newMethod()\n }\n}\n\nfun newMethod(){\n println(\"Delayed method call!\")\n}" }, { "code": null, "e": 1654, "s": 1581, "text": "Once executed, the above piece of code will yield the following output −" }, { "code": null, "e": 1689, "s": 1654, "text": "Hello world!!\nDelayed method call!" } ]
Java Image Translation example using OpenCV.
The warpAffine() method of the Imgproc class applies an affine transformation to the specified image. This method accepts − Three Mat objects representing the source, destination, and transformation matrices. Three Mat objects representing the source, destination, and transformation matrices. An integer value representing the size of the output image. An integer value representing the size of the output image. To translate an image Create a translation matrix and pass it as a transformation matrix to this method along with the other parameters. import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.Size; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class TranslatingAnImage extends Application { public void start(Stage stage) throws IOException { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading image data String file ="D:\\Images\\elephant.jpg"; Mat src = Imgcodecs.imread(file); //Creating destination matrix Mat dst = new Mat(src.rows(), src.cols(), src.type()); Point p1 = new Point( 0,0 ); Point p2 = new Point( src.cols() - 1, 0 ); Point p3 = new Point( 0, src.rows() - 1 ); Point p4 = new Point( src.cols()*0.0, src.rows()*0.33 ); Point p5 = new Point( src.cols()*0.85, src.rows()*0.25 ); Point p6 = new Point( src.cols()*0.15, src.rows()*0.7 ); MatOfPoint2f ma1 = new MatOfPoint2f(p1,p2,p3); MatOfPoint2f ma2 = new MatOfPoint2f(p4,p5,p6); //Creating the transformation matrix Mat tranformMatrix = Imgproc.getAffineTransform(ma1,ma2); //Creating object of the class Size Size size = new Size(src.cols(), src.cols()); //Applying Wrap Affine Imgproc.warpAffine(src, dst, tranformMatrix, size); //Converting matrix to JavaFX writable image Image img = HighGui.toBufferedImage(dst); WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null); //Setting the image view ImageView imageView = new ImageView(writableImage); imageView.setX(10); imageView.setY(10); imageView.setFitWidth(575); imageView.setPreserveRatio(true); //Setting the Scene object Group root = new Group(imageView); Scene scene = new Scene(root, 595, 400); stage.setTitle("Image Translation example"); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } } On executing the above program generates the following output −
[ { "code": null, "e": 1186, "s": 1062, "text": "The warpAffine() method of the Imgproc class applies an affine transformation to the specified image. This method accepts −" }, { "code": null, "e": 1271, "s": 1186, "text": "Three Mat objects representing the source, destination, and transformation\nmatrices." }, { "code": null, "e": 1356, "s": 1271, "text": "Three Mat objects representing the source, destination, and transformation\nmatrices." }, { "code": null, "e": 1416, "s": 1356, "text": "An integer value representing the size of the output image." }, { "code": null, "e": 1476, "s": 1416, "text": "An integer value representing the size of the output image." }, { "code": null, "e": 1613, "s": 1476, "text": "To translate an image Create a translation matrix and pass it as a transformation matrix to this method along with the other parameters." }, { "code": null, "e": 4029, "s": 1613, "text": "import java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfPoint2f;\nimport org.opencv.core.Point;\nimport org.opencv.core.Size;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class TranslatingAnImage extends Application {\n public void start(Stage stage) throws IOException {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\elephant.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n Point p1 = new Point( 0,0 );\n Point p2 = new Point( src.cols() - 1, 0 );\n Point p3 = new Point( 0, src.rows() - 1 );\n Point p4 = new Point( src.cols()*0.0, src.rows()*0.33 );\n Point p5 = new Point( src.cols()*0.85, src.rows()*0.25 );\n Point p6 = new Point( src.cols()*0.15, src.rows()*0.7 );\n MatOfPoint2f ma1 = new MatOfPoint2f(p1,p2,p3);\n MatOfPoint2f ma2 = new MatOfPoint2f(p4,p5,p6);\n //Creating the transformation matrix\n Mat tranformMatrix = Imgproc.getAffineTransform(ma1,ma2);\n //Creating object of the class Size\n Size size = new Size(src.cols(), src.cols());\n //Applying Wrap Affine\n Imgproc.warpAffine(src, dst, tranformMatrix, size);\n //Converting matrix to JavaFX writable image\n Image img = HighGui.toBufferedImage(dst);\n WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);\n //Setting the image view\n ImageView imageView = new ImageView(writableImage);\n imageView.setX(10);\n imageView.setY(10);\n imageView.setFitWidth(575);\n imageView.setPreserveRatio(true);\n //Setting the Scene object\n Group root = new Group(imageView);\n Scene scene = new Scene(root, 595, 400);\n stage.setTitle(\"Image Translation example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 4093, "s": 4029, "text": "On executing the above program generates the following output −" } ]
Python – Group and calculate the sum of column values of a Pandas DataFrame
We will consider an example of Car Sale Records and group month-wise to calculate the sum of Registration Price of car monthly. To sum, we use the sum() method. At first, let’s say the following is our Pandas DataFrame with three columns − dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"], "Date_of_Purchase": [ pd.Timestamp("2021-06-10"), pd.Timestamp("2021-07-11"), pd.Timestamp("2021-06-25"), pd.Timestamp("2021-06-29"), pd.Timestamp("2021-03-20"), pd.Timestamp("2021-01-22"), pd.Timestamp("2021-01-06"), pd.Timestamp("2021-01-04"), pd.Timestamp("2021-05-09") ], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] } ) Use the Grouper to select Date_of_Purchase column within groupby() function. The frequency freq is set ‘M’ to group by month-wise and sum is calculates using the sum() function − print"\nGroup Dataframe by month...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum() Following is the code − import pandas as pd # dataframe with one of the columns as Date_of_Purchase dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"], "Date_of_Purchase": [ pd.Timestamp("2021-06-10"), pd.Timestamp("2021-07-11"), pd.Timestamp("2021-06-25"), pd.Timestamp("2021-06-29"), pd.Timestamp("2021-03-20"), pd.Timestamp("2021-01-22"), pd.Timestamp("2021-01-06"), pd.Timestamp("2021-01-04"), pd.Timestamp("2021-05-09") ], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] } ) print"DataFrame...\n",dataFrame # Grouper to select Date_of_Purchase column within groupby function # calculation the sum month-wise print"\nGroup Dataframe by month...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum() This will produce the following output − DataFrame... Car Date_of_Purchase Reg_Price 0 Audi 2021-06-10 1000 1 Lexus 2021-07-11 1400 2 Tesla 2021-06-25 1100 3 Mercedes 2021-06-29 900 4 BMW 2021-03-20 1700 5 Toyota 2021-01-22 1800 6 Nissan 2021-01-06 1300 7 Bentley 2021-01-04 1150 8 Mustang 2021-05-09 1350 Group Dataframe by month... Reg_Price Date_of_Purchase 2021-01-31 4250.0 2021-02-28 NaN 2021-03-31 1700.0 2021-04-30 NaN 2021-05-31 1350.0 2021-06-30 3000.0 2021-07-31 1400.0
[ { "code": null, "e": 1223, "s": 1062, "text": "We will consider an example of Car Sale Records and group month-wise to calculate the sum of Registration Price of car monthly. To sum, we use the sum() method." }, { "code": null, "e": 1302, "s": 1223, "text": "At first, let’s say the following is our Pandas DataFrame with three columns −" }, { "code": null, "e": 1888, "s": 1302, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\", \"Toyota\", \"Nissan\", \"Bentley\", \"Mustang\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n pd.Timestamp(\"2021-01-22\"),\n pd.Timestamp(\"2021-01-06\"),\n pd.Timestamp(\"2021-01-04\"),\n pd.Timestamp(\"2021-05-09\")\n ],\n\n \"Reg_Price\": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]\n }\n)\n\n" }, { "code": null, "e": 2067, "s": 1888, "text": "Use the Grouper to select Date_of_Purchase column within groupby() function. The frequency freq is set ‘M’ to group by month-wise and sum is calculates using the sum() function −" }, { "code": null, "e": 2184, "s": 2067, "text": "print\"\\nGroup Dataframe by month...\\n\",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum()" }, { "code": null, "e": 2208, "s": 2184, "text": "Following is the code −" }, { "code": null, "e": 3123, "s": 2208, "text": "import pandas as pd\n\n# dataframe with one of the columns as Date_of_Purchase\ndataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\", \"Toyota\", \"Nissan\", \"Bentley\", \"Mustang\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n pd.Timestamp(\"2021-01-22\"),\n pd.Timestamp(\"2021-01-06\"),\n pd.Timestamp(\"2021-01-04\"),\n pd.Timestamp(\"2021-05-09\")\n ],\n\n \"Reg_Price\": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]\n }\n)\n\nprint\"DataFrame...\\n\",dataFrame\n\n# Grouper to select Date_of_Purchase column within groupby function\n# calculation the sum month-wise\nprint\"\\nGroup Dataframe by month...\\n\",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum()\n\n" }, { "code": null, "e": 3164, "s": 3123, "text": "This will produce the following output −" }, { "code": null, "e": 3869, "s": 3164, "text": "DataFrame...\n Car Date_of_Purchase Reg_Price\n0 Audi 2021-06-10 1000\n1 Lexus 2021-07-11 1400\n2 Tesla 2021-06-25 1100\n3 Mercedes 2021-06-29 900\n4 BMW 2021-03-20 1700\n5 Toyota 2021-01-22 1800\n6 Nissan 2021-01-06 1300\n7 Bentley 2021-01-04 1150\n8 Mustang 2021-05-09 1350\n\nGroup Dataframe by month...\n Reg_Price\nDate_of_Purchase\n2021-01-31 4250.0\n2021-02-28 NaN\n2021-03-31 1700.0\n2021-04-30 NaN\n2021-05-31 1350.0\n2021-06-30 3000.0\n2021-07-31 1400.0" } ]
WebAssembly - Program Structure
WebAssembly, also called WASM, is binary format low level code developed to be executed inside browsers in the most efficient way. WebAssembly code is structured with following concepts − Values Types Instructions Let us learn them in detail now. Values in WebAssembly are meant to store complex data such as text, strings and vectors. WebAssembly supports the following − Bytes Integers Floating point Names Bytes is the simplest form of values supported in WebAssembly. The value is in hexadecimal format. Bytes represented as b, can also take natural numbers n, where n <256. byte ::= 0x00| .... |0xFF In WebAssembly, integers supported are as given below − i32: 32-bit integer i64: 64-bit integer In WebAssembly floating point numbers supported are as follows − f32: 32-bit floating point f64: 64-bit floating point Names are sequence of character, with scalar values defined by Unicode, which is available at the link http://www.unicode.org/versions/Unicode12.1.0/ given herewith. The entities in WebAssembly are classified as types. The types supported are as stated below − Value Types Result Types Function Types Limits Memory Types Table Types Global Types External Types Let us study them one by one. The values type supported by WebAssembly are as mentioned below − i32: 32-bit integer i64: 64-bit integer f32: 32-bit floating point f64: 64-bit floating point valtype ::= i32|i64|f32|f64 The values written inside brackets are executed and stored inside result types. The result type is the output of the execution of a block of code made up of values. resulttype::=[valtype?] A function type will take in vector of parameters returns a vector of results. functype::=[vec(valtype)]--> [vec(valtype)] Limits are the storage range linked with memory and table types. limits ::= {min u32, max u32} Memory types deal with linear memories and the size range. memtype ::= limits Table Types are classified by the element type assigned to it. tabletype ::= limits elemtype elemtype ::= funcref Table type is dependent on the limit for the minimum and maximum size assigned to it. Global Type holds the global variables that have the value, that can change or remain the same. globaltype ::= mut valtype mut ::= const|var External Types deals with imports and external values. externtype ::= func functype | table tabletype | mem memtype | global globaltype WebAssembly code is a sequence of instructions that follows a stack machine model. As WebAssembly follows a stack machine model, the instructions are pushed on the stack. The argument values for a function, for example, are popped from stack and the result is pushed back on the stack. In the end, there will be only one value in the stack and that is the result. Some of the commonly used Instructions are as follows − Numeric Instructions Variable Instructions Numeric Instructions are operations, which are performed on numeric value. nn, mm ::= 32|64 ibinop ::= add|sub|mul|div_sx|rem_sx|and|or|xor irelop ::= eq | ne | lt_sx | gt_sx | le_sx | ge_sx frelop ::= eq | ne | lt | gt | le | ge Variable instructions are about accessing the local and global variables. For example To access local variables − get_local $a get_local $b To set local variables − set_local $a set_local $b To access global variables − get_global $a get_global $b To set global variables − set_global $a set_global $b Print Add Notes Bookmark this page
[ { "code": null, "e": 2421, "s": 2233, "text": "WebAssembly, also called WASM, is binary format low level code developed to be executed inside browsers in the most efficient way. WebAssembly code is structured with following concepts −" }, { "code": null, "e": 2428, "s": 2421, "text": "Values" }, { "code": null, "e": 2434, "s": 2428, "text": "Types" }, { "code": null, "e": 2447, "s": 2434, "text": "Instructions" }, { "code": null, "e": 2480, "s": 2447, "text": "Let us learn them in detail now." }, { "code": null, "e": 2606, "s": 2480, "text": "Values in WebAssembly are meant to store complex data such as text, strings and vectors. WebAssembly supports the following −" }, { "code": null, "e": 2612, "s": 2606, "text": "Bytes" }, { "code": null, "e": 2621, "s": 2612, "text": "Integers" }, { "code": null, "e": 2636, "s": 2621, "text": "Floating point" }, { "code": null, "e": 2642, "s": 2636, "text": "Names" }, { "code": null, "e": 2741, "s": 2642, "text": "Bytes is the simplest form of values supported in WebAssembly. The value is in hexadecimal format." }, { "code": null, "e": 2812, "s": 2741, "text": "Bytes represented as b, can also take natural numbers n, where n <256." }, { "code": null, "e": 2839, "s": 2812, "text": "byte ::= 0x00| .... |0xFF\n" }, { "code": null, "e": 2895, "s": 2839, "text": "In WebAssembly, integers supported are as given below −" }, { "code": null, "e": 2915, "s": 2895, "text": "i32: 32-bit integer" }, { "code": null, "e": 2935, "s": 2915, "text": "i64: 64-bit integer" }, { "code": null, "e": 3000, "s": 2935, "text": "In WebAssembly floating point numbers supported are as follows −" }, { "code": null, "e": 3027, "s": 3000, "text": "f32: 32-bit floating point" }, { "code": null, "e": 3054, "s": 3027, "text": "f64: 64-bit floating point" }, { "code": null, "e": 3220, "s": 3054, "text": "Names are sequence of character, with scalar values defined by Unicode, which is available at the link http://www.unicode.org/versions/Unicode12.1.0/ given herewith." }, { "code": null, "e": 3315, "s": 3220, "text": "The entities in WebAssembly are classified as types. The types supported are as stated below −" }, { "code": null, "e": 3327, "s": 3315, "text": "Value Types" }, { "code": null, "e": 3340, "s": 3327, "text": "Result Types" }, { "code": null, "e": 3355, "s": 3340, "text": "Function Types" }, { "code": null, "e": 3362, "s": 3355, "text": "Limits" }, { "code": null, "e": 3375, "s": 3362, "text": "Memory Types" }, { "code": null, "e": 3387, "s": 3375, "text": "Table Types" }, { "code": null, "e": 3400, "s": 3387, "text": "Global Types" }, { "code": null, "e": 3415, "s": 3400, "text": "External Types" }, { "code": null, "e": 3445, "s": 3415, "text": "Let us study them one by one." }, { "code": null, "e": 3511, "s": 3445, "text": "The values type supported by WebAssembly are as mentioned below −" }, { "code": null, "e": 3531, "s": 3511, "text": "i32: 32-bit integer" }, { "code": null, "e": 3551, "s": 3531, "text": "i64: 64-bit integer" }, { "code": null, "e": 3578, "s": 3551, "text": "f32: 32-bit floating point" }, { "code": null, "e": 3605, "s": 3578, "text": "f64: 64-bit floating point" }, { "code": null, "e": 3634, "s": 3605, "text": "valtype ::= i32|i64|f32|f64\n" }, { "code": null, "e": 3799, "s": 3634, "text": "The values written inside brackets are executed and stored inside result types. The result type is the output of the execution of a block of code made up of values." }, { "code": null, "e": 3824, "s": 3799, "text": "resulttype::=[valtype?]\n" }, { "code": null, "e": 3903, "s": 3824, "text": "A function type will take in vector of parameters returns a vector of results." }, { "code": null, "e": 3948, "s": 3903, "text": "functype::=[vec(valtype)]--> [vec(valtype)]\n" }, { "code": null, "e": 4013, "s": 3948, "text": "Limits are the storage range linked with memory and table types." }, { "code": null, "e": 4044, "s": 4013, "text": "limits ::= {min u32, max u32}\n" }, { "code": null, "e": 4103, "s": 4044, "text": "Memory types deal with linear memories and the size range." }, { "code": null, "e": 4123, "s": 4103, "text": "memtype ::= limits\n" }, { "code": null, "e": 4186, "s": 4123, "text": "Table Types are classified by the element type assigned to it." }, { "code": null, "e": 4238, "s": 4186, "text": "tabletype ::= limits elemtype\nelemtype ::= funcref\n" }, { "code": null, "e": 4324, "s": 4238, "text": "Table type is dependent on the limit for the minimum and maximum size assigned to it." }, { "code": null, "e": 4420, "s": 4324, "text": "Global Type holds the global variables that have the value, that can change or remain the same." }, { "code": null, "e": 4466, "s": 4420, "text": "globaltype ::= mut valtype\nmut ::= const|var\n" }, { "code": null, "e": 4521, "s": 4466, "text": "External Types deals with imports and external values." }, { "code": null, "e": 4603, "s": 4521, "text": "externtype ::= func functype | table tabletype | mem memtype | global globaltype\n" }, { "code": null, "e": 4774, "s": 4603, "text": "WebAssembly code is a sequence of instructions that follows a stack machine model. As WebAssembly follows a stack machine model, the instructions are pushed on the stack." }, { "code": null, "e": 4967, "s": 4774, "text": "The argument values for a function, for example, are popped from stack and the result is pushed back on the stack. In the end, there will be only one value in the stack and that is the result." }, { "code": null, "e": 5023, "s": 4967, "text": "Some of the commonly used Instructions are as follows −" }, { "code": null, "e": 5044, "s": 5023, "text": "Numeric Instructions" }, { "code": null, "e": 5066, "s": 5044, "text": "Variable Instructions" }, { "code": null, "e": 5141, "s": 5066, "text": "Numeric Instructions are operations, which are performed on numeric value." }, { "code": null, "e": 5297, "s": 5141, "text": "nn, mm ::= 32|64\nibinop ::= add|sub|mul|div_sx|rem_sx|and|or|xor\nirelop ::= eq | ne | lt_sx | gt_sx | le_sx | ge_sx\nfrelop ::= eq | ne | lt | gt | le | ge\n" }, { "code": null, "e": 5371, "s": 5297, "text": "Variable instructions are about accessing the local and global variables." }, { "code": null, "e": 5383, "s": 5371, "text": "For example" }, { "code": null, "e": 5411, "s": 5383, "text": "To access local variables −" }, { "code": null, "e": 5438, "s": 5411, "text": "get_local $a\nget_local $b\n" }, { "code": null, "e": 5463, "s": 5438, "text": "To set local variables −" }, { "code": null, "e": 5490, "s": 5463, "text": "set_local $a\nset_local $b\n" }, { "code": null, "e": 5519, "s": 5490, "text": "To access global variables −" }, { "code": null, "e": 5548, "s": 5519, "text": "get_global $a\nget_global $b\n" }, { "code": null, "e": 5574, "s": 5548, "text": "To set global variables −" }, { "code": null, "e": 5603, "s": 5574, "text": "set_global $a\nset_global $b\n" }, { "code": null, "e": 5610, "s": 5603, "text": " Print" }, { "code": null, "e": 5621, "s": 5610, "text": " Add Notes" } ]
CTR Full Form - GeeksforGeeks
29 Dec, 2020 CTR stands for click-through rate. It is a metric that measures the number of clicks advertisers receive on their ads per number of impressions. A ratio showing how often people who see your ad end up clicking it. Clickthrough rate (CTR) can be used to gauge how well your keywords and ads are performing. Formula : CTR is the number of clicks that your ad receives divided by the number of times your ad is shown: clicks ÷ impressions = CTR.For example, if you had 5 clicks and 100 impressions, then your CTR would be 5%. In short, CTR = ( Total Measured Ad Impressions / Total Measured Clicks ) × 100 ​Benefits of High CTR : Organic Search Positions Get A Boost Conversion Rates Increase Much Higher Ad Impression Share Free Clicks From Social Ads More people seeing, opening and engaging with owner’s emails Good Click-Through Rate Examples : Facebook Ad click-through rates range from 0.5% to 1.6%. For paid digital ads, Wordstream reported that the average Adwords click-through rate is 1.91% on search and 0.35% on display. Importance of CTR : Without a high CTR, one’s ads aren’t operating at peak performance. Low CTRs can increase the cost of one’s ads. Low CTRs can make it harder for one’s ads to show up. Conclusion of CTR :Your click-through rates are typically a litmus test for how your web campaigns are performing. Low click-through rates indicates that something’s not right. By segmenting your audience, speaking to their needs with effective headlines and ad copy, and using emojis to show your more laid-back side, you could see a significant boost to your click-through rates. Once your ads, emails, and organic listings are targeted and dressed up for a boost in CTRs, your campaigns will improve and your conversions should also rise in kind. Technical Scripter 2020 Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advantages and Disadvantages of OOP Lex Program to count number of words Consensus Algorithms in Blockchain Challenges in Internet of things (IoT) Election algorithm and distributed processing Spatial Filtering and its Types Characteristics of Internet of Things Bubble Sort algorithm using JavaScript Activation Functions Introduction to Parallel Computing
[ { "code": null, "e": 24283, "s": 24255, "text": "\n29 Dec, 2020" }, { "code": null, "e": 24589, "s": 24283, "text": "CTR stands for click-through rate. It is a metric that measures the number of clicks advertisers receive on their ads per number of impressions. A ratio showing how often people who see your ad end up clicking it. Clickthrough rate (CTR) can be used to gauge how well your keywords and ads are performing." }, { "code": null, "e": 24806, "s": 24589, "text": "Formula : CTR is the number of clicks that your ad receives divided by the number of times your ad is shown: clicks ÷ impressions = CTR.For example, if you had 5 clicks and 100 impressions, then your CTR would be 5%." }, { "code": null, "e": 24816, "s": 24806, "text": "In short," }, { "code": null, "e": 24887, "s": 24816, "text": "CTR = ( Total Measured Ad Impressions / Total Measured Clicks ) × 100 " }, { "code": null, "e": 24911, "s": 24887, "text": "​Benefits of High CTR :" }, { "code": null, "e": 24948, "s": 24911, "text": "Organic Search Positions Get A Boost" }, { "code": null, "e": 24974, "s": 24948, "text": "Conversion Rates Increase" }, { "code": null, "e": 25006, "s": 24974, "text": "Much Higher Ad Impression Share" }, { "code": null, "e": 25034, "s": 25006, "text": "Free Clicks From Social Ads" }, { "code": null, "e": 25095, "s": 25034, "text": "More people seeing, opening and engaging with owner’s emails" }, { "code": null, "e": 25130, "s": 25095, "text": "Good Click-Through Rate Examples :" }, { "code": null, "e": 25187, "s": 25130, "text": "Facebook Ad click-through rates range from 0.5% to 1.6%." }, { "code": null, "e": 25314, "s": 25187, "text": "For paid digital ads, Wordstream reported that the average Adwords click-through rate is 1.91% on search and 0.35% on display." }, { "code": null, "e": 25334, "s": 25314, "text": "Importance of CTR :" }, { "code": null, "e": 25402, "s": 25334, "text": "Without a high CTR, one’s ads aren’t operating at peak performance." }, { "code": null, "e": 25447, "s": 25402, "text": "Low CTRs can increase the cost of one’s ads." }, { "code": null, "e": 25501, "s": 25447, "text": "Low CTRs can make it harder for one’s ads to show up." }, { "code": null, "e": 25883, "s": 25501, "text": "Conclusion of CTR :Your click-through rates are typically a litmus test for how your web campaigns are performing. Low click-through rates indicates that something’s not right. By segmenting your audience, speaking to their needs with effective headlines and ad copy, and using emojis to show your more laid-back side, you could see a significant boost to your click-through rates." }, { "code": null, "e": 26051, "s": 25883, "text": "Once your ads, emails, and organic listings are targeted and dressed up for a boost in CTRs, your campaigns will improve and your conversions should also rise in kind." }, { "code": null, "e": 26075, "s": 26051, "text": "Technical Scripter 2020" }, { "code": null, "e": 26080, "s": 26075, "text": "Misc" }, { "code": null, "e": 26085, "s": 26080, "text": "Misc" }, { "code": null, "e": 26090, "s": 26085, "text": "Misc" }, { "code": null, "e": 26188, "s": 26090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26197, "s": 26188, "text": "Comments" }, { "code": null, "e": 26210, "s": 26197, "text": "Old Comments" }, { "code": null, "e": 26246, "s": 26210, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 26283, "s": 26246, "text": "Lex Program to count number of words" }, { "code": null, "e": 26318, "s": 26283, "text": "Consensus Algorithms in Blockchain" }, { "code": null, "e": 26357, "s": 26318, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 26403, "s": 26357, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 26435, "s": 26403, "text": "Spatial Filtering and its Types" }, { "code": null, "e": 26473, "s": 26435, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 26512, "s": 26473, "text": "Bubble Sort algorithm using JavaScript" }, { "code": null, "e": 26533, "s": 26512, "text": "Activation Functions" } ]
Input/Output from external file in C/C++, Java and Python for Competitive Programming
In this article, we will learn about Input/Output from an external files in C/C++, Java, and Python for Competitive Programming. In python, the sys module is used to take input from a file and write output to the file. Let’s look at the implementation in the form of code. import sys # For getting input sys.stdin = open('sample.txt', 'r') # Printing the Output sys.stdout = open('sample.txt', 'w') Here we take the help of buffered reader method to take input associated with file reader to read input from file and print writer to print the data back to the file. // Java program For handling Input/Output import java.io.*; class Input { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("sampleinp.txt")); PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter("sampleout.txt"))); pw.flush(); } } Here we take the help of free open() function and define the mode in which we want to open the file and what kind of operation we want to perform. By default mode is set to read-only #include<stdio.h> int main() { // For getting input freopen("sampleinp.txt", stdin); // Printing the Output freopen("sampleout.txt", "w", stdout); return 0; } In this tutorial, we will learn about Input/Output from an external files in C/C++, Java, and Python for Competitive Programming.
[ { "code": null, "e": 1191, "s": 1062, "text": "In this article, we will learn about Input/Output from an external files in C/C++, Java, and Python for Competitive Programming." }, { "code": null, "e": 1335, "s": 1191, "text": "In python, the sys module is used to take input from a file and write output to the file. Let’s look at the implementation in the form of code." }, { "code": null, "e": 1461, "s": 1335, "text": "import sys\n# For getting input\nsys.stdin = open('sample.txt', 'r')\n# Printing the Output\nsys.stdout = open('sample.txt', 'w')" }, { "code": null, "e": 1628, "s": 1461, "text": "Here we take the help of buffered reader method to take input associated with file reader to read input from file and print writer to print the data back to the file." }, { "code": null, "e": 1978, "s": 1628, "text": "// Java program For handling Input/Output\nimport java.io.*;\nclass Input {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new\n FileReader(\"sampleinp.txt\"));\n PrintWriter pw=new PrintWriter(new\n BufferedWriter(new\n FileWriter(\"sampleout.txt\")));\n pw.flush();\n }\n}" }, { "code": null, "e": 2161, "s": 1978, "text": "Here we take the help of free open() function and define the mode in which we want to open the file and what kind of operation we want to perform. By default mode is set to read-only" }, { "code": null, "e": 2335, "s": 2161, "text": "#include<stdio.h>\nint main() {\n // For getting input\n freopen(\"sampleinp.txt\", stdin);\n // Printing the Output\n freopen(\"sampleout.txt\", \"w\", stdout);\n return 0;\n}" }, { "code": null, "e": 2465, "s": 2335, "text": "In this tutorial, we will learn about Input/Output from an external files in C/C++, Java, and Python for Competitive Programming." } ]
Speech Recognition in Python using Google Speech API
The speech recognition is one of the most useful features in several applications like home automation, AI etc. In this section we will see how the speech recognition can be done using Python and Google’s Speech API. In this case we will give an audio using microphone for speech recognizing. To configure the microphones, there are some parameters. To use this module, we have to install the SpeechRecognition module. There is another module called pyaudio, which is optional. Using this we can set different modes of audio. sudo pip3 install SpeechRecognition sudo apt-get install python3-pyaudio For External Microphones or USB microphones, we need to provide the exact microphone to avoid any difficulties. On Linux, if we type ‘lsusb’ to show the related information for USB devices. The second parameter is the Chunk Size. Using this we can specify how much data we want to read at once. It will be a number which is power of 2, like 1024 or 2048 etc. We also have to specify the sampling rate to determine how often the data are recorded for processing. As there may some unavoidable noise in the surroundings, then we have to adjust the ambient Noise to take the exact voice. Take different microphone related information. Take different microphone related information. Configure the microphone using chunk size, sampling rate, ambient noise adjustments etc. Configure the microphone using chunk size, sampling rate, ambient noise adjustments etc. Wait for some time to get the voice When the voice is recognized, try to convert it into texts, otherwise raise some errors. Wait for some time to get the voice When the voice is recognized, try to convert it into texts, otherwise raise some errors. When the voice is recognized, try to convert it into texts, otherwise raise some errors. Stop the process. Stop the process. import speech_recognition as spreg #Setup the sampling rate and the data size sample_rate = 48000 data_size = 8192 recog = spreg.Recognizer() with spreg.Microphone(sample_rate = sample_rate, chunk_size = data_size) as source: recog.adjust_for_ambient_noise(source) print('Tell Something: ') speech = recog.listen(source) try: text = recog.recognize_google(speech) print('You have said: ' + text) except spreg.UnknownValueError: print('Unable to recognize the audio') except spreg.RequestError as e: print("Request error from Google Speech Recognition service; {}".format(e)) $ python3 318.speech_recognition.py Tell Something: You have said: here we are considering the asymptotic notation Pico to calculate the upper bound of the time complexity so then the definition of the big O notation is like this one $ Without using the microphone, we can also take some audio file as input to convert it to a speech. import speech_recognition as spreg sound_file = 'sample_audio.wav' recog = spreg.Recognizer() with spreg.AudioFile(sound_file) as source: speech = recog.record(source) #use record instead of listning try: text = recog.recognize_google(speech) print('The file contains: ' + text) except spreg.UnknownValueError: print('Unable to recognize the audio') except spreg.RequestError as e: print("Request error from Google Speech Recognition service; {}".format(e)) $ python3 318a.speech_recognition_file.py The file contains: staying ahead of the curve demand planning new technology it also helps you progress in your career $
[ { "code": null, "e": 1279, "s": 1062, "text": "The speech recognition is one of the most useful features in several applications like home automation, AI etc. In this section we will see how the speech recognition can be done using Python and Google’s Speech API." }, { "code": null, "e": 1412, "s": 1279, "text": "In this case we will give an audio using microphone for speech recognizing. To configure the microphones, there are some parameters." }, { "code": null, "e": 1588, "s": 1412, "text": "To use this module, we have to install the SpeechRecognition module. There is another module called pyaudio, which is optional. Using this we can set different modes of audio." }, { "code": null, "e": 1662, "s": 1588, "text": "sudo pip3 install SpeechRecognition\nsudo apt-get install python3-pyaudio\n" }, { "code": null, "e": 1852, "s": 1662, "text": "For External Microphones or USB microphones, we need to provide the exact microphone to avoid any difficulties. On Linux, if we type ‘lsusb’ to show the related information for USB devices." }, { "code": null, "e": 2021, "s": 1852, "text": "The second parameter is the Chunk Size. Using this we can specify how much data we want to read at once. It will be a number which is power of 2, like 1024 or 2048 etc." }, { "code": null, "e": 2124, "s": 2021, "text": "We also have to specify the sampling rate to determine how often the data are recorded for processing." }, { "code": null, "e": 2247, "s": 2124, "text": "As there may some unavoidable noise in the surroundings, then we have to adjust the ambient Noise to take the exact voice." }, { "code": null, "e": 2294, "s": 2247, "text": "Take different microphone related information." }, { "code": null, "e": 2341, "s": 2294, "text": "Take different microphone related information." }, { "code": null, "e": 2430, "s": 2341, "text": "Configure the microphone using chunk size, sampling rate, ambient noise adjustments etc." }, { "code": null, "e": 2519, "s": 2430, "text": "Configure the microphone using chunk size, sampling rate, ambient noise adjustments etc." }, { "code": null, "e": 2647, "s": 2519, "text": "Wait for some time to get the voice\n\nWhen the voice is recognized, try to convert it into texts, otherwise raise some errors.\n\n" }, { "code": null, "e": 2683, "s": 2647, "text": "Wait for some time to get the voice" }, { "code": null, "e": 2772, "s": 2683, "text": "When the voice is recognized, try to convert it into texts, otherwise raise some errors." }, { "code": null, "e": 2861, "s": 2772, "text": "When the voice is recognized, try to convert it into texts, otherwise raise some errors." }, { "code": null, "e": 2879, "s": 2861, "text": "Stop the process." }, { "code": null, "e": 2897, "s": 2879, "text": "Stop the process." }, { "code": null, "e": 3488, "s": 2897, "text": "import speech_recognition as spreg\n#Setup the sampling rate and the data size\nsample_rate = 48000\ndata_size = 8192\nrecog = spreg.Recognizer()\nwith spreg.Microphone(sample_rate = sample_rate, chunk_size = data_size) as source:\nrecog.adjust_for_ambient_noise(source)\nprint('Tell Something: ')\n speech = recog.listen(source)\ntry:\n text = recog.recognize_google(speech)\n print('You have said: ' + text)\nexcept spreg.UnknownValueError:\n print('Unable to recognize the audio')\nexcept spreg.RequestError as e: \n print(\"Request error from Google Speech Recognition service; {}\".format(e))" }, { "code": null, "e": 3727, "s": 3488, "text": "$ python3 318.speech_recognition.py\nTell Something: \nYou have said: here we are considering the asymptotic notation Pico to calculate the upper bound \nof the time complexity so then the definition of the big O notation is like this one\n$\n" }, { "code": null, "e": 3826, "s": 3727, "text": "Without using the microphone, we can also take some audio file as input to convert it to a speech." }, { "code": null, "e": 4321, "s": 3826, "text": "import speech_recognition as spreg\nsound_file = 'sample_audio.wav'\nrecog = spreg.Recognizer()\nwith spreg.AudioFile(sound_file) as source:\n speech = recog.record(source) #use record instead of listning\n try:\n text = recog.recognize_google(speech)\n print('The file contains: ' + text)\n except spreg.UnknownValueError:\n print('Unable to recognize the audio')\n except spreg.RequestError as e: \n print(\"Request error from Google Speech Recognition service; {}\".format(e))" }, { "code": null, "e": 4487, "s": 4321, "text": "$ python3 318a.speech_recognition_file.py \nThe file contains: staying ahead of the curve demand planning new technology it also helps you progress in your career\n$ \n" } ]
How to create a process in Linux?
A program loaded into memory and executing is called a process. In simple, a process is a program in execution. A new process can be created by the fork() system call. The new process consists of a copy of the address space of the original process. fork() creates new process from existing process. Existing process is called the parent process and the process is created newly is called child process. The function is called from parent process. Both the parent and the child processes continue execution at the instruction after the fork(), the return code for the fork() is zero for the new process, whereas the process identifier of the child is returned to the parent. Fork() system call is situated in <sys/types.h> library. System call getpid() returns the Process ID of the current process and getppid() returns the process ID of the current process’s parent process. Let’s take an example how to create child process using fork() system call. #include <unistd.h> #include <sys/types.h> #include <stdio.h> int main( ){ pid_t child_pid; child_pid = fork (); // Create a new child process; if (child_pid < 0) { printf("fork failed"); return 1; } else if (child_pid == 0) { printf ("child process successfully created!\n"); printf ("child_PID = %d,parent_PID = %d\n", getpid(), getppid( ) ); } else { wait(NULL); printf ("parent process successfully created!\n"); printf ("child_PID = %d, parent_PID = %d", getpid( ), getppid( ) ); } return 0; } child process successfully created! child_PID = 31497, parent_PID = 31496 parent process successfully created! child_PID = 31496, parent_PID = 31491 Here, getppid() in the child process returns the same value as getpid() in the parent process. pid_t is a data type which represents the process ID. It is created for process identification. Each process has a unique ID number. Next, we call the system call fork() which will create a new process from calling process. Parent process is the calling function and a new process is a child process. The system call fork() is returns zero or positive value if the process is successfully created.
[ { "code": null, "e": 1174, "s": 1062, "text": "A program loaded into memory and executing is called a process. In simple, a process is a program in execution." }, { "code": null, "e": 1736, "s": 1174, "text": "A new process can be created by the fork() system call. The new process consists of a copy of the address space of the original process. fork() creates new process from existing process. Existing process is called the parent process and the process is created newly is called child process. The function is called from parent process. Both the parent and the child processes continue execution at the instruction after the fork(), the return code for the fork() is zero for the new process, whereas the process identifier of the child is returned to the parent." }, { "code": null, "e": 1793, "s": 1736, "text": "Fork() system call is situated in <sys/types.h> library." }, { "code": null, "e": 1938, "s": 1793, "text": "System call getpid() returns the Process ID of the current process and getppid() returns the process ID of the current process’s parent process." }, { "code": null, "e": 2014, "s": 1938, "text": "Let’s take an example how to create child process using fork() system call." }, { "code": null, "e": 2582, "s": 2014, "text": "#include <unistd.h>\n#include <sys/types.h>\n#include <stdio.h>\nint main( ){\n pid_t child_pid;\n child_pid = fork (); // Create a new child process;\n if (child_pid < 0) {\n printf(\"fork failed\");\n return 1;\n } else if (child_pid == 0) {\n printf (\"child process successfully created!\\n\");\n printf (\"child_PID = %d,parent_PID = %d\\n\",\n getpid(), getppid( ) );\n } else {\n wait(NULL);\n printf (\"parent process successfully created!\\n\");\n printf (\"child_PID = %d, parent_PID = %d\", getpid( ), getppid( ) );\n }\n return 0;\n}" }, { "code": null, "e": 2731, "s": 2582, "text": "child process successfully created!\nchild_PID = 31497, parent_PID = 31496\nparent process successfully created!\nchild_PID = 31496, parent_PID = 31491" }, { "code": null, "e": 2826, "s": 2731, "text": "Here, getppid() in the child process returns the same value as getpid() in the parent process." }, { "code": null, "e": 3224, "s": 2826, "text": "pid_t is a data type which represents the process ID. It is created for process identification. Each process has a unique ID number. Next, we call the system call fork() which will create a new process from calling process. Parent process is the calling function and a new process is a child process. The system call fork() is returns zero or positive value if the process is successfully created." } ]
JSP - Database Access
In this chapter, we will discuss how to access database with JSP. We assume you have good understanding on how JDBC application works. Before starting with database access through a JSP, make sure you have proper JDBC environment setup along with a database. For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial. To start with basic concept, let us create a table and create a few records in that table as follows − To create the Employees table in the EMP database, use the following steps − Open a Command Prompt and change to the installation directory as follows − C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Login to the database as follows − C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Create the Employee table in the TEST database as follows − − mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> Let us now create a few records in the Employee table as follows − − mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> Following example shows how we can execute the SQL SELECT statement using JTSL in JSP programming − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>SELECT Operation</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Employees; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td><c:out value = "${row.id}"/></td> <td><c:out value = "${row.first}"/></td> <td><c:out value = "${row.last}"/></td> <td><c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Khan 30 103 Sumit Mittal 28 Following example shows how we can execute the SQL INSERT statement using JTSL in JSP programming − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>JINSERT Operation</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/> <sql:update dataSource = "${snapshot}" var = "result"> INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali'); </sql:update> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Employees; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td><c:out value = "${row.id}"/></td> <td><c:out value = "${row.first}"/></td> <td><c:out value = "${row.last}"/></td> <td><c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Khan 30 103 Sumit Mittal 28 104 Nuha Ali 2 Following example shows how we can execute the SQL DELETE statement using JTSL in JSP programming − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>DELETE Operation</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/> <c:set var = "empId" value = "103"/> <sql:update dataSource = "${snapshot}" var = "count"> DELETE FROM Employees WHERE Id = ? <sql:param value = "${empId}" /> </sql:update> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Employees; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td><c:out value = "${row.id}"/></td> <td><c:out value = "${row.first}"/></td> <td><c:out value = "${row.last}"/></td> <td><c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Khan 30 Following example shows how we can execute the SQL UPDATE statement using JTSL in JSP programming − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>DELETE Operation</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/> <c:set var = "empId" value = "102"/> <sql:update dataSource = "${snapshot}" var = "count"> UPDATE Employees SET WHERE last = 'Ali' <sql:param value = "${empId}" /> </sql:update> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Employees; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td><c:out value = "${row.id}"/></td> <td><c:out value = "${row.first}"/></td> <td><c:out value = "${row.last}"/></td> <td><c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − Emp ID First Name Last Name Age 100 Zara Ali 18 101 Mahnaz Fatma 25 102 Zaid Ali 30 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": 2498, "s": 2239, "text": "In this chapter, we will discuss how to access database with JSP. We assume you have good understanding on how JDBC application works. Before starting with database access through a JSP, make sure you have proper JDBC environment setup along with a database." }, { "code": null, "e": 2615, "s": 2498, "text": "For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial." }, { "code": null, "e": 2718, "s": 2615, "text": "To start with basic concept, let us create a table and create a few records in that table as follows −" }, { "code": null, "e": 2795, "s": 2718, "text": "To create the Employees table in the EMP database, use the following steps −" }, { "code": null, "e": 2871, "s": 2795, "text": "Open a Command Prompt and change to the installation directory as follows −" }, { "code": null, "e": 2935, "s": 2871, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>" }, { "code": null, "e": 2970, "s": 2935, "text": "Login to the database as follows −" }, { "code": null, "e": 3046, "s": 2970, "text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p\nEnter password: ********\nmysql>" }, { "code": null, "e": 3108, "s": 3046, "text": "Create the Employee table in the TEST database as follows − −" }, { "code": null, "e": 3309, "s": 3108, "text": "mysql> use TEST;\nmysql> create table Employees\n (\n id int not null,\n age int not null,\n first varchar (255),\n last varchar (255)\n );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>" }, { "code": null, "e": 3378, "s": 3309, "text": "Let us now create a few records in the Employee table as follows − −" }, { "code": null, "e": 3794, "s": 3378, "text": "mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n \nmysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql>" }, { "code": null, "e": 3894, "s": 3794, "text": "Following example shows how we can execute the SQL SELECT statement using JTSL in JSP programming −" }, { "code": null, "e": 5071, "s": 3894, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n \n<html>\n <head>\n <title>SELECT Operation</title>\n </head>\n\n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\"\n user = \"root\" password = \"pass123\"/>\n \n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Employees;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Age</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td><c:out value = \"${row.id}\"/></td>\n <td><c:out value = \"${row.first}\"/></td>\n <td><c:out value = \"${row.last}\"/></td>\n <td><c:out value = \"${row.age}\"/></td>\n </tr>\n </c:forEach>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 5134, "s": 5071, "text": "Access the above JSP, the following result will be displayed −" }, { "code": null, "e": 5253, "s": 5134, "text": "\n\nEmp ID\nFirst Name\nLast Name\nAge\n\n\n100\nZara\nAli\n18\n\n\n101\nMahnaz\nFatma\n25\n\n \n102\nZaid\nKhan\n30\n\n\n103\nSumit\nMittal\n28\n\n\n" }, { "code": null, "e": 5353, "s": 5253, "text": "Following example shows how we can execute the SQL INSERT statement using JTSL in JSP programming −" }, { "code": null, "e": 6681, "s": 5353, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n \n<html>\n <head>\n <title>JINSERT Operation</title>\n </head>\n \n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\"\n user = \"root\" password = \"pass123\"/>\n <sql:update dataSource = \"${snapshot}\" var = \"result\">\n INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');\n </sql:update>\n \n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Employees;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Age</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td><c:out value = \"${row.id}\"/></td>\n <td><c:out value = \"${row.first}\"/></td>\n <td><c:out value = \"${row.last}\"/></td>\n <td><c:out value = \"${row.age}\"/></td>\n </tr>\n </c:forEach>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 6744, "s": 6681, "text": "Access the above JSP, the following result will be displayed −" }, { "code": null, "e": 6880, "s": 6744, "text": "\n\nEmp ID\nFirst Name\nLast Name\nAge\n\n\n100\nZara\nAli\n18\n\n\n101\nMahnaz\nFatma\n25\n\n \n102\nZaid\nKhan\n30\n\n\n103\nSumit\nMittal\n28\n\n\n104\nNuha\nAli\n2\n\n\n" }, { "code": null, "e": 6980, "s": 6880, "text": "Following example shows how we can execute the SQL DELETE statement using JTSL in JSP programming −" }, { "code": null, "e": 8375, "s": 6980, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n \n<html>\n <head>\n <title>DELETE Operation</title>\n </head>\n \n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\"\n user = \"root\" password = \"pass123\"/>\n \n <c:set var = \"empId\" value = \"103\"/>\n \n <sql:update dataSource = \"${snapshot}\" var = \"count\">\n DELETE FROM Employees WHERE Id = ?\n <sql:param value = \"${empId}\" />\n </sql:update>\n \n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Employees;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Age</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td><c:out value = \"${row.id}\"/></td>\n <td><c:out value = \"${row.first}\"/></td>\n <td><c:out value = \"${row.last}\"/></td>\n <td><c:out value = \"${row.age}\"/></td>\n </tr>\n </c:forEach>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 8438, "s": 8375, "text": "Access the above JSP, the following result will be displayed −" }, { "code": null, "e": 8534, "s": 8438, "text": "\n\nEmp ID\nFirst Name\nLast Name\nAge\n\n\n100\nZara\nAli\n18\n\n\n101\nMahnaz\nFatma\n25\n\n\n102\nZaid\nKhan\n30\n\n\n" }, { "code": null, "e": 8634, "s": 8534, "text": "Following example shows how we can execute the SQL UPDATE statement using JTSL in JSP programming −" }, { "code": null, "e": 10038, "s": 8634, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n \n<html>\n <head>\n <title>DELETE Operation</title>\n </head>\n \n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\"\n user = \"root\" password = \"pass123\"/>\n \n <c:set var = \"empId\" value = \"102\"/>\n \n <sql:update dataSource = \"${snapshot}\" var = \"count\">\n UPDATE Employees SET WHERE last = 'Ali'\n <sql:param value = \"${empId}\" />\n </sql:update>\n \n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Employees;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Age</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td><c:out value = \"${row.id}\"/></td>\n <td><c:out value = \"${row.first}\"/></td>\n <td><c:out value = \"${row.last}\"/></td>\n <td><c:out value = \"${row.age}\"/></td>\n </tr>\n </c:forEach>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 10101, "s": 10038, "text": "Access the above JSP, the following result will be displayed −" }, { "code": null, "e": 10196, "s": 10101, "text": "\n\nEmp ID\nFirst Name\nLast Name\nAge\n\n\n100\nZara\nAli\n18\n\n\n101\nMahnaz\nFatma\n25\n\n\n102\nZaid\nAli\n30\n\n\n" }, { "code": null, "e": 10231, "s": 10196, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 10246, "s": 10231, "text": " Chaand Sheikh" }, { "code": null, "e": 10281, "s": 10246, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 10296, "s": 10281, "text": " Chaand Sheikh" }, { "code": null, "e": 10331, "s": 10296, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10345, "s": 10331, "text": " Karthikeya T" }, { "code": null, "e": 10380, "s": 10345, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10396, "s": 10380, "text": " TELCOMA Global" }, { "code": null, "e": 10429, "s": 10396, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 10445, "s": 10429, "text": " TELCOMA Global" }, { "code": null, "e": 10479, "s": 10445, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 10487, "s": 10479, "text": " Uplatz" }, { "code": null, "e": 10494, "s": 10487, "text": " Print" }, { "code": null, "e": 10505, "s": 10494, "text": " Add Notes" } ]
Django - Environment
Django development environment consists of installing and setting up Python, Django, and a Database System. Since Django deals with web application, it's worth mentioning that you would need a web server setup as well. Django is written in 100% pure Python code, so you'll need to install Python on your system. Latest Django version requires Python 2.6.5 or higher If you're on one of the latest Linux or Mac OS X distribution, you probably already have Python installed. You can verify it by typing python command at a command prompt. If you see something like this, then Python is installed. $ python Python 2.7.5 (default, Jun 17 2014, 18:11:42) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2 Otherwise, you can download and install the latest version of Python from the link http://www.python.org/download. Installing Django is very easy, but the steps required for its installation depends on your operating system. Since Python is a platform-independent language, Django has one package that works everywhere regardless of your operating system. You can download the latest version of Django from the link http://www.djangoproject.com/download. You have two ways of installing Django if you are running Linux or Mac OS system − You can use the package manager of your OS, or use easy_install or pip if installed. You can use the package manager of your OS, or use easy_install or pip if installed. Install it manually using the official archive you downloaded before. Install it manually using the official archive you downloaded before. We will cover the second option as the first one depends on your OS distribution. If you have decided to follow the first option, just be careful about the version of Django you are installing. Let's say you got your archive from the link above, it should be something like Django-x.xx.tar.gz: Extract and install. $ tar xzvf Django-x.xx.tar.gz $ cd Django-x.xx $ sudo python setup.py install You can test your installation by running this command − $ django-admin.py --version If you see the current version of Django printed on the screen, then everything is set. Note − For some version of Django it will be django-admin the ".py" is removed. We assume you have your Django archive and python installed on your computer. First, PATH verification. On some version of windows (windows 7) you might need to make sure the Path system variable has the path the following C:\Python34\;C:\Python34\Lib\site-packages\django\bin\ in it, of course depending on your Python version. Then, extract and install Django. c:\>cd c:\Django-x.xx Next, install Django by running the following command for which you will need administrative privileges in windows shell "cmd" − c:\Django-x.xx>python setup.py install To test your installation, open a command prompt and type the following command − c:\>python -c "import django; print(django.get_version())" If you see the current version of Django printed on screen, then everything is set. OR Launch a "cmd" prompt and type python then − c:\> python >>> import django >>> django.VERSION Django supports several major database engines and you can set up any of them based on your comfort. MySQL (http://www.mysql.com/) PostgreSQL (http://www.postgresql.org/) SQLite 3 (http://www.sqlite.org/) Oracle (http://www.oracle.com/) MongoDb (https://django-mongodb-engine.readthedocs.org) GoogleAppEngine Datastore (https://cloud.google.com/appengine/articles/django-nonrel) You can refer to respective documentation to installing and configuring a database of your choice. Note − Number 5 and 6 are NoSQL databases. Django comes with a lightweight web server for developing and testing applications. This server is pre-configured to work with Django, and more importantly, it restarts whenever you modify the code. However, Django does support Apache and other popular web servers such as Lighttpd. We will discuss both the approaches in coming chapters while working with different examples. 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2264, "s": 2045, "text": "Django development environment consists of installing and setting up Python, Django, and a Database System. Since Django deals with web application, it's worth mentioning that you would need a web server setup as well." }, { "code": null, "e": 2412, "s": 2264, "text": "Django is written in 100% pure Python code, so you'll need to install Python on your system. Latest Django version requires Python 2.6.5 or higher " }, { "code": null, "e": 2641, "s": 2412, "text": "If you're on one of the latest Linux or Mac OS X distribution, you probably already have Python installed. You can verify it by typing python command at a command prompt. If you see something like this, then Python is installed." }, { "code": null, "e": 2747, "s": 2641, "text": "$ python\nPython 2.7.5 (default, Jun 17 2014, 18:11:42)\n[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2\n" }, { "code": null, "e": 2862, "s": 2747, "text": "Otherwise, you can download and install the latest version of Python from the link http://www.python.org/download." }, { "code": null, "e": 3103, "s": 2862, "text": "Installing Django is very easy, but the steps required for its installation depends on your operating system. Since Python is a platform-independent language, Django has one package that works everywhere regardless of your operating system." }, { "code": null, "e": 3202, "s": 3103, "text": "You can download the latest version of Django from the link http://www.djangoproject.com/download." }, { "code": null, "e": 3285, "s": 3202, "text": "You have two ways of installing Django if you are running Linux or Mac OS system −" }, { "code": null, "e": 3370, "s": 3285, "text": "You can use the package manager of your OS, or use easy_install or pip if installed." }, { "code": null, "e": 3455, "s": 3370, "text": "You can use the package manager of your OS, or use easy_install or pip if installed." }, { "code": null, "e": 3525, "s": 3455, "text": "Install it manually using the official archive you downloaded before." }, { "code": null, "e": 3595, "s": 3525, "text": "Install it manually using the official archive you downloaded before." }, { "code": null, "e": 3789, "s": 3595, "text": "We will cover the second option as the first one depends on your OS distribution. If you have decided to follow the first option, just be careful about the version of Django you are installing." }, { "code": null, "e": 3889, "s": 3789, "text": "Let's say you got your archive from the link above, it should be something like Django-x.xx.tar.gz:" }, { "code": null, "e": 3910, "s": 3889, "text": "Extract and install." }, { "code": null, "e": 3989, "s": 3910, "text": "$ tar xzvf Django-x.xx.tar.gz\n$ cd Django-x.xx\n$ sudo python setup.py install\n" }, { "code": null, "e": 4046, "s": 3989, "text": "You can test your installation by running this command −" }, { "code": null, "e": 4075, "s": 4046, "text": "$ django-admin.py --version\n" }, { "code": null, "e": 4163, "s": 4075, "text": "If you see the current version of Django printed on the screen, then everything is set." }, { "code": null, "e": 4243, "s": 4163, "text": "Note − For some version of Django it will be django-admin the \".py\" is removed." }, { "code": null, "e": 4321, "s": 4243, "text": "We assume you have your Django archive and python installed on your computer." }, { "code": null, "e": 4347, "s": 4321, "text": "First, PATH verification." }, { "code": null, "e": 4573, "s": 4347, "text": "On some version of windows (windows 7) you might need to make sure the Path system variable has the path the following C:\\Python34\\;C:\\Python34\\Lib\\site-packages\\django\\bin\\ in it, of course depending on your Python version." }, { "code": null, "e": 4607, "s": 4573, "text": "Then, extract and install Django." }, { "code": null, "e": 4630, "s": 4607, "text": "c:\\>cd c:\\Django-x.xx\n" }, { "code": null, "e": 4759, "s": 4630, "text": "Next, install Django by running the following command for which you will need administrative privileges in windows shell \"cmd\" −" }, { "code": null, "e": 4799, "s": 4759, "text": "c:\\Django-x.xx>python setup.py install\n" }, { "code": null, "e": 4881, "s": 4799, "text": "To test your installation, open a command prompt and type the following command −" }, { "code": null, "e": 4941, "s": 4881, "text": "c:\\>python -c \"import django; print(django.get_version())\"\n" }, { "code": null, "e": 5025, "s": 4941, "text": "If you see the current version of Django printed on screen, then everything is set." }, { "code": null, "e": 5028, "s": 5025, "text": "OR" }, { "code": null, "e": 5073, "s": 5028, "text": "Launch a \"cmd\" prompt and type python then −" }, { "code": null, "e": 5123, "s": 5073, "text": "c:\\> python\n>>> import django\n>>> django.VERSION\n" }, { "code": null, "e": 5224, "s": 5123, "text": "Django supports several major database engines and you can set up any of them based on your comfort." }, { "code": null, "e": 5254, "s": 5224, "text": "MySQL (http://www.mysql.com/)" }, { "code": null, "e": 5294, "s": 5254, "text": "PostgreSQL (http://www.postgresql.org/)" }, { "code": null, "e": 5328, "s": 5294, "text": "SQLite 3 (http://www.sqlite.org/)" }, { "code": null, "e": 5360, "s": 5328, "text": "Oracle (http://www.oracle.com/)" }, { "code": null, "e": 5416, "s": 5360, "text": "MongoDb (https://django-mongodb-engine.readthedocs.org)" }, { "code": null, "e": 5502, "s": 5416, "text": "GoogleAppEngine Datastore (https://cloud.google.com/appengine/articles/django-nonrel)" }, { "code": null, "e": 5601, "s": 5502, "text": "You can refer to respective documentation to installing and configuring a database of your choice." }, { "code": null, "e": 5644, "s": 5601, "text": "Note − Number 5 and 6 are NoSQL databases." }, { "code": null, "e": 5843, "s": 5644, "text": "Django comes with a lightweight web server for developing and testing applications. This server is pre-configured to work with Django, and more importantly, it restarts whenever you modify the code." }, { "code": null, "e": 6021, "s": 5843, "text": "However, Django does support Apache and other popular web servers such as Lighttpd. We will discuss both the approaches in coming chapters while working with different examples." }, { "code": null, "e": 6056, "s": 6021, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6068, "s": 6056, "text": " John Elder" }, { "code": null, "e": 6103, "s": 6068, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6115, "s": 6103, "text": " John Elder" }, { "code": null, "e": 6148, "s": 6115, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 6160, "s": 6148, "text": " John Elder" }, { "code": null, "e": 6193, "s": 6160, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 6205, "s": 6193, "text": " John Elder" }, { "code": null, "e": 6238, "s": 6205, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 6250, "s": 6238, "text": " John Elder" }, { "code": null, "e": 6284, "s": 6250, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 6298, "s": 6284, "text": " Rathan Kumar" }, { "code": null, "e": 6305, "s": 6298, "text": " Print" }, { "code": null, "e": 6316, "s": 6305, "text": " Add Notes" } ]
jsoup - Loading from File
Following example will showcase fetching an HTML from the disk using a file and then find its data. String url = "http://www.google.com"; Document document = Jsoup.connect(url).get(); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to connect the url and get the HTML String. Jsoup − main class to connect the url and get the HTML String. url − url of the html page to load. url − url of the html page to load. The connect(url) method makes a connection to the url and get() method return the html of the requested url. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class JsoupTester { public static void main(String[] args) throws IOException, URISyntaxException { URL path = ClassLoader.getSystemResource("test.htm"); File input = new File(path.toURI()); Document document = Jsoup.parse(input, "UTF-8"); System.out.println(document.title()); } } test.htm Create following test.htm file in C:\jsoup folder. <html> <head> <title>Sample Title</title> </head> <body> <p>Sample Content</p> </body> </html> Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Sample Title Print Add Notes Bookmark this page
[ { "code": null, "e": 2130, "s": 2030, "text": "Following example will showcase fetching an HTML from the disk using a file and then find its data." }, { "code": null, "e": 2215, "s": 2130, "text": "String url = \"http://www.google.com\";\nDocument document = Jsoup.connect(url).get();\n" }, { "code": null, "e": 2221, "s": 2215, "text": "Where" }, { "code": null, "e": 2273, "s": 2221, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2325, "s": 2273, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2388, "s": 2325, "text": "Jsoup − main class to connect the url and get the HTML String." }, { "code": null, "e": 2451, "s": 2388, "text": "Jsoup − main class to connect the url and get the HTML String." }, { "code": null, "e": 2487, "s": 2451, "text": "url − url of the html page to load." }, { "code": null, "e": 2523, "s": 2487, "text": "url − url of the html page to load." }, { "code": null, "e": 2632, "s": 2523, "text": "The connect(url) method makes a connection to the url and get() method return the html of the requested url." }, { "code": null, "e": 2717, "s": 2632, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 2734, "s": 2717, "text": "JsoupTester.java" }, { "code": null, "e": 3225, "s": 2734, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.net.URL;\n\nimport org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\n\npublic class JsoupTester {\n public static void main(String[] args) throws IOException, URISyntaxException {\n \n URL path = ClassLoader.getSystemResource(\"test.htm\");\n File input = new File(path.toURI());\n Document document = Jsoup.parse(input, \"UTF-8\");\n System.out.println(document.title());\n }\n}" }, { "code": null, "e": 3234, "s": 3225, "text": "test.htm" }, { "code": null, "e": 3285, "s": 3234, "text": "Create following test.htm file in C:\\jsoup folder." }, { "code": null, "e": 3404, "s": 3285, "text": "<html>\n <head>\n <title>Sample Title</title>\n </head>\n <body>\n <p>Sample Content</p>\n </body>\n</html>" }, { "code": null, "e": 3455, "s": 3404, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 3488, "s": 3455, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 3531, "s": 3488, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 3558, "s": 3531, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 3574, "s": 3558, "text": "See the result." }, { "code": null, "e": 3588, "s": 3574, "text": "Sample Title\n" }, { "code": null, "e": 3595, "s": 3588, "text": " Print" }, { "code": null, "e": 3606, "s": 3595, "text": " Add Notes" } ]
TimSort - GeeksforGeeks
26 Jun, 2021 TimSort is a sorting algorithm based on Insertion Sort and Merge Sort. A stable sorting algorithm works in O(n Log n) timeUsed in Java’s Arrays.sort() as well as Python’s sorted() and sort().First sort small pieces using Insertion Sort, then merges the pieces using merge of merge sort. A stable sorting algorithm works in O(n Log n) time Used in Java’s Arrays.sort() as well as Python’s sorted() and sort(). First sort small pieces using Insertion Sort, then merges the pieces using merge of merge sort. We divide the Array into blocks known as Run. We sort those runs using insertion sort one by one and then merge those runs using the combine function used in merge sort. If the size of the Array is less than run, then Array gets sorted just by using Insertion Sort. The size of the run may vary from 32 to 64 depending upon the size of the array. Note that the merge function performs well when size subarrays are powers of 2. The idea is based on the fact that insertion sort performs well for small arrays. Details of below implementation: We consider size of run as 32. We one by one sort pieces of size equal to run After sorting individual pieces, we merge them one by one. We double the size of merged subarrays after every iteration. C++ Java Python3 C# Javascript // C++ program to perform TimSort.#include<bits/stdc++.h>using namespace std;const int RUN = 32; // This function sorts array from left index to// to right index which is of size atmost RUNvoid insertionSort(int arr[], int left, int right){ for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; while (j >= left && arr[j] > temp) { arr[j+1] = arr[j]; j--; } arr[j+1] = temp; }} // Merge function merges the sorted runsvoid merge(int arr[], int l, int m, int r){ // Original array is broken in two parts // left and right array int len1 = m - l + 1, len2 = r - m; int left[len1], right[len2]; for (int i = 0; i < len1; i++) left[i] = arr[l + i]; for (int i = 0; i < len2; i++) right[i] = arr[m + 1 + i]; int i = 0; int j = 0; int k = l; // After comparing, we // merge those two array // in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; }} // Iterative Timsort function to sort the// array[0...n-1] (similar to merge sort)void timSort(int arr[], int n){ // Sort individual subarrays of size RUN for (int i = 0; i < n; i+=RUN) insertionSort(arr, i, min((i+RUN-1), (n-1))); // Start merging from size RUN (or 32). // It will merge // to form size 64, then 128, 256 // and so on .... for (int size = RUN; size < n; size = 2*size) { // pick starting point of // left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we // increase left by 2*size for (int left = 0; left < n; left += 2*size) { // find ending point of // left sub array // mid+1 is starting point // of right sub array int mid = left + size - 1; int right = min((left + 2*size - 1), (n-1)); // merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } }} // Utility function to print the Arrayvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionint main(){ int arr[] = {-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12}; int n = sizeof(arr)/sizeof(arr[0]); printf("Given Array is\n"); printArray(arr, n); // Function Call timSort(arr, n); printf("After Sorting Array is\n"); printArray(arr, n); return 0;} // Java program to perform TimSort.class GFG{ static int MIN_MERGE = 32; public static int minRunLength(int n) { assert n >= 0; // Becomes 1 if any 1 bits are shifted off int r = 0; while (n >= MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; } // This function sorts array from left index to // to right index which is of size atmost RUN public static void insertionSort(int[] arr, int left, int right) { for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; while (j >= left && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } // Merge function merges the sorted runs public static void merge(int[] arr, int l, int m, int r) { // Original array is broken in two parts // left and right array int len1 = m - l + 1, len2 = r - m; int[] left = new int[len1]; int[] right = new int[len2]; for (int x = 0; x < len1; x++) { left[x] = arr[l + x]; } for (int x = 0; x < len2; x++) { right[x] = arr[m + 1 + x]; } int i = 0; int j = 0; int k = l; // After comparing, we merge those two array // in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements // of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element // of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; } } // Iterative Timsort function to sort the // array[0...n-1] (similar to merge sort) public static void timSort(int[] arr, int n) { int minRun = minRunLength(MIN_MERGE); // Sort individual subarrays of size RUN for (int i = 0; i < n; i += minRun) { insertionSort(arr, i, Math.min((i + MIN_MERGE - 1), (n - 1))); } // Start merging from size // RUN (or 32). It will // merge to form size 64, // then 128, 256 and so on // .... for (int size = minRun; size < n; size = 2 * size) { // Pick starting point // of left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we // increase left by 2*size for (int left = 0; left < n; left += 2 * size) { // Find ending point of left sub array // mid+1 is starting point of right sub // array int mid = left + size - 1; int right = Math.min((left + 2 * size - 1), (n - 1)); // Merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } } } // Utility function to print the Array public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.print("\n"); } // Driver code public static void main(String[] args) { int[] arr = { -2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12 }; int n = arr.length; System.out.println("Given Array is"); printArray(arr, n); timSort(arr, n); System.out.println("After Sorting Array is"); printArray(arr, n); }} // This code has been contributed by 29AjayKumar # Python3 program to perform basic timSortMIN_MERGE = 32 def calcMinRun(n): """Returns the minimum length of a run from 23 - 64 so that the len(array)/minrun is less than or equal to a power of 2. e.g. 1=>1, ..., 63=>63, 64=>32, 65=>33, ..., 127=>64, 128=>32, ... """ r = 0 while n >= MIN_MERGE: r |= n & 1 n >>= 1 return n + r # This function sorts array from left index to# to right index which is of size atmost RUNdef insertionSort(arr, left, right): for i in range(left + 1, right + 1): j = i while j > left and arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] j -= 1 # Merge function merges the sorted runsdef merge(arr, l, m, r): # original array is broken in two parts # left and right array len1, len2 = m - l + 1, r - m left, right = [], [] for i in range(0, len1): left.append(arr[l + i]) for i in range(0, len2): right.append(arr[m + 1 + i]) i, j, k = 0, 0, l # after comparing, we merge those two array # in larger sub array while i < len1 and j < len2: if left[i] <= right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 # Copy remaining elements of left, if any while i < len1: arr[k] = left[i] k += 1 i += 1 # Copy remaining element of right, if any while j < len2: arr[k] = right[j] k += 1 j += 1 # Iterative Timsort function to sort the# array[0...n-1] (similar to merge sort)def timSort(arr): n = len(arr) minRun = calcMinRun(n) # Sort individual subarrays of size RUN for start in range(0, n, minRun): end = min(start + minRun - 1, n - 1) insertionSort(arr, start, end) # Start merging from size RUN (or 32). It will merge # to form size 64, then 128, 256 and so on .... size = minRun while size < n: # Pick starting point of left sub array. We # are going to merge arr[left..left+size-1] # and arr[left+size, left+2*size-1] # After every merge, we increase left by 2*size for left in range(0, n, 2 * size): # Find ending point of left sub array # mid+1 is starting point of right sub array mid = min(n - 1, left + size - 1) right = min((left + 2 * size - 1), (n - 1)) # Merge sub array arr[left.....mid] & # arr[mid+1....right] if mid < right: merge(arr, left, mid, right) size = 2 * size # Driver program to test above functionif __name__ == "__main__": arr = [-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12] print("Given Array is") print(arr) # Function Call timSort(arr) print("After Sorting Array is") print(arr) # [-14, -14, -13, -7, -4, -2, 0, 0, 5, 7, 7, 8, 12, 15, 15] // C# program to perform TimSort.using System; class GFG{ public const int RUN = 32; // This function sorts array from left index to // to right index which is of size atmost RUN public static void insertionSort(int[] arr, int left, int right) { for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; while (j >= left && arr[j] > temp) { arr[j+1] = arr[j]; j--; } arr[j+1] = temp; } } // merge function merges the sorted runs public static void merge(int[] arr, int l, int m, int r) { // original array is broken in two parts // left and right array int len1 = m - l + 1, len2 = r - m; int[] left = new int[len1]; int[] right = new int[len2]; for (int x = 0; x < len1; x++) left[x] = arr[l + x]; for (int x = 0; x < len2; x++) right[x] = arr[m + 1 + x]; int i = 0; int j = 0; int k = l; // After comparing, we merge those two array // in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements // of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element // of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; } } // Iterative Timsort function to sort the // array[0...n-1] (similar to merge sort) public static void timSort(int[] arr, int n) { // Sort individual subarrays of size RUN for (int i = 0; i < n; i+=RUN) insertionSort(arr, i, Math.Min((i+RUN-1), (n-1))); // Start merging from size RUN (or 32). // It will merge // to form size 64, then // 128, 256 and so on .... for (int size = RUN; size < n; size = 2*size) { // Pick starting point of // left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we increase // left by 2*size for (int left = 0; left < n; left += 2*size) { // Find ending point of left sub array // mid+1 is starting point of // right sub array int mid = left + size - 1; int right = Math.Min((left + 2*size - 1), (n-1)); // Merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } } } // Utility function to print the Array public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.Write("\n"); } // Driver program to test above function public static void Main() { int[] arr = {-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12}; int n = arr.Length; Console.Write("Given Array is\n"); printArray(arr, n); // Function Call timSort(arr, n); Console.Write("After Sorting Array is\n"); printArray(arr, n); } } //This code is contributed by DrRoot_ <script> // Javascript program to perform TimSort.let MIN_MERGE = 32; function minRunLength(n){ // Becomes 1 if any 1 bits are shifted off let r = 0; while (n >= MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r;} // This function sorts array from left index to// to right index which is of size atmost RUNfunction insertionSort(arr,left,right){ for(let i = left + 1; i <= right; i++) { let temp = arr[i]; let j = i - 1; while (j >= left && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; }} // Merge function merges the sorted runsfunction merge(arr, l, m, r){ // Original array is broken in two parts // left and right array let len1 = m - l + 1, len2 = r - m; let left = new Array(len1); let right = new Array(len2); for(let x = 0; x < len1; x++) { left[x] = arr[l + x]; } for(let x = 0; x < len2; x++) { right[x] = arr[m + 1 + x]; } let i = 0; let j = 0; let k = l; // After comparing, we merge those two // array in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements // of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element // of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; }} // Iterative Timsort function to sort the// array[0...n-1] (similar to merge sort)function timSort(arr, n){ let minRun = minRunLength(MIN_MERGE); // Sort individual subarrays of size RUN for(let i = 0; i < n; i += minRun) { insertionSort(arr, i, Math.min( (i + MIN_MERGE - 1), (n - 1))); } // Start merging from size // RUN (or 32). It will // merge to form size 64, // then 128, 256 and so on // .... for(let size = minRun; size < n; size = 2 * size) { // Pick starting point // of left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we // increase left by 2*size for(let left = 0; left < n; left += 2 * size) { // Find ending point of left sub array // mid+1 is starting point of right sub // array let mid = left + size - 1; let right = Math.min((left + 2 * size - 1), (n - 1)); // Merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } }} // Utility function to print the Arrayfunction printArray(arr,n){ for(let i = 0; i < n; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr = [ -2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12 ];let n = arr.length;document.write("Given Array is<br>");printArray(arr, n);timSort(arr, n); document.write("After Sorting Array is<br>");printArray(arr, n); // This code is contributed by rag2127 </script> Output: Given Array is -2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12 After Sorting Array is -14 -14 -13 -7 -4 -2 0 0 5 7 7 8 12 15 15 References : https://svn.python.org/projects/python/trunk/Objects/listsort.txt https://en.wikipedia.org/wiki/Timsort#Minimum_size_.28minrun.29 This article is contributed by Aditya Kumar. 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. rituraj_jain DrRoot_ 29AjayKumar KarampistisDimitris tjrdnjs33936 nespamujtetu rag2127 Insertion Sort Merge Sort Sorting Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort Quick Sort vs Merge Sort Stability in sorting algorithms Sort a nearly sorted (or K sorted) array Quickselect Algorithm Recursive Bubble Sort Sorting in Java Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted Binary Insertion Sort Check if two arrays are equal or not
[ { "code": null, "e": 23687, "s": 23659, "text": "\n26 Jun, 2021" }, { "code": null, "e": 23758, "s": 23687, "text": "TimSort is a sorting algorithm based on Insertion Sort and Merge Sort." }, { "code": null, "e": 23974, "s": 23758, "text": "A stable sorting algorithm works in O(n Log n) timeUsed in Java’s Arrays.sort() as well as Python’s sorted() and sort().First sort small pieces using Insertion Sort, then merges the pieces using merge of merge sort." }, { "code": null, "e": 24026, "s": 23974, "text": "A stable sorting algorithm works in O(n Log n) time" }, { "code": null, "e": 24096, "s": 24026, "text": "Used in Java’s Arrays.sort() as well as Python’s sorted() and sort()." }, { "code": null, "e": 24192, "s": 24096, "text": "First sort small pieces using Insertion Sort, then merges the pieces using merge of merge sort." }, { "code": null, "e": 24701, "s": 24192, "text": "We divide the Array into blocks known as Run. We sort those runs using insertion sort one by one and then merge those runs using the combine function used in merge sort. If the size of the Array is less than run, then Array gets sorted just by using Insertion Sort. The size of the run may vary from 32 to 64 depending upon the size of the array. Note that the merge function performs well when size subarrays are powers of 2. The idea is based on the fact that insertion sort performs well for small arrays." }, { "code": null, "e": 24734, "s": 24701, "text": "Details of below implementation:" }, { "code": null, "e": 24765, "s": 24734, "text": "We consider size of run as 32." }, { "code": null, "e": 24812, "s": 24765, "text": "We one by one sort pieces of size equal to run" }, { "code": null, "e": 24933, "s": 24812, "text": "After sorting individual pieces, we merge them one by one. We double the size of merged subarrays after every iteration." }, { "code": null, "e": 24937, "s": 24933, "text": "C++" }, { "code": null, "e": 24942, "s": 24937, "text": "Java" }, { "code": null, "e": 24950, "s": 24942, "text": "Python3" }, { "code": null, "e": 24953, "s": 24950, "text": "C#" }, { "code": null, "e": 24964, "s": 24953, "text": "Javascript" }, { "code": "// C++ program to perform TimSort.#include<bits/stdc++.h>using namespace std;const int RUN = 32; // This function sorts array from left index to// to right index which is of size atmost RUNvoid insertionSort(int arr[], int left, int right){ for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; while (j >= left && arr[j] > temp) { arr[j+1] = arr[j]; j--; } arr[j+1] = temp; }} // Merge function merges the sorted runsvoid merge(int arr[], int l, int m, int r){ // Original array is broken in two parts // left and right array int len1 = m - l + 1, len2 = r - m; int left[len1], right[len2]; for (int i = 0; i < len1; i++) left[i] = arr[l + i]; for (int i = 0; i < len2; i++) right[i] = arr[m + 1 + i]; int i = 0; int j = 0; int k = l; // After comparing, we // merge those two array // in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; }} // Iterative Timsort function to sort the// array[0...n-1] (similar to merge sort)void timSort(int arr[], int n){ // Sort individual subarrays of size RUN for (int i = 0; i < n; i+=RUN) insertionSort(arr, i, min((i+RUN-1), (n-1))); // Start merging from size RUN (or 32). // It will merge // to form size 64, then 128, 256 // and so on .... for (int size = RUN; size < n; size = 2*size) { // pick starting point of // left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we // increase left by 2*size for (int left = 0; left < n; left += 2*size) { // find ending point of // left sub array // mid+1 is starting point // of right sub array int mid = left + size - 1; int right = min((left + 2*size - 1), (n-1)); // merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } }} // Utility function to print the Arrayvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionint main(){ int arr[] = {-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Given Array is\\n\"); printArray(arr, n); // Function Call timSort(arr, n); printf(\"After Sorting Array is\\n\"); printArray(arr, n); return 0;}", "e": 28194, "s": 24964, "text": null }, { "code": "// Java program to perform TimSort.class GFG{ static int MIN_MERGE = 32; public static int minRunLength(int n) { assert n >= 0; // Becomes 1 if any 1 bits are shifted off int r = 0; while (n >= MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; } // This function sorts array from left index to // to right index which is of size atmost RUN public static void insertionSort(int[] arr, int left, int right) { for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; while (j >= left && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } // Merge function merges the sorted runs public static void merge(int[] arr, int l, int m, int r) { // Original array is broken in two parts // left and right array int len1 = m - l + 1, len2 = r - m; int[] left = new int[len1]; int[] right = new int[len2]; for (int x = 0; x < len1; x++) { left[x] = arr[l + x]; } for (int x = 0; x < len2; x++) { right[x] = arr[m + 1 + x]; } int i = 0; int j = 0; int k = l; // After comparing, we merge those two array // in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements // of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element // of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; } } // Iterative Timsort function to sort the // array[0...n-1] (similar to merge sort) public static void timSort(int[] arr, int n) { int minRun = minRunLength(MIN_MERGE); // Sort individual subarrays of size RUN for (int i = 0; i < n; i += minRun) { insertionSort(arr, i, Math.min((i + MIN_MERGE - 1), (n - 1))); } // Start merging from size // RUN (or 32). It will // merge to form size 64, // then 128, 256 and so on // .... for (int size = minRun; size < n; size = 2 * size) { // Pick starting point // of left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we // increase left by 2*size for (int left = 0; left < n; left += 2 * size) { // Find ending point of left sub array // mid+1 is starting point of right sub // array int mid = left + size - 1; int right = Math.min((left + 2 * size - 1), (n - 1)); // Merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } } } // Utility function to print the Array public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } System.out.print(\"\\n\"); } // Driver code public static void main(String[] args) { int[] arr = { -2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12 }; int n = arr.length; System.out.println(\"Given Array is\"); printArray(arr, n); timSort(arr, n); System.out.println(\"After Sorting Array is\"); printArray(arr, n); }} // This code has been contributed by 29AjayKumar", "e": 32412, "s": 28194, "text": null }, { "code": "# Python3 program to perform basic timSortMIN_MERGE = 32 def calcMinRun(n): \"\"\"Returns the minimum length of a run from 23 - 64 so that the len(array)/minrun is less than or equal to a power of 2. e.g. 1=>1, ..., 63=>63, 64=>32, 65=>33, ..., 127=>64, 128=>32, ... \"\"\" r = 0 while n >= MIN_MERGE: r |= n & 1 n >>= 1 return n + r # This function sorts array from left index to# to right index which is of size atmost RUNdef insertionSort(arr, left, right): for i in range(left + 1, right + 1): j = i while j > left and arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] j -= 1 # Merge function merges the sorted runsdef merge(arr, l, m, r): # original array is broken in two parts # left and right array len1, len2 = m - l + 1, r - m left, right = [], [] for i in range(0, len1): left.append(arr[l + i]) for i in range(0, len2): right.append(arr[m + 1 + i]) i, j, k = 0, 0, l # after comparing, we merge those two array # in larger sub array while i < len1 and j < len2: if left[i] <= right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 # Copy remaining elements of left, if any while i < len1: arr[k] = left[i] k += 1 i += 1 # Copy remaining element of right, if any while j < len2: arr[k] = right[j] k += 1 j += 1 # Iterative Timsort function to sort the# array[0...n-1] (similar to merge sort)def timSort(arr): n = len(arr) minRun = calcMinRun(n) # Sort individual subarrays of size RUN for start in range(0, n, minRun): end = min(start + minRun - 1, n - 1) insertionSort(arr, start, end) # Start merging from size RUN (or 32). It will merge # to form size 64, then 128, 256 and so on .... size = minRun while size < n: # Pick starting point of left sub array. We # are going to merge arr[left..left+size-1] # and arr[left+size, left+2*size-1] # After every merge, we increase left by 2*size for left in range(0, n, 2 * size): # Find ending point of left sub array # mid+1 is starting point of right sub array mid = min(n - 1, left + size - 1) right = min((left + 2 * size - 1), (n - 1)) # Merge sub array arr[left.....mid] & # arr[mid+1....right] if mid < right: merge(arr, left, mid, right) size = 2 * size # Driver program to test above functionif __name__ == \"__main__\": arr = [-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12] print(\"Given Array is\") print(arr) # Function Call timSort(arr) print(\"After Sorting Array is\") print(arr) # [-14, -14, -13, -7, -4, -2, 0, 0, 5, 7, 7, 8, 12, 15, 15]", "e": 35353, "s": 32412, "text": null }, { "code": "// C# program to perform TimSort.using System; class GFG{ public const int RUN = 32; // This function sorts array from left index to // to right index which is of size atmost RUN public static void insertionSort(int[] arr, int left, int right) { for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; while (j >= left && arr[j] > temp) { arr[j+1] = arr[j]; j--; } arr[j+1] = temp; } } // merge function merges the sorted runs public static void merge(int[] arr, int l, int m, int r) { // original array is broken in two parts // left and right array int len1 = m - l + 1, len2 = r - m; int[] left = new int[len1]; int[] right = new int[len2]; for (int x = 0; x < len1; x++) left[x] = arr[l + x]; for (int x = 0; x < len2; x++) right[x] = arr[m + 1 + x]; int i = 0; int j = 0; int k = l; // After comparing, we merge those two array // in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements // of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element // of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; } } // Iterative Timsort function to sort the // array[0...n-1] (similar to merge sort) public static void timSort(int[] arr, int n) { // Sort individual subarrays of size RUN for (int i = 0; i < n; i+=RUN) insertionSort(arr, i, Math.Min((i+RUN-1), (n-1))); // Start merging from size RUN (or 32). // It will merge // to form size 64, then // 128, 256 and so on .... for (int size = RUN; size < n; size = 2*size) { // Pick starting point of // left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we increase // left by 2*size for (int left = 0; left < n; left += 2*size) { // Find ending point of left sub array // mid+1 is starting point of // right sub array int mid = left + size - 1; int right = Math.Min((left + 2*size - 1), (n-1)); // Merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } } } // Utility function to print the Array public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.Write(\"\\n\"); } // Driver program to test above function public static void Main() { int[] arr = {-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12}; int n = arr.Length; Console.Write(\"Given Array is\\n\"); printArray(arr, n); // Function Call timSort(arr, n); Console.Write(\"After Sorting Array is\\n\"); printArray(arr, n); } } //This code is contributed by DrRoot_", "e": 39320, "s": 35353, "text": null }, { "code": "<script> // Javascript program to perform TimSort.let MIN_MERGE = 32; function minRunLength(n){ // Becomes 1 if any 1 bits are shifted off let r = 0; while (n >= MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r;} // This function sorts array from left index to// to right index which is of size atmost RUNfunction insertionSort(arr,left,right){ for(let i = left + 1; i <= right; i++) { let temp = arr[i]; let j = i - 1; while (j >= left && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; }} // Merge function merges the sorted runsfunction merge(arr, l, m, r){ // Original array is broken in two parts // left and right array let len1 = m - l + 1, len2 = r - m; let left = new Array(len1); let right = new Array(len2); for(let x = 0; x < len1; x++) { left[x] = arr[l + x]; } for(let x = 0; x < len2; x++) { right[x] = arr[m + 1 + x]; } let i = 0; let j = 0; let k = l; // After comparing, we merge those two // array in larger sub array while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } // Copy remaining elements // of left, if any while (i < len1) { arr[k] = left[i]; k++; i++; } // Copy remaining element // of right, if any while (j < len2) { arr[k] = right[j]; k++; j++; }} // Iterative Timsort function to sort the// array[0...n-1] (similar to merge sort)function timSort(arr, n){ let minRun = minRunLength(MIN_MERGE); // Sort individual subarrays of size RUN for(let i = 0; i < n; i += minRun) { insertionSort(arr, i, Math.min( (i + MIN_MERGE - 1), (n - 1))); } // Start merging from size // RUN (or 32). It will // merge to form size 64, // then 128, 256 and so on // .... for(let size = minRun; size < n; size = 2 * size) { // Pick starting point // of left sub array. We // are going to merge // arr[left..left+size-1] // and arr[left+size, left+2*size-1] // After every merge, we // increase left by 2*size for(let left = 0; left < n; left += 2 * size) { // Find ending point of left sub array // mid+1 is starting point of right sub // array let mid = left + size - 1; let right = Math.min((left + 2 * size - 1), (n - 1)); // Merge sub array arr[left.....mid] & // arr[mid+1....right] if(mid < right) merge(arr, left, mid, right); } }} // Utility function to print the Arrayfunction printArray(arr,n){ for(let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr = [ -2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12 ];let n = arr.length;document.write(\"Given Array is<br>\");printArray(arr, n);timSort(arr, n); document.write(\"After Sorting Array is<br>\");printArray(arr, n); // This code is contributed by rag2127 </script>", "e": 42706, "s": 39320, "text": null }, { "code": null, "e": 42714, "s": 42706, "text": "Output:" }, { "code": null, "e": 42864, "s": 42714, "text": "Given Array is\n-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12\nAfter Sorting Array is\n-14 -14 -13 -7 -4 -2 0 0 5 7 7 8 12 15 15" }, { "code": null, "e": 43427, "s": 42864, "text": "References : https://svn.python.org/projects/python/trunk/Objects/listsort.txt https://en.wikipedia.org/wiki/Timsort#Minimum_size_.28minrun.29 This article is contributed by Aditya Kumar. 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": 43440, "s": 43427, "text": "rituraj_jain" }, { "code": null, "e": 43448, "s": 43440, "text": "DrRoot_" }, { "code": null, "e": 43460, "s": 43448, "text": "29AjayKumar" }, { "code": null, "e": 43480, "s": 43460, "text": "KarampistisDimitris" }, { "code": null, "e": 43493, "s": 43480, "text": "tjrdnjs33936" }, { "code": null, "e": 43506, "s": 43493, "text": "nespamujtetu" }, { "code": null, "e": 43514, "s": 43506, "text": "rag2127" }, { "code": null, "e": 43529, "s": 43514, "text": "Insertion Sort" }, { "code": null, "e": 43540, "s": 43529, "text": "Merge Sort" }, { "code": null, "e": 43548, "s": 43540, "text": "Sorting" }, { "code": null, "e": 43556, "s": 43548, "text": "Sorting" }, { "code": null, "e": 43567, "s": 43556, "text": "Merge Sort" }, { "code": null, "e": 43665, "s": 43567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43674, "s": 43665, "text": "Comments" }, { "code": null, "e": 43687, "s": 43674, "text": "Old Comments" }, { "code": null, "e": 43713, "s": 43687, "text": "C++ Program for QuickSort" }, { "code": null, "e": 43738, "s": 43713, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 43770, "s": 43738, "text": "Stability in sorting algorithms" }, { "code": null, "e": 43811, "s": 43770, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 43833, "s": 43811, "text": "Quickselect Algorithm" }, { "code": null, "e": 43855, "s": 43833, "text": "Recursive Bubble Sort" }, { "code": null, "e": 43871, "s": 43855, "text": "Sorting in Java" }, { "code": null, "e": 43960, "s": 43871, "text": "Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted" }, { "code": null, "e": 43982, "s": 43960, "text": "Binary Insertion Sort" } ]
Largest integer that can be placed at center of given square Matrix to maximise arithmetic progressions - GeeksforGeeks
25 Jan, 2022 Given a N x N matrix, such that the element at the index [N/2, N/2] is missing, the task is to find the maximum integer that can be placed at index [N/2, N/2] such that the count of arithmetic progressions over all rows, columns, and diagonals is maximized. Example: Input: mat[][]={{3, 4, 11}, {10, ?, 9}, {-1, 6, 7}}Output: 5Explanation: The maximum integer that can be palced on [1, 1] is 5. Hence, the AP’s formed is are: Top left diagonal: 3, 5, 7.Top right diagonal: −1, 5, 1.Middle column: 4, 5, 6.Right column: 11, 9, 7. Top left diagonal: 3, 5, 7. Top right diagonal: −1, 5, 1. Middle column: 4, 5, 6. Right column: 11, 9, 7. Therefore, the number of AP formed is 4 which is the maximum possible. Input: mat[][]={{2, 2, 11}, {1, ?, 7}, {-1, 6, 6}}Output: 4 Approach: The given problem can be solved by finding all the possible numbers that can be placed on the index [N/2, N/2] such that it forms an Arithmetic progression over any row, column, or diagonal of the given matrix and keeping track of the largest integer out of them which forms the maximum AP’s. Let’s suppose the matrix is of 3*3 size. Now, the missing element is (1, 1). So, for each row, column and diagonal, three numbers are present. Say, these three numbers are A, B, C and B is missing. So, it can be observed that for integers A, B, and C to form and an AP, B must be equal to [A + (C – A)]/2. Hence, for any value of A and C, B can be calculated using the above-discussed formula. Also, if (C – A) is odd then no integer value exists for B. So, apply this formula to over row, column and diagonal and find the maximum element which will form the maximum element. The same approach can be applied to N*N matrix. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum value// of the missing integer such that the// count of AP's formed is maximizedint findMissing(vector<vector<int> >& mat){ int N = mat.size(); // Stores the occurence of each // possible integer value unordered_map<int, int> mp; // For 1st Row int t = abs(mat[N / 2][N / 2 + 1] - mat[N / 2][N / 2 - 1]); int A = min(mat[N / 2][N / 2 + 1], mat[N / 2][N / 2 - 1]); if (t % 2 == 0) { mp[A + t / 2] += 1; } // For 1st Col t = abs(mat[N / 2 + 1][N / 2] - mat[N / 2][N / 2]); A = min(mat[N / 2 + 1][N / 2], mat[N / 2][N / 2]); if (t % 2 == 0) { mp[A + t / 2] += 1; } // For Left Diagonal t = abs(mat[N / 2 + 1][N / 2 + 1] - mat[N / 2 - 1][N / 2 - 1]); A = min(mat[N / 2 + 1][N / 2 + 1], mat[N / 2 - 1][N / 2 - 1]); if (t % 2 == 0) { mp[A + t / 2] += 1; } // For Right Diagonal t = abs(mat[N / 2 - 1][N / 2 + 1] - mat[N / 2 + 1][N / 2 - 1]); A = min(mat[N / 2 - 1][N / 2 + 1], mat[N / 2 + 1][N / 2 - 1]); if (t % 2 == 0) { mp[A + t / 2] += 1; } int ans = -1, occur = 0; // Loop to find the largest integer // with maximum count for (auto x : mp) { if (occur < x.second) { ans = x.first; } if (occur == x.second) { ans = max(ans, x.first); } } // Return Answer return ans;} // Driver Codeint main(){ vector<vector<int> > mat = { { 3, 4, 11 }, { 10, INT_MAX, 9 }, { -1, 6, 7 } }; cout << findMissing(mat);} // Java code for the above approachimport java.util.*;class GFG{ // Function to find the maximum value // of the missing integer such that the // count of AP's formed is maximized static int findMissing(int[][] mat) { int N = mat.length; // Stores the occurence of each // possible integer value HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // For 1st Row int t = Math.abs(mat[N / 2][N / 2 + 1] - mat[N / 2][N / 2 - 1]); int A = Math.min(mat[N / 2][N / 2 + 1], mat[N / 2][N / 2 - 1]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } // For 1st Col t = Math.abs(mat[N / 2 + 1][N / 2] - mat[N / 2][N / 2]); A = Math.min(mat[N / 2 + 1][N / 2], mat[N / 2][N / 2]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } // For Left Diagonal t = Math.abs(mat[N / 2 + 1][N / 2 + 1] - mat[N / 2 - 1][N / 2 - 1]); A = Math.min(mat[N / 2 + 1][N / 2 + 1], mat[N / 2 - 1][N / 2 - 1]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } // For Right Diagonal t = Math.abs(mat[N / 2 - 1][N / 2 + 1] - mat[N / 2 + 1][N / 2 - 1]); A = Math.min(mat[N / 2 - 1][N / 2 + 1], mat[N / 2 + 1][N / 2 - 1]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } int ans = -1, occur = 0; // Loop to find the largest integer // with maximum count for (Map.Entry<Integer, Integer> x : mp.entrySet()) { if (occur < x.getValue()) { ans = x.getKey(); } if (occur == x.getValue()) { ans = Math.max(ans, x.getKey()); } } // Return Answer return ans; } // Driver Code public static void main(String[] args) { int[][] mat = { { 3, 4, 11 }, { 10, Integer.MAX_VALUE, 9 }, { -1, 6, 7 } }; System.out.print(findMissing(mat)); }} // This code is contributed by shikhasingrajput # Python 3 code for the above approachfrom collections import defaultdictimport sys # Function to find the maximum value# of the missing integer such that the# count of AP's formed is maximizeddef findMissing(mat): N = len(mat) # Stores the occurence of each # possible integer value mp = defaultdict(int) # For 1st Row t = abs(mat[N // 2][N // 2 + 1] - mat[N // 2][N // 2 - 1]) A = min(mat[N // 2][N // 2 + 1], mat[N // 2][N // 2 - 1]) if (t % 2 == 0): mp[A + t // 2] += 1 # For 1st Col t = abs(mat[N // 2 + 1][N // 2] - mat[N // 2][N // 2]) A = min(mat[N // 2 + 1][N // 2], mat[N // 2][N // 2]) if (t % 2 == 0): mp[A + t // 2] += 1 # For Left Diagonal t = abs(mat[N // 2 + 1][N // 2 + 1] - mat[N // 2 - 1][N // 2 - 1]) A = min(mat[N // 2 + 1][N // 2 + 1], mat[N // 2 - 1][N // 2 - 1]) if (t % 2 == 0): mp[A + t // 2] += 1 # For Right Diagonal t = abs(mat[N // 2 - 1][N // 2 + 1] - mat[N // 2 + 1][N // 2 - 1]) A = min(mat[N // 2 - 1][N // 2 + 1], mat[N // 2 + 1][N // 2 - 1]) if (t % 2 == 0): mp[A + t // 2] += 1 ans = -1 occur = 0 # Loop to find the largest integer # with maximum count for x in mp: if (occur < mp[x]): ans = x if (occur == mp[x]): ans = max(ans, x) # Return Answer return ans # Driver Codeif __name__ == "__main__": mat = [[3, 4, 11], [10, sys.maxsize, 9], [-1, 6, 7]] print(findMissing(mat)) # This code is contributed by ukasp. // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static int INT_MAX = 2147483647; // Function to find the maximum value// of the missing integer such that the// count of AP's formed is maximizedstatic int findMissing(int [,]mat){ int N = mat.GetLength(0); // Stores the occurence of each // possible integer value Dictionary<int, int> mp = new Dictionary<int, int>(); // For 1st Row int t = Math.Abs(mat[N / 2, N / 2 + 1] - mat[N / 2, N / 2 - 1]); int A = Math.Min(mat[N / 2, N / 2 + 1], mat[N / 2, N / 2 - 1]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } // For 1st Col t = Math.Abs(mat[N / 2 + 1, N / 2] - mat[N / 2, N / 2]); A = Math.Min(mat[N / 2 + 1, N / 2], mat[N / 2, N / 2]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } // For Left Diagonal t = Math.Abs(mat[N / 2 + 1, N / 2 + 1] - mat[N / 2 - 1, N / 2 - 1]); A = Math.Min(mat[N / 2 + 1, N / 2 + 1], mat[N / 2 - 1, N / 2 - 1]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } // For Right Diagonal t = Math.Abs(mat[N / 2 - 1, N / 2 + 1] - mat[N / 2 + 1, N / 2 - 1]); A = Math.Min(mat[N / 2 - 1, N / 2 + 1], mat[N / 2 + 1, N / 2 - 1]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } int ans = -1, occur = 0; // Loop to find the largest integer // with maximum count foreach(KeyValuePair<int, int> x in mp) { if (occur < x.Value) { ans = x.Key; } if (occur == x.Value) { ans = Math.Max(ans, x.Value); } } // Return Answer return ans;} // Driver Codepublic static void Main(){ int [,]mat = { { 3, 4, 11 }, { 10, INT_MAX, 9 }, { -1, 6, 7 } }; Console.Write(findMissing(mat));}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to find the maximum value // of the missing integer such that the // count of AP's formed is maximized function findMissing(mat) { let N = mat.length; // Stores the occurence of each // possible integer value let mp = new Map(); // For 1st Row let t = Math.abs(mat[Math.floor(N / 2)][Math.floor(N / 2) + 1] - mat[Math.floor(N / 2)][Math.floor(N / 2) - 1]); let A = Math.min(mat[Math.floor(N / 2)][Math.floor(N / 2) + 1], mat[Math.floor(N / 2)][Math.floor(N / 2) - 1]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } // For 1st Col t = Math.abs(mat[Math.floor(N / 2) + 1][Math.floor(N / 2)] - mat[Math.floor(N / 2)][Math.floor(N / 2)]); A = Math.min(mat[Math.floor(N / 2) + 1][Math.floor(N / 2)], mat[Math.floor(N / 2)][Math.floor(N / 2)]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } // For Left Diagonal t = Math.abs(mat[Math.floor(N / 2) + 1][Math.floor(N / 2) + 1] - mat[Math.floor(N / 2) - 1][Math.floor(N / 2) - 1]); A = Math.min(mat[Math.floor(N / 2) + 1][Math.floor(N / 2) + 1], mat[Math.floor(N / 2) - 1][Math.floor(N / 2) - 1]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } // For Right Diagonal t = Math.abs(mat[Math.floor(N / 2) - 1][Math.floor(N / 2) + 1] - mat[Math.floor(N / 2) + 1][Math.floor(N / 2) - 1]); A = Math.min(mat[Math.floor(N / 2) - 1][Math.floor(N / 2) + 1], mat[Math.floor(N / 2) + 1][Math.floor(N / 2) - 1]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } let ans = -1, occur = 0; // Loop to find the largest integer // with maximum count for (let [key, val] of mp) { if (occur < val) { ans = key; } if (occur == val) { ans = Math.max(ans, key); } } // Return Answer return ans; } // Driver Code let mat = [[3, 4, 11], [10, Number.MAX_VALUE, 9], [-1, 6, 7]]; document.write(findMissing(mat)) // This code is contributed by Potta Lokesh </script> 5 Time Complexity: O(1)Auxiliary Space: O(1) lokeshpotta20 samim2000 ukasp shikhasingrajput Arithmetic Progressions C++ Programs Greedy Hash Mathematical Matrix Hash Greedy Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Pi(π) in C++ with Examples Const keyword in C++ Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 24215, "s": 24187, "text": "\n25 Jan, 2022" }, { "code": null, "e": 24473, "s": 24215, "text": "Given a N x N matrix, such that the element at the index [N/2, N/2] is missing, the task is to find the maximum integer that can be placed at index [N/2, N/2] such that the count of arithmetic progressions over all rows, columns, and diagonals is maximized." }, { "code": null, "e": 24482, "s": 24473, "text": "Example:" }, { "code": null, "e": 24641, "s": 24482, "text": "Input: mat[][]={{3, 4, 11}, {10, ?, 9}, {-1, 6, 7}}Output: 5Explanation: The maximum integer that can be palced on [1, 1] is 5. Hence, the AP’s formed is are:" }, { "code": null, "e": 24744, "s": 24641, "text": "Top left diagonal: 3, 5, 7.Top right diagonal: −1, 5, 1.Middle column: 4, 5, 6.Right column: 11, 9, 7." }, { "code": null, "e": 24772, "s": 24744, "text": "Top left diagonal: 3, 5, 7." }, { "code": null, "e": 24802, "s": 24772, "text": "Top right diagonal: −1, 5, 1." }, { "code": null, "e": 24826, "s": 24802, "text": "Middle column: 4, 5, 6." }, { "code": null, "e": 24850, "s": 24826, "text": "Right column: 11, 9, 7." }, { "code": null, "e": 24921, "s": 24850, "text": "Therefore, the number of AP formed is 4 which is the maximum possible." }, { "code": null, "e": 24981, "s": 24921, "text": "Input: mat[][]={{2, 2, 11}, {1, ?, 7}, {-1, 6, 6}}Output: 4" }, { "code": null, "e": 25284, "s": 24981, "text": "Approach: The given problem can be solved by finding all the possible numbers that can be placed on the index [N/2, N/2] such that it forms an Arithmetic progression over any row, column, or diagonal of the given matrix and keeping track of the largest integer out of them which forms the maximum AP’s." }, { "code": null, "e": 25326, "s": 25284, "text": "Let’s suppose the matrix is of 3*3 size. " }, { "code": null, "e": 25484, "s": 25326, "text": "Now, the missing element is (1, 1). So, for each row, column and diagonal, three numbers are present. Say, these three numbers are A, B, C and B is missing. " }, { "code": null, "e": 25594, "s": 25484, "text": "So, it can be observed that for integers A, B, and C to form and an AP, B must be equal to [A + (C – A)]/2. " }, { "code": null, "e": 25742, "s": 25594, "text": "Hence, for any value of A and C, B can be calculated using the above-discussed formula. Also, if (C – A) is odd then no integer value exists for B." }, { "code": null, "e": 25864, "s": 25742, "text": "So, apply this formula to over row, column and diagonal and find the maximum element which will form the maximum element." }, { "code": null, "e": 25912, "s": 25864, "text": "The same approach can be applied to N*N matrix." }, { "code": null, "e": 25963, "s": 25912, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25967, "s": 25963, "text": "C++" }, { "code": null, "e": 25972, "s": 25967, "text": "Java" }, { "code": null, "e": 25980, "s": 25972, "text": "Python3" }, { "code": null, "e": 25983, "s": 25980, "text": "C#" }, { "code": null, "e": 25994, "s": 25983, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum value// of the missing integer such that the// count of AP's formed is maximizedint findMissing(vector<vector<int> >& mat){ int N = mat.size(); // Stores the occurence of each // possible integer value unordered_map<int, int> mp; // For 1st Row int t = abs(mat[N / 2][N / 2 + 1] - mat[N / 2][N / 2 - 1]); int A = min(mat[N / 2][N / 2 + 1], mat[N / 2][N / 2 - 1]); if (t % 2 == 0) { mp[A + t / 2] += 1; } // For 1st Col t = abs(mat[N / 2 + 1][N / 2] - mat[N / 2][N / 2]); A = min(mat[N / 2 + 1][N / 2], mat[N / 2][N / 2]); if (t % 2 == 0) { mp[A + t / 2] += 1; } // For Left Diagonal t = abs(mat[N / 2 + 1][N / 2 + 1] - mat[N / 2 - 1][N / 2 - 1]); A = min(mat[N / 2 + 1][N / 2 + 1], mat[N / 2 - 1][N / 2 - 1]); if (t % 2 == 0) { mp[A + t / 2] += 1; } // For Right Diagonal t = abs(mat[N / 2 - 1][N / 2 + 1] - mat[N / 2 + 1][N / 2 - 1]); A = min(mat[N / 2 - 1][N / 2 + 1], mat[N / 2 + 1][N / 2 - 1]); if (t % 2 == 0) { mp[A + t / 2] += 1; } int ans = -1, occur = 0; // Loop to find the largest integer // with maximum count for (auto x : mp) { if (occur < x.second) { ans = x.first; } if (occur == x.second) { ans = max(ans, x.first); } } // Return Answer return ans;} // Driver Codeint main(){ vector<vector<int> > mat = { { 3, 4, 11 }, { 10, INT_MAX, 9 }, { -1, 6, 7 } }; cout << findMissing(mat);}", "e": 27723, "s": 25994, "text": null }, { "code": "// Java code for the above approachimport java.util.*;class GFG{ // Function to find the maximum value // of the missing integer such that the // count of AP's formed is maximized static int findMissing(int[][] mat) { int N = mat.length; // Stores the occurence of each // possible integer value HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // For 1st Row int t = Math.abs(mat[N / 2][N / 2 + 1] - mat[N / 2][N / 2 - 1]); int A = Math.min(mat[N / 2][N / 2 + 1], mat[N / 2][N / 2 - 1]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } // For 1st Col t = Math.abs(mat[N / 2 + 1][N / 2] - mat[N / 2][N / 2]); A = Math.min(mat[N / 2 + 1][N / 2], mat[N / 2][N / 2]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } // For Left Diagonal t = Math.abs(mat[N / 2 + 1][N / 2 + 1] - mat[N / 2 - 1][N / 2 - 1]); A = Math.min(mat[N / 2 + 1][N / 2 + 1], mat[N / 2 - 1][N / 2 - 1]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } // For Right Diagonal t = Math.abs(mat[N / 2 - 1][N / 2 + 1] - mat[N / 2 + 1][N / 2 - 1]); A = Math.min(mat[N / 2 - 1][N / 2 + 1], mat[N / 2 + 1][N / 2 - 1]); if (t % 2 == 0) { if (mp.containsKey(A + t / 2)) { mp.put(A + t / 2, mp.get(A + t / 2) + 1); } else { mp.put(A + t / 2, 1); } } int ans = -1, occur = 0; // Loop to find the largest integer // with maximum count for (Map.Entry<Integer, Integer> x : mp.entrySet()) { if (occur < x.getValue()) { ans = x.getKey(); } if (occur == x.getValue()) { ans = Math.max(ans, x.getKey()); } } // Return Answer return ans; } // Driver Code public static void main(String[] args) { int[][] mat = { { 3, 4, 11 }, { 10, Integer.MAX_VALUE, 9 }, { -1, 6, 7 } }; System.out.print(findMissing(mat)); }} // This code is contributed by shikhasingrajput", "e": 29956, "s": 27723, "text": null }, { "code": "# Python 3 code for the above approachfrom collections import defaultdictimport sys # Function to find the maximum value# of the missing integer such that the# count of AP's formed is maximizeddef findMissing(mat): N = len(mat) # Stores the occurence of each # possible integer value mp = defaultdict(int) # For 1st Row t = abs(mat[N // 2][N // 2 + 1] - mat[N // 2][N // 2 - 1]) A = min(mat[N // 2][N // 2 + 1], mat[N // 2][N // 2 - 1]) if (t % 2 == 0): mp[A + t // 2] += 1 # For 1st Col t = abs(mat[N // 2 + 1][N // 2] - mat[N // 2][N // 2]) A = min(mat[N // 2 + 1][N // 2], mat[N // 2][N // 2]) if (t % 2 == 0): mp[A + t // 2] += 1 # For Left Diagonal t = abs(mat[N // 2 + 1][N // 2 + 1] - mat[N // 2 - 1][N // 2 - 1]) A = min(mat[N // 2 + 1][N // 2 + 1], mat[N // 2 - 1][N // 2 - 1]) if (t % 2 == 0): mp[A + t // 2] += 1 # For Right Diagonal t = abs(mat[N // 2 - 1][N // 2 + 1] - mat[N // 2 + 1][N // 2 - 1]) A = min(mat[N // 2 - 1][N // 2 + 1], mat[N // 2 + 1][N // 2 - 1]) if (t % 2 == 0): mp[A + t // 2] += 1 ans = -1 occur = 0 # Loop to find the largest integer # with maximum count for x in mp: if (occur < mp[x]): ans = x if (occur == mp[x]): ans = max(ans, x) # Return Answer return ans # Driver Codeif __name__ == \"__main__\": mat = [[3, 4, 11], [10, sys.maxsize, 9], [-1, 6, 7]] print(findMissing(mat)) # This code is contributed by ukasp.", "e": 31587, "s": 29956, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static int INT_MAX = 2147483647; // Function to find the maximum value// of the missing integer such that the// count of AP's formed is maximizedstatic int findMissing(int [,]mat){ int N = mat.GetLength(0); // Stores the occurence of each // possible integer value Dictionary<int, int> mp = new Dictionary<int, int>(); // For 1st Row int t = Math.Abs(mat[N / 2, N / 2 + 1] - mat[N / 2, N / 2 - 1]); int A = Math.Min(mat[N / 2, N / 2 + 1], mat[N / 2, N / 2 - 1]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } // For 1st Col t = Math.Abs(mat[N / 2 + 1, N / 2] - mat[N / 2, N / 2]); A = Math.Min(mat[N / 2 + 1, N / 2], mat[N / 2, N / 2]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } // For Left Diagonal t = Math.Abs(mat[N / 2 + 1, N / 2 + 1] - mat[N / 2 - 1, N / 2 - 1]); A = Math.Min(mat[N / 2 + 1, N / 2 + 1], mat[N / 2 - 1, N / 2 - 1]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } // For Right Diagonal t = Math.Abs(mat[N / 2 - 1, N / 2 + 1] - mat[N / 2 + 1, N / 2 - 1]); A = Math.Min(mat[N / 2 - 1, N / 2 + 1], mat[N / 2 + 1, N / 2 - 1]); if (t % 2 == 0) { if (mp.ContainsKey(A + t / 2)) { mp[A + t / 2] = mp[A + t / 2] + 1; } else { mp.Add(A + t / 2, 1); } } int ans = -1, occur = 0; // Loop to find the largest integer // with maximum count foreach(KeyValuePair<int, int> x in mp) { if (occur < x.Value) { ans = x.Key; } if (occur == x.Value) { ans = Math.Max(ans, x.Value); } } // Return Answer return ans;} // Driver Codepublic static void Main(){ int [,]mat = { { 3, 4, 11 }, { 10, INT_MAX, 9 }, { -1, 6, 7 } }; Console.Write(findMissing(mat));}} // This code is contributed by Samim Hossain Mondal.", "e": 34099, "s": 31587, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the maximum value // of the missing integer such that the // count of AP's formed is maximized function findMissing(mat) { let N = mat.length; // Stores the occurence of each // possible integer value let mp = new Map(); // For 1st Row let t = Math.abs(mat[Math.floor(N / 2)][Math.floor(N / 2) + 1] - mat[Math.floor(N / 2)][Math.floor(N / 2) - 1]); let A = Math.min(mat[Math.floor(N / 2)][Math.floor(N / 2) + 1], mat[Math.floor(N / 2)][Math.floor(N / 2) - 1]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } // For 1st Col t = Math.abs(mat[Math.floor(N / 2) + 1][Math.floor(N / 2)] - mat[Math.floor(N / 2)][Math.floor(N / 2)]); A = Math.min(mat[Math.floor(N / 2) + 1][Math.floor(N / 2)], mat[Math.floor(N / 2)][Math.floor(N / 2)]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } // For Left Diagonal t = Math.abs(mat[Math.floor(N / 2) + 1][Math.floor(N / 2) + 1] - mat[Math.floor(N / 2) - 1][Math.floor(N / 2) - 1]); A = Math.min(mat[Math.floor(N / 2) + 1][Math.floor(N / 2) + 1], mat[Math.floor(N / 2) - 1][Math.floor(N / 2) - 1]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } // For Right Diagonal t = Math.abs(mat[Math.floor(N / 2) - 1][Math.floor(N / 2) + 1] - mat[Math.floor(N / 2) + 1][Math.floor(N / 2) - 1]); A = Math.min(mat[Math.floor(N / 2) - 1][Math.floor(N / 2) + 1], mat[Math.floor(N / 2) + 1][Math.floor(N / 2) - 1]); if (t % 2 == 0) { if (mp.has(A + Math.floor(t / 2))) mp.set(A + Math.floor(t / 2), mp.get(A + Math.floor(t / 2)) + 1); else mp.set(A + Math.floor(t / 2), 1); } let ans = -1, occur = 0; // Loop to find the largest integer // with maximum count for (let [key, val] of mp) { if (occur < val) { ans = key; } if (occur == val) { ans = Math.max(ans, key); } } // Return Answer return ans; } // Driver Code let mat = [[3, 4, 11], [10, Number.MAX_VALUE, 9], [-1, 6, 7]]; document.write(findMissing(mat)) // This code is contributed by Potta Lokesh </script>", "e": 37358, "s": 34099, "text": null }, { "code": null, "e": 37363, "s": 37361, "text": "5" }, { "code": null, "e": 37408, "s": 37365, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 37424, "s": 37410, "text": "lokeshpotta20" }, { "code": null, "e": 37434, "s": 37424, "text": "samim2000" }, { "code": null, "e": 37440, "s": 37434, "text": "ukasp" }, { "code": null, "e": 37457, "s": 37440, "text": "shikhasingrajput" }, { "code": null, "e": 37481, "s": 37457, "text": "Arithmetic Progressions" }, { "code": null, "e": 37494, "s": 37481, "text": "C++ Programs" }, { "code": null, "e": 37501, "s": 37494, "text": "Greedy" }, { "code": null, "e": 37506, "s": 37501, "text": "Hash" }, { "code": null, "e": 37519, "s": 37506, "text": "Mathematical" }, { "code": null, "e": 37526, "s": 37519, "text": "Matrix" }, { "code": null, "e": 37531, "s": 37526, "text": "Hash" }, { "code": null, "e": 37538, "s": 37531, "text": "Greedy" }, { "code": null, "e": 37551, "s": 37538, "text": "Mathematical" }, { "code": null, "e": 37558, "s": 37551, "text": "Matrix" }, { "code": null, "e": 37656, "s": 37558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37665, "s": 37656, "text": "Comments" }, { "code": null, "e": 37678, "s": 37665, "text": "Old Comments" }, { "code": null, "e": 37719, "s": 37678, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 37778, "s": 37719, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 37790, "s": 37778, "text": "cout in C++" }, { "code": null, "e": 37817, "s": 37790, "text": "Pi(π) in C++ with Examples" }, { "code": null, "e": 37838, "s": 37817, "text": "Const keyword in C++" }, { "code": null, "e": 37889, "s": 37838, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 37940, "s": 37889, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 37967, "s": 37940, "text": "Program for array rotation" }, { "code": null, "e": 38025, "s": 37967, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
How to create circular ProgressBar in Android?
This example demonstrate about How to create circular ProgressBar 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/drawable/circular_progress_bar.xml. <? xml version= "1.0" encoding= "utf-8" ?> <rotate xmlns: android = "http://schemas.android.com/apk/res/android" android :fromDegrees= "270" android :toDegrees= "270" > <shape android :innerRadiusRatio= "2.5" android :shape= "ring" android :thickness= "1dp" android :useLevel= "true" > <!-- this line fixes the issue for lollipop api 21 --> <gradient android :angle= "0" android :endColor= "#007DD6" android :startColor= "#007DD6" android :type= "sweep" android :useLevel= "false" /> </shape> </rotate> Step 3 − Add the following code to res/drawable/circular_shape.xml <? xml version= "1.0" encoding= "utf-8" ?> <shape xmlns: android = "http://schemas.android.com/apk/res/android" android :innerRadiusRatio= "2.5" android :shape= "ring" android :thickness= "1dp" android :useLevel= "false" > <solid android :color= "#CCC" /> </shape> Step 4 − Add the following code to res/layout/activity_main.xml. <? xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :layout_margin= "16dp" tools :context= ".MainActivity" > <ProgressBar android :id= "@+id/progressBar" style= "?android:attr/progressBarStyleHorizontal" android :layout_width= "200dp" android :layout_height= "200dp" android :layout_centerInParent= "true" android :background= "@drawable/circular_shape" android :indeterminate= "false" android :max= "100" android :progress= "65" android :progressDrawable= "@drawable/circular_progress_bar" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package app.tutorialspoint.com.sample ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } } Step 4 − 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.tutorialspoint.com.sample" > <uses-permission android :name= "android.permission.CALL_PHONE" /> <application android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android :label= "@string/app_name" android :roundIcon= "@mipmap/ic_launcher_round" android :supportsRtl= "true" android :theme= "@style/AppTheme" > <activity android :name= ".MainActivity" > <intent-filter> <action android :name= "android.intent.action.MAIN" /> <category android :name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run 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": 1140, "s": 1062, "text": "This example demonstrate about How to create circular ProgressBar in Android." }, { "code": null, "e": 1269, "s": 1140, "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": 1344, "s": 1269, "text": "Step 2 − Add the following code to res/drawable/circular_progress_bar.xml." }, { "code": null, "e": 1934, "s": 1344, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<rotate xmlns: android = \"http://schemas.android.com/apk/res/android\"\n android :fromDegrees= \"270\"\n android :toDegrees= \"270\" >\n <shape\n android :innerRadiusRatio= \"2.5\"\n android :shape= \"ring\"\n android :thickness= \"1dp\"\n android :useLevel= \"true\" > <!-- this line fixes the issue for lollipop api 21 -->\n <gradient\n android :angle= \"0\"\n android :endColor= \"#007DD6\"\n android :startColor= \"#007DD6\"\n android :type= \"sweep\"\n android :useLevel= \"false\" />\n </shape>\n</rotate>" }, { "code": null, "e": 2001, "s": 1934, "text": "Step 3 − Add the following code to res/drawable/circular_shape.xml" }, { "code": null, "e": 2281, "s": 2001, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<shape xmlns: android = \"http://schemas.android.com/apk/res/android\"\n android :innerRadiusRatio= \"2.5\"\n android :shape= \"ring\"\n android :thickness= \"1dp\"\n android :useLevel= \"false\" >\n <solid android :color= \"#CCC\" />\n</shape>" }, { "code": null, "e": 2346, "s": 2281, "text": "Step 4 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3140, "s": 2346, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <ProgressBar\n android :id= \"@+id/progressBar\"\n style= \"?android:attr/progressBarStyleHorizontal\"\n android :layout_width= \"200dp\"\n android :layout_height= \"200dp\"\n android :layout_centerInParent= \"true\"\n android :background= \"@drawable/circular_shape\"\n android :indeterminate= \"false\"\n android :max= \"100\"\n android :progress= \"65\"\n android :progressDrawable= \"@drawable/circular_progress_bar\" />\n</RelativeLayout>" }, { "code": null, "e": 3197, "s": 3140, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3538, "s": 3197, "text": "package app.tutorialspoint.com.sample ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.os.Bundle ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n}" }, { "code": null, "e": 3593, "s": 3538, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4380, "s": 3593, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\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": 4727, "s": 4380, "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 –" } ]
Analyzing the Titanic with a Business Analyst mindset using R (ggplot2) | by Etoma Egot | Towards Data Science
Lately, i have been fascinated with R programming software and the fantastic data visualization package (ggplot2) created by Hadley Wickham. I am a Business analyst by profession with lots of experience in the e-payments industry but i have found passion with data analysis, visualizing and communicating data to stakeholders. Well, why Titanic...one may ask? Coincidentally, i decided to watch the Titanic movie a second time but this time with the mindset of a Business analyst inspired by the power of data analysis . The first time i watched the movie i had a couple of questions in mind about how things played out on the Titanic, but didn’t get around with finding the answers back then. Well this time , i got inspired by the solution-driven nature of data analysis and decided to source the answers to my own questions by pulling the ubiquitous Titanic Dataset on google. I began my analysis with a couple of probe questions (BAs ask lots of questions, guess you all know this already :))regarding the events that unfolded in the Titanic shipwreck. The visualization dashboard below materialized during my analysis. What was the Survival rate on the Titanic?How could i use data to visualize the Women and Children first approach adopted by rescuers on the Titanic?What was the age distribution on the Titanic (both survivors and fatalities)?What was the survivor age distribution by ticket class on the Titanic?Following that the Titanic was the most expensive ship over a century ago, how does the fare value compare across all ticket classes? What was the Survival rate on the Titanic? How could i use data to visualize the Women and Children first approach adopted by rescuers on the Titanic? What was the age distribution on the Titanic (both survivors and fatalities)? What was the survivor age distribution by ticket class on the Titanic? Following that the Titanic was the most expensive ship over a century ago, how does the fare value compare across all ticket classes? If you’ve seen the movie then you’re in the right place and if you haven’t then you are the very target of my findings. Perhaps, you may decide to watch it right away. Now, let’s get into it. Let’s start by loading the packages we’ll use to create the visualizations used for the analysis. Tidyverse package will help with data processing and graphing. Load relevant libraries and import the Titanic Dataset saved on your computer drive into R Studio. Note: The source dataframe does not contain information for the crew, but it does contain actual and estimated ages for almost 80% of the passengers library(tidyverse)titanic <- read.csv(file.choose()) Examine the structure of your dataset (variable names and variable type). This step is essential to determining the suitability of your variables for plotting. #Check out the structure of the datasetsummary(titanic)str(titanic)names(titanic)head(titanic.df, n = 10)#Remove rows with NAtitanic.df <- filter(titanic, survived != "") First, the dataset was cleaned up to remove or replace missing values. The columns in the dataset are listed below: Pclass: Ticket Class (1 = 1st, 2= 2nd; 3= 3rd) Survived: Survival ( 0 = No;1 = Yes) Name: Passenger name Sex: Gender (Male or Female) Age: Passenger Age SibSp: Nos of sibling and/or spouses aboard Parch: Nos of parent(s) and/or children aboard Ticket: Ticket number Fare: Fare price (British Pound) Cabin: Cabin Embarked: Port of embarkation (C = Cherbourg: Q = Queenstown: S= Southampton) Boat: Lifeboat Body: Body Identification Number home.dest:Address of Passengers Home or Destination The next step is we need to decide what variables we need and the appropriate scale to visualize our data. I used the table classification below, To answer our first question, What was the Survival rate on the Titanic? In order of class (*1st, 2nd and 3rd), the percentage of females that survived was 97%, 89% and 49%. In order of class (*1st, 2nd and 3rd), the percentage of males that survived was 34%, 15(~14.6)% and 15(~15.2)%. Run the code below to generate corresponding visualizations: ggplot(data = titanic.df) + aes(x = age, fill = survived) + geom_histogram(bin = 30, colour = "#1380A1") + #scale_fill_brewer(palette = "Accent") + labs(title = "Survival rate on the Titanic", y = "Survived", subtitle = "Distribution By Age, Gender and class of ticket", caption = "Author: etoma.egot") + theme_tomski() + # using a custom theme for my visualizations#theme_bw()+ #Use the inbuilt ggplot2 them for your practice facet_grid(sex~pclass, scales = "free")#Proportion of 1st, 2nd and 3rd class women and men who survivedmf.survived <- titanic.df %>% filter(survived == 1)%>% group_by(pclass,sex)%>% summarise(Counts = n() )mf.died <- titanic.df %>% filter(survived != 1)%>% group_by(pclass,sex)%>% summarise(Counts = n() )mf.perc.survived <- mf.survived/(mf.survived + mf.died) * 100select (mf.perc.survived, Counts) Results Interpretation: This graph helps identify the rate of survival patterns considering all the three variables(age, sex, ticket class). In order of class (*1st, 2nd and 3rd), the percentage of females that survived was 97%, 89% and 49%. In order of class (*1st, 2nd and 3rd), the percentage of males that survived was 34%, 15(~14.6)% and 15(~15.2)%. Within 1st and 2nd class, all Children survived except one female child from 1st class. There were more children fatalities in 3rd class. To our second question, How could i use data to confirm the Women and Children first approach adopted by rescuers on the Titanic? Children and women in order of ticket class were considered first by rescuers with priority been women and children and older adults at least 60 yrs across all classes. Run the code to get the visualization below: titanic.df %>% filter(fare <= 300)%>% ggplot(mapping = aes(x = age, y = fare)) + geom_point(aes(colour = survived, size = fare, alpha = 0.7)) + geom_smooth(se = FALSE)+ facet_grid(sex~pclass, scales = "free") + labs(title = "Priority and pattern of rescue on the Titanic", x = "Age (yrs)", y = "Fare(£)", subtitle = "Children and women in order of ticket class were\nconsidered first in the rescue plan with priority been\nwomen, children and older adults >= 60yrs", caption = "Author: etoma.egot") + theme( plot.subtitle = element_text(colour = "#17c5c9", size=14))+ theme_tomski() #using a custom theme Results Interpretation Following the results of the distribution in the figure above.(fares been proportional to ticket class). Aside the fact that Children (<=12) on the titanic were charged separate boarding fares. It seemed like the fares for children and teens seem unusually high when compared with average fares for non-children age groups. Let me know if you know why this is so. Nonetheless,the bubble chart gives some other clues in regards to the pattern of rescue operations. Evidently, Women and Children first approach in order of ticket class was adopted in the rescue plans by rescuers with priority been women and children and older adults at least 60yrs across all classes. Apparently little or no priority was given to male passengers by rescuers ##Note: I removed the outlier fares (500 £) from the bubble chart. The males and females who paid these fares were anyway rescued. I used boxplots to visualize the next three questions: Moving on to the 3rd question, What was the age distribution on the Titanic (both survivors and fatalities)? Generally, the males on the titanic were older than the females by an average of 3yrs across all ticket classes. titanic.df %>% ggplot(mapping = aes(x = pclass, y = age)) + geom_point(colour = "#1380A1", size = 1) + geom_jitter(aes(colour = survived))+ #This generates multiple colours geom_boxplot(alpha = 0.7, outlier.colour = NA)+ labs(title = "Age Distribution by Class on the Titanic", x = "Ticket Class", y = "Age(Yrs)", subtitle = "The males on the titanic were older than the females by an average of 3yrs across all ticket classes ", caption = "Author: etoma.egot") + theme_tomski() + #using my own custom theme theme(plot.subtitle = element_text( size=18))+ facet_wrap(.~sex)#Calculating Mean and median age by Class and Gender for adultstitanic.df %>% group_by(pclass, sex)%>% summarise( n = n(), #count of passengers Average.age = mean(age, na.rm = TRUE), Median.age = median(age, na.rm = TRUE) ) Results Interpretation Negatively Skewed — the boxplot will show the median closer to the upper quartilePositively Skewed — the boxplot will show the median closer to the lower quartile FEMALE About 75% of the females in order of class (*1st, 2nd, 3rd) were at least 22, 20 and 17 yrs old. The median age was 36 yrs (normally distributed),28yrs (negatively skewed) and 22 yrs (positively skewed) MALE About 75% of the males in order of class (*1st, 2nd, 3rd) were at least 30, 24 and 20 yrs old.The median age was 42 yrs (negatively skewed),30yrs (positively skewed) and 25 yrs (positively skewed) #Summary:Generally, the males on the titanic were older than the females by an average of 3yrs across all ticket classes. Subsequently, for the 4th question, What was the survivor age distribution by ticket class on the Titanic? The median age of male and female survivors in 1st class was the same(36 yrs)- The females in 2nd class were 1.5 times older than the males - The males in 3rd class were older than the females by 2yrs titanic.df %>% filter(survived ==1)%>% ggplot(mapping = aes(x = pclass, y = age)) + geom_point(size = 1) + geom_jitter(colour = "#1380A1")+ geom_boxplot(alpha = 0.7, outlier.colour = NA)+ labs(title = "Survivors Age Distribution by Class on the Titanic", x = "Ticket Class", y = "Age(Yrs)", subtitle = "The median age of male and female survivors in 1st class was the same(36 yrs)\nThe females in 2nd class were 1.5 times older than the males\nThe males in 3rd class were older than the females by 2yrs", caption = "Author: etoma.egot") + theme_tomski() + #using my own custom theme theme(plot.subtitle = element_text(colour = "#1380A1", size=18))+ facet_wrap(.~sex)#Calculating Mean and median age by Class and Gender for adultstitanic.df %>% filter(survived ==1)%>% group_by(pclass, sex)%>% summarise( n = n(), #count of passengers Average.age = mean(age, na.rm = TRUE), Median.age = median(age, na.rm = TRUE) ) Results Interpretation FEMALE- The median age was 36 yrs (normally distributed),28yrs (negatively skewed) and 22 yrs (positively skewed) MALE- The median age was 36 yrs (positively skewed),19yrs (negatively skewed) and 25 yrs (negatively skewed) #Summary:- The median age of male and female survivors in 1st class was the same(36 yrs)- The females in 2nd class were 1.5 times older than the males - The males in 3rd class were older than the females by 2yrs Finally, for the last question, Following that the Titanic was the most expensive ship over a century ago, how does the fare value compare across all ticket classes? 1st class ticket costs about 3 times a 2nd class ticket and 2nd class ticket was worth about twice that of 3rd class. #Prepare Data, remove outliers in faretitanic.df %>% filter(fare < 300)%>% ggplot(mapping = aes(x = pclass, y = fare)) + #geom_point(colour = "#1380A1", size = 1) + #geom_jitter(aes(colour = survived))+ geom_boxplot(colour = "#1380A1", outlier.colour = NA)+ labs(title = "Fare Value by Class", x = "Ticket Class", y = "Ticket Fare (£)", subtitle = "1st class ticket was worth 3 times a 2nd class ticket\nand 2nd class ticket was worth almost twice that of 3rd class", caption = "Author: etoma.egot") + theme_tomski()+ #using my own custom theme theme(plot.subtitle = element_text(colour = "#1380A1",size=18))+ coord_cartesian(ylim = c(0,125))+ coord_flip()#Calculating Mean and Median Fare by Classtitanic.df %>% filter(fare < 300)%>% group_by(pclass)%>% summarise( Average.fares = mean(fare, na.rm = TRUE), Median.fare = median(fare, na.rm = TRUE) )#Calculating Mean and Median Fare by Class for childrentitanic.df %>% filter(fare < 300, age <= 12)%>% group_by(pclass)%>% summarise( n = n(), Average.fares = mean(fare, na.rm = TRUE), Median.fare = median(fare, na.rm = TRUE) )#Calculating Mean and Median Fare by Class for adultstitanic.df %>% filter(fare < 300, age >= 12)%>% group_by(pclass)%>% summarise( n = n(), Average.fare = mean(fare, na.rm = TRUE), Median.fare = median(fare, na.rm = TRUE) ) Results Interpretation The box plot confirms that the ticket fare is proportional to the Ticket class.Pretty much intuitive. The distribution is skewed to the right .The median fares for 1st, 2nd and 3rd class is 59.4 £, 15 £ and 8.05 £. The mean fares for 1st, 2nd and 3rd class is 82.2 £, 21.2 £ and 13.3 £.(mean fares are greater than median fares). Hence,a better measure of the center for this distribution is the median. Thus,1st class ticket costs about 3 times a 2nd class ticket and 2nd class ticket was worth about twice that of 3rd class. The average and median fare for children is higher when compared to that of adults in same class. Note: For a symmetrical distribution, the mean is in the middle. Hence, Mean is an appropriate measure to use for comparisons. But if a distribution is skewed, then the mean is usually not in the middle. Hence, median is an appropriate measure for comparisonsI am quite thrilled at my first write-up on TDS, nonetheless, if you have done similar analysis, i still need to clarify if Children really paid more than some adults across different age groups as my visualization bubble chart results seem to suggest. Thanks for reading!.
[ { "code": null, "e": 499, "s": 172, "text": "Lately, i have been fascinated with R programming software and the fantastic data visualization package (ggplot2) created by Hadley Wickham. I am a Business analyst by profession with lots of experience in the e-payments industry but i have found passion with data analysis, visualizing and communicating data to stakeholders." }, { "code": null, "e": 1052, "s": 499, "text": "Well, why Titanic...one may ask? Coincidentally, i decided to watch the Titanic movie a second time but this time with the mindset of a Business analyst inspired by the power of data analysis . The first time i watched the movie i had a couple of questions in mind about how things played out on the Titanic, but didn’t get around with finding the answers back then. Well this time , i got inspired by the solution-driven nature of data analysis and decided to source the answers to my own questions by pulling the ubiquitous Titanic Dataset on google." }, { "code": null, "e": 1296, "s": 1052, "text": "I began my analysis with a couple of probe questions (BAs ask lots of questions, guess you all know this already :))regarding the events that unfolded in the Titanic shipwreck. The visualization dashboard below materialized during my analysis." }, { "code": null, "e": 1726, "s": 1296, "text": "What was the Survival rate on the Titanic?How could i use data to visualize the Women and Children first approach adopted by rescuers on the Titanic?What was the age distribution on the Titanic (both survivors and fatalities)?What was the survivor age distribution by ticket class on the Titanic?Following that the Titanic was the most expensive ship over a century ago, how does the fare value compare across all ticket classes?" }, { "code": null, "e": 1769, "s": 1726, "text": "What was the Survival rate on the Titanic?" }, { "code": null, "e": 1877, "s": 1769, "text": "How could i use data to visualize the Women and Children first approach adopted by rescuers on the Titanic?" }, { "code": null, "e": 1955, "s": 1877, "text": "What was the age distribution on the Titanic (both survivors and fatalities)?" }, { "code": null, "e": 2026, "s": 1955, "text": "What was the survivor age distribution by ticket class on the Titanic?" }, { "code": null, "e": 2160, "s": 2026, "text": "Following that the Titanic was the most expensive ship over a century ago, how does the fare value compare across all ticket classes?" }, { "code": null, "e": 2352, "s": 2160, "text": "If you’ve seen the movie then you’re in the right place and if you haven’t then you are the very target of my findings. Perhaps, you may decide to watch it right away. Now, let’s get into it." }, { "code": null, "e": 2513, "s": 2352, "text": "Let’s start by loading the packages we’ll use to create the visualizations used for the analysis. Tidyverse package will help with data processing and graphing." }, { "code": null, "e": 2612, "s": 2513, "text": "Load relevant libraries and import the Titanic Dataset saved on your computer drive into R Studio." }, { "code": null, "e": 2761, "s": 2612, "text": "Note: The source dataframe does not contain information for the crew, but it does contain actual and estimated ages for almost 80% of the passengers" }, { "code": null, "e": 2814, "s": 2761, "text": "library(tidyverse)titanic <- read.csv(file.choose())" }, { "code": null, "e": 2974, "s": 2814, "text": "Examine the structure of your dataset (variable names and variable type). This step is essential to determining the suitability of your variables for plotting." }, { "code": null, "e": 3145, "s": 2974, "text": "#Check out the structure of the datasetsummary(titanic)str(titanic)names(titanic)head(titanic.df, n = 10)#Remove rows with NAtitanic.df <- filter(titanic, survived != \"\")" }, { "code": null, "e": 3216, "s": 3145, "text": "First, the dataset was cleaned up to remove or replace missing values." }, { "code": null, "e": 3261, "s": 3216, "text": "The columns in the dataset are listed below:" }, { "code": null, "e": 3308, "s": 3261, "text": "Pclass: Ticket Class (1 = 1st, 2= 2nd; 3= 3rd)" }, { "code": null, "e": 3345, "s": 3308, "text": "Survived: Survival ( 0 = No;1 = Yes)" }, { "code": null, "e": 3366, "s": 3345, "text": "Name: Passenger name" }, { "code": null, "e": 3395, "s": 3366, "text": "Sex: Gender (Male or Female)" }, { "code": null, "e": 3414, "s": 3395, "text": "Age: Passenger Age" }, { "code": null, "e": 3458, "s": 3414, "text": "SibSp: Nos of sibling and/or spouses aboard" }, { "code": null, "e": 3505, "s": 3458, "text": "Parch: Nos of parent(s) and/or children aboard" }, { "code": null, "e": 3527, "s": 3505, "text": "Ticket: Ticket number" }, { "code": null, "e": 3560, "s": 3527, "text": "Fare: Fare price (British Pound)" }, { "code": null, "e": 3573, "s": 3560, "text": "Cabin: Cabin" }, { "code": null, "e": 3651, "s": 3573, "text": "Embarked: Port of embarkation (C = Cherbourg: Q = Queenstown: S= Southampton)" }, { "code": null, "e": 3666, "s": 3651, "text": "Boat: Lifeboat" }, { "code": null, "e": 3699, "s": 3666, "text": "Body: Body Identification Number" }, { "code": null, "e": 3751, "s": 3699, "text": "home.dest:Address of Passengers Home or Destination" }, { "code": null, "e": 3897, "s": 3751, "text": "The next step is we need to decide what variables we need and the appropriate scale to visualize our data. I used the table classification below," }, { "code": null, "e": 3970, "s": 3897, "text": "To answer our first question, What was the Survival rate on the Titanic?" }, { "code": null, "e": 4071, "s": 3970, "text": "In order of class (*1st, 2nd and 3rd), the percentage of females that survived was 97%, 89% and 49%." }, { "code": null, "e": 4184, "s": 4071, "text": "In order of class (*1st, 2nd and 3rd), the percentage of males that survived was 34%, 15(~14.6)% and 15(~15.2)%." }, { "code": null, "e": 4245, "s": 4184, "text": "Run the code below to generate corresponding visualizations:" }, { "code": null, "e": 5104, "s": 4245, "text": "ggplot(data = titanic.df) + aes(x = age, fill = survived) + geom_histogram(bin = 30, colour = \"#1380A1\") + #scale_fill_brewer(palette = \"Accent\") + labs(title = \"Survival rate on the Titanic\", y = \"Survived\", subtitle = \"Distribution By Age, Gender and class of ticket\", caption = \"Author: etoma.egot\") + theme_tomski() + # using a custom theme for my visualizations#theme_bw()+ #Use the inbuilt ggplot2 them for your practice facet_grid(sex~pclass, scales = \"free\")#Proportion of 1st, 2nd and 3rd class women and men who survivedmf.survived <- titanic.df %>% filter(survived == 1)%>% group_by(pclass,sex)%>% summarise(Counts = n() )mf.died <- titanic.df %>% filter(survived != 1)%>% group_by(pclass,sex)%>% summarise(Counts = n() )mf.perc.survived <- mf.survived/(mf.survived + mf.died) * 100select (mf.perc.survived, Counts)" }, { "code": null, "e": 5128, "s": 5104, "text": "Results Interpretation:" }, { "code": null, "e": 5245, "s": 5128, "text": "This graph helps identify the rate of survival patterns considering all the three variables(age, sex, ticket class)." }, { "code": null, "e": 5346, "s": 5245, "text": "In order of class (*1st, 2nd and 3rd), the percentage of females that survived was 97%, 89% and 49%." }, { "code": null, "e": 5459, "s": 5346, "text": "In order of class (*1st, 2nd and 3rd), the percentage of males that survived was 34%, 15(~14.6)% and 15(~15.2)%." }, { "code": null, "e": 5597, "s": 5459, "text": "Within 1st and 2nd class, all Children survived except one female child from 1st class. There were more children fatalities in 3rd class." }, { "code": null, "e": 5727, "s": 5597, "text": "To our second question, How could i use data to confirm the Women and Children first approach adopted by rescuers on the Titanic?" }, { "code": null, "e": 5896, "s": 5727, "text": "Children and women in order of ticket class were considered first by rescuers with priority been women and children and older adults at least 60 yrs across all classes." }, { "code": null, "e": 5941, "s": 5896, "text": "Run the code to get the visualization below:" }, { "code": null, "e": 6636, "s": 5941, "text": "titanic.df %>% filter(fare <= 300)%>% ggplot(mapping = aes(x = age, y = fare)) + geom_point(aes(colour = survived, size = fare, alpha = 0.7)) + geom_smooth(se = FALSE)+ facet_grid(sex~pclass, scales = \"free\") + labs(title = \"Priority and pattern of rescue on the Titanic\", x = \"Age (yrs)\", y = \"Fare(£)\", subtitle = \"Children and women in order of ticket class were\\nconsidered first in the rescue plan with priority been\\nwomen, children and older adults >= 60yrs\", caption = \"Author: etoma.egot\") + theme( plot.subtitle = element_text(colour = \"#17c5c9\", size=14))+ theme_tomski() #using a custom theme" }, { "code": null, "e": 6659, "s": 6636, "text": "Results Interpretation" }, { "code": null, "e": 7023, "s": 6659, "text": "Following the results of the distribution in the figure above.(fares been proportional to ticket class). Aside the fact that Children (<=12) on the titanic were charged separate boarding fares. It seemed like the fares for children and teens seem unusually high when compared with average fares for non-children age groups. Let me know if you know why this is so." }, { "code": null, "e": 7327, "s": 7023, "text": "Nonetheless,the bubble chart gives some other clues in regards to the pattern of rescue operations. Evidently, Women and Children first approach in order of ticket class was adopted in the rescue plans by rescuers with priority been women and children and older adults at least 60yrs across all classes." }, { "code": null, "e": 7401, "s": 7327, "text": "Apparently little or no priority was given to male passengers by rescuers" }, { "code": null, "e": 7532, "s": 7401, "text": "##Note: I removed the outlier fares (500 £) from the bubble chart. The males and females who paid these fares were anyway rescued." }, { "code": null, "e": 7587, "s": 7532, "text": "I used boxplots to visualize the next three questions:" }, { "code": null, "e": 7696, "s": 7587, "text": "Moving on to the 3rd question, What was the age distribution on the Titanic (both survivors and fatalities)?" }, { "code": null, "e": 7809, "s": 7696, "text": "Generally, the males on the titanic were older than the females by an average of 3yrs across all ticket classes." }, { "code": null, "e": 8695, "s": 7809, "text": "titanic.df %>% ggplot(mapping = aes(x = pclass, y = age)) + geom_point(colour = \"#1380A1\", size = 1) + geom_jitter(aes(colour = survived))+ #This generates multiple colours geom_boxplot(alpha = 0.7, outlier.colour = NA)+ labs(title = \"Age Distribution by Class on the Titanic\", x = \"Ticket Class\", y = \"Age(Yrs)\", subtitle = \"The males on the titanic were older than the females by an average of 3yrs across all ticket classes \", caption = \"Author: etoma.egot\") + theme_tomski() + #using my own custom theme theme(plot.subtitle = element_text( size=18))+ facet_wrap(.~sex)#Calculating Mean and median age by Class and Gender for adultstitanic.df %>% group_by(pclass, sex)%>% summarise( n = n(), #count of passengers Average.age = mean(age, na.rm = TRUE), Median.age = median(age, na.rm = TRUE) )" }, { "code": null, "e": 8718, "s": 8695, "text": "Results Interpretation" }, { "code": null, "e": 8881, "s": 8718, "text": "Negatively Skewed — the boxplot will show the median closer to the upper quartilePositively Skewed — the boxplot will show the median closer to the lower quartile" }, { "code": null, "e": 8888, "s": 8881, "text": "FEMALE" }, { "code": null, "e": 9091, "s": 8888, "text": "About 75% of the females in order of class (*1st, 2nd, 3rd) were at least 22, 20 and 17 yrs old. The median age was 36 yrs (normally distributed),28yrs (negatively skewed) and 22 yrs (positively skewed)" }, { "code": null, "e": 9096, "s": 9091, "text": "MALE" }, { "code": null, "e": 9293, "s": 9096, "text": "About 75% of the males in order of class (*1st, 2nd, 3rd) were at least 30, 24 and 20 yrs old.The median age was 42 yrs (negatively skewed),30yrs (positively skewed) and 25 yrs (positively skewed)" }, { "code": null, "e": 9415, "s": 9293, "text": "#Summary:Generally, the males on the titanic were older than the females by an average of 3yrs across all ticket classes." }, { "code": null, "e": 9522, "s": 9415, "text": "Subsequently, for the 4th question, What was the survivor age distribution by ticket class on the Titanic?" }, { "code": null, "e": 9723, "s": 9522, "text": "The median age of male and female survivors in 1st class was the same(36 yrs)- The females in 2nd class were 1.5 times older than the males - The males in 3rd class were older than the females by 2yrs" }, { "code": null, "e": 10724, "s": 9723, "text": "titanic.df %>% filter(survived ==1)%>% ggplot(mapping = aes(x = pclass, y = age)) + geom_point(size = 1) + geom_jitter(colour = \"#1380A1\")+ geom_boxplot(alpha = 0.7, outlier.colour = NA)+ labs(title = \"Survivors Age Distribution by Class on the Titanic\", x = \"Ticket Class\", y = \"Age(Yrs)\", subtitle = \"The median age of male and female survivors in 1st class was the same(36 yrs)\\nThe females in 2nd class were 1.5 times older than the males\\nThe males in 3rd class were older than the females by 2yrs\", caption = \"Author: etoma.egot\") + theme_tomski() + #using my own custom theme theme(plot.subtitle = element_text(colour = \"#1380A1\", size=18))+ facet_wrap(.~sex)#Calculating Mean and median age by Class and Gender for adultstitanic.df %>% filter(survived ==1)%>% group_by(pclass, sex)%>% summarise( n = n(), #count of passengers Average.age = mean(age, na.rm = TRUE), Median.age = median(age, na.rm = TRUE) )" }, { "code": null, "e": 10747, "s": 10724, "text": "Results Interpretation" }, { "code": null, "e": 10861, "s": 10747, "text": "FEMALE- The median age was 36 yrs (normally distributed),28yrs (negatively skewed) and 22 yrs (positively skewed)" }, { "code": null, "e": 10970, "s": 10861, "text": "MALE- The median age was 36 yrs (positively skewed),19yrs (negatively skewed) and 25 yrs (negatively skewed)" }, { "code": null, "e": 11182, "s": 10970, "text": "#Summary:- The median age of male and female survivors in 1st class was the same(36 yrs)- The females in 2nd class were 1.5 times older than the males - The males in 3rd class were older than the females by 2yrs" }, { "code": null, "e": 11348, "s": 11182, "text": "Finally, for the last question, Following that the Titanic was the most expensive ship over a century ago, how does the fare value compare across all ticket classes?" }, { "code": null, "e": 11466, "s": 11348, "text": "1st class ticket costs about 3 times a 2nd class ticket and 2nd class ticket was worth about twice that of 3rd class." }, { "code": null, "e": 12851, "s": 11466, "text": "#Prepare Data, remove outliers in faretitanic.df %>% filter(fare < 300)%>% ggplot(mapping = aes(x = pclass, y = fare)) + #geom_point(colour = \"#1380A1\", size = 1) + #geom_jitter(aes(colour = survived))+ geom_boxplot(colour = \"#1380A1\", outlier.colour = NA)+ labs(title = \"Fare Value by Class\", x = \"Ticket Class\", y = \"Ticket Fare (£)\", subtitle = \"1st class ticket was worth 3 times a 2nd class ticket\\nand 2nd class ticket was worth almost twice that of 3rd class\", caption = \"Author: etoma.egot\") + theme_tomski()+ #using my own custom theme theme(plot.subtitle = element_text(colour = \"#1380A1\",size=18))+ coord_cartesian(ylim = c(0,125))+ coord_flip()#Calculating Mean and Median Fare by Classtitanic.df %>% filter(fare < 300)%>% group_by(pclass)%>% summarise( Average.fares = mean(fare, na.rm = TRUE), Median.fare = median(fare, na.rm = TRUE) )#Calculating Mean and Median Fare by Class for childrentitanic.df %>% filter(fare < 300, age <= 12)%>% group_by(pclass)%>% summarise( n = n(), Average.fares = mean(fare, na.rm = TRUE), Median.fare = median(fare, na.rm = TRUE) )#Calculating Mean and Median Fare by Class for adultstitanic.df %>% filter(fare < 300, age >= 12)%>% group_by(pclass)%>% summarise( n = n(), Average.fare = mean(fare, na.rm = TRUE), Median.fare = median(fare, na.rm = TRUE) )" }, { "code": null, "e": 12874, "s": 12851, "text": "Results Interpretation" }, { "code": null, "e": 12976, "s": 12874, "text": "The box plot confirms that the ticket fare is proportional to the Ticket class.Pretty much intuitive." }, { "code": null, "e": 13204, "s": 12976, "text": "The distribution is skewed to the right .The median fares for 1st, 2nd and 3rd class is 59.4 £, 15 £ and 8.05 £. The mean fares for 1st, 2nd and 3rd class is 82.2 £, 21.2 £ and 13.3 £.(mean fares are greater than median fares)." }, { "code": null, "e": 13401, "s": 13204, "text": "Hence,a better measure of the center for this distribution is the median. Thus,1st class ticket costs about 3 times a 2nd class ticket and 2nd class ticket was worth about twice that of 3rd class." }, { "code": null, "e": 13499, "s": 13401, "text": "The average and median fare for children is higher when compared to that of adults in same class." }, { "code": null, "e": 14011, "s": 13499, "text": "Note: For a symmetrical distribution, the mean is in the middle. Hence, Mean is an appropriate measure to use for comparisons. But if a distribution is skewed, then the mean is usually not in the middle. Hence, median is an appropriate measure for comparisonsI am quite thrilled at my first write-up on TDS, nonetheless, if you have done similar analysis, i still need to clarify if Children really paid more than some adults across different age groups as my visualization bubble chart results seem to suggest." } ]
StringBuffer insert() in Java
06 Dec, 2018 The StringBuffer.insert() method inserts the string representation of given data type at given position in a StringBuffer. Syntax: str.insert(int position, char x); str.insert(int position, boolean x); str.insert(int position, char[] x); str.insert(int position, float x); str.insert(int position, double x); str.insert(int position, long x); str.insert(int position, int x); position is the index in string where we need to insert. Return: This method returns a reference to this object. Exception: The position argument must be greater than or equal to 0, and less than or equal to the length of this string. Boolean Input // Java program to demonstrate StringBuffer insert// for boolean input. import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // insert boolean value at offset 8 str.insert(8, true); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); }} string = geeks for geeks After insertion = geeks fotruer geeks Character Input // Java program to demonstrate StringBuffer insert// for char input. import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // insert boolean value at offset 8 str.insert(8, 'p'); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); }} string = geeks for geeks After insertion = geeks fopr geeks Character Array Input // Java program to demonstrate StringBuffer insert// for char array input. import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // character array to be inserted char cArr[] = { 'p', 'a', 'w', 'a', 'n' }; // insert character array at offset 9 str.insert(8, cArr); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); }} string = geeks for geeks After insertion = geeks fopawanr geeks Float Input // Java program to demonstrate StringBuffer insert// for float input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // insert float value at offset 3 str.insert(8, 41.35f); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); } } string = geeks for geeks After insertion = geeks fo41.35r geeks Double Input // Java program to demonstrate StringBuffer insert// for double input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // insert float value at offset 3 str.insert(8, 41.35d); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); } } string = geeks for geeks After insertion = geeks fo41.35r geeks Long Input // Java program to demonstrate StringBuffer insert// for Long input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // insert float value at offset 3 str.insert(8, 546986L); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); } } string = geeks for geeks After insertion = geeks fo546986r geeks Int Input // Java program to demonstrate StringBuffer insert// for Int input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer("geeks for geeks"); System.out.println("string = " + str); // insert float value at offset 8 int x = 10; str.insert(8, x); // prints stringbuffer after insertion System.out.print("After insertion = "); System.out.println(str.toString()); } } string = geeks for geeks After insertion = geeks fo10r geeks Java-Functions Java-lang package java-StringBuffer Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2018" }, { "code": null, "e": 175, "s": 52, "text": "The StringBuffer.insert() method inserts the string representation of given data type at given position in a StringBuffer." }, { "code": null, "e": 183, "s": 175, "text": "Syntax:" }, { "code": null, "e": 497, "s": 183, "text": " str.insert(int position, char x);\n str.insert(int position, boolean x);\n str.insert(int position, char[] x);\n str.insert(int position, float x);\n str.insert(int position, double x);\n str.insert(int position, long x);\n str.insert(int position, int x);\n\nposition is the index in string where\nwe need to insert.\n" }, { "code": null, "e": 505, "s": 497, "text": "Return:" }, { "code": null, "e": 553, "s": 505, "text": "This method returns a reference to this object." }, { "code": null, "e": 564, "s": 553, "text": "Exception:" }, { "code": null, "e": 677, "s": 564, "text": "The position argument must be greater\nthan or equal to 0, and less than \nor equal to the length of this string.\n" }, { "code": null, "e": 691, "s": 677, "text": "Boolean Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for boolean input. import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // insert boolean value at offset 8 str.insert(8, true); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); }}", "e": 1190, "s": 691, "text": null }, { "code": null, "e": 1254, "s": 1190, "text": "string = geeks for geeks\nAfter insertion = geeks fotruer geeks\n" }, { "code": null, "e": 1270, "s": 1254, "text": "Character Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for char input. import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // insert boolean value at offset 8 str.insert(8, 'p'); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); }}", "e": 1763, "s": 1270, "text": null }, { "code": null, "e": 1824, "s": 1763, "text": "string = geeks for geeks\nAfter insertion = geeks fopr geeks\n" }, { "code": null, "e": 1846, "s": 1824, "text": "Character Array Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for char array input. import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // character array to be inserted char cArr[] = { 'p', 'a', 'w', 'a', 'n' }; // insert character array at offset 9 str.insert(8, cArr); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); }}", "e": 2445, "s": 1846, "text": null }, { "code": null, "e": 2510, "s": 2445, "text": "string = geeks for geeks\nAfter insertion = geeks fopawanr geeks\n" }, { "code": null, "e": 2522, "s": 2510, "text": "Float Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for float input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // insert float value at offset 3 str.insert(8, 41.35f); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); } }", "e": 3036, "s": 2522, "text": null }, { "code": null, "e": 3101, "s": 3036, "text": "string = geeks for geeks\nAfter insertion = geeks fo41.35r geeks\n" }, { "code": null, "e": 3114, "s": 3101, "text": "Double Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for double input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // insert float value at offset 3 str.insert(8, 41.35d); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); } }", "e": 3629, "s": 3114, "text": null }, { "code": null, "e": 3694, "s": 3629, "text": "string = geeks for geeks\nAfter insertion = geeks fo41.35r geeks\n" }, { "code": null, "e": 3705, "s": 3694, "text": "Long Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for Long input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // insert float value at offset 3 str.insert(8, 546986L); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); } }", "e": 4208, "s": 3705, "text": null }, { "code": null, "e": 4274, "s": 4208, "text": "string = geeks for geeks\nAfter insertion = geeks fo546986r geeks\n" }, { "code": null, "e": 4284, "s": 4274, "text": "Int Input" }, { "code": "// Java program to demonstrate StringBuffer insert// for Int input.import java.lang.*; public class GFG { public static void main(String[] args) { StringBuffer str = new StringBuffer(\"geeks for geeks\"); System.out.println(\"string = \" + str); // insert float value at offset 8 int x = 10; str.insert(8, x); // prints stringbuffer after insertion System.out.print(\"After insertion = \"); System.out.println(str.toString()); } }", "e": 4811, "s": 4284, "text": null }, { "code": null, "e": 4873, "s": 4811, "text": "string = geeks for geeks\nAfter insertion = geeks fo10r geeks\n" }, { "code": null, "e": 4888, "s": 4873, "text": "Java-Functions" }, { "code": null, "e": 4906, "s": 4888, "text": "Java-lang package" }, { "code": null, "e": 4924, "s": 4906, "text": "java-StringBuffer" }, { "code": null, "e": 4937, "s": 4924, "text": "Java-Strings" }, { "code": null, "e": 4942, "s": 4937, "text": "Java" }, { "code": null, "e": 4955, "s": 4942, "text": "Java-Strings" }, { "code": null, "e": 4960, "s": 4955, "text": "Java" } ]
Python – Smallest Length String
31 Dec, 2019 Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loopThis is the brute method in which we perform this task. In this, we run a loop to keep a memory of smallest string length and return the string which has min length in list. # Python3 code to demonstrate working of # Smallest Length String# using loop # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Smallest Length String # using loop min_len = 99999for ele in test_list: if len(ele) < min_len: min_len = len(ele) res = ele # printing result print("Minimum length string is : " + res) The original list : ['gfg', 'is', 'best', 'for', 'geeks'] Minimum length string is : is Method #2 : Using min() + keyThis method can also be used to solve this problem. In this, we use inbuilt min() with “len” as key argument to extract the string with the minimum length. # Python3 code to demonstrate working of # Smallest Length String# using min() + key # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Smallest Length String# using min() + key res = min(test_list, key = len) # printing result print("Minimum length string is : " + res) The original list : ['gfg', 'is', 'best', 'for', 'geeks'] Minimum length string is : is Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Dec, 2019" }, { "code": null, "e": 286, "s": 28, "text": "Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 482, "s": 286, "text": "Method #1 : Using loopThis is the brute method in which we perform this task. In this, we run a loop to keep a memory of smallest string length and return the string which has min length in list." }, { "code": "# Python3 code to demonstrate working of # Smallest Length String# using loop # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print(\"The original list : \" + str(test_list)) # Smallest Length String # using loop min_len = 99999for ele in test_list: if len(ele) < min_len: min_len = len(ele) res = ele # printing result print(\"Minimum length string is : \" + res) ", "e": 917, "s": 482, "text": null }, { "code": null, "e": 1006, "s": 917, "text": "The original list : ['gfg', 'is', 'best', 'for', 'geeks']\nMinimum length string is : is\n" }, { "code": null, "e": 1193, "s": 1008, "text": "Method #2 : Using min() + keyThis method can also be used to solve this problem. In this, we use inbuilt min() with “len” as key argument to extract the string with the minimum length." }, { "code": "# Python3 code to demonstrate working of # Smallest Length String# using min() + key # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print(\"The original list : \" + str(test_list)) # Smallest Length String# using min() + key res = min(test_list, key = len) # printing result print(\"Minimum length string is : \" + res) ", "e": 1564, "s": 1193, "text": null }, { "code": null, "e": 1653, "s": 1564, "text": "The original list : ['gfg', 'is', 'best', 'for', 'geeks']\nMinimum length string is : is\n" }, { "code": null, "e": 1674, "s": 1653, "text": "Python list-programs" }, { "code": null, "e": 1697, "s": 1674, "text": "Python string-programs" }, { "code": null, "e": 1704, "s": 1697, "text": "Python" }, { "code": null, "e": 1720, "s": 1704, "text": "Python Programs" } ]
PL/SQL Introduction
03 Apr, 2018 PL/SQL is a block structured language that enables developers to combine the power of SQL with procedural statements.All the statements of a block are passed to oracle engine all at once which increases processing speed and decreases the traffic. Disadvantages of SQL: SQL doesn’t provide the programmers with a technique of condition checking, looping and branching. SQL statements are passed to Oracle engine one at a time which increases traffic and decreases speed. SQL has no facility of error checking during manipulation of data. Features of PL/SQL: PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages.PL/SQL can execute a number of queries in one block using single command.One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications.PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block.Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational.PL/SQL Offers extensive error checking. PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages. PL/SQL can execute a number of queries in one block using single command. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block. Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational. PL/SQL Offers extensive error checking. Differences between SQL and PL/SQL: Structure of PL/SQL Block: PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other. Typically, each block performs a logical action in the program. A block has the following structure: DECLARE declaration statements; BEGIN executable statements EXCEPTIONS exception handling statements END; Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be declared which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part of the code is optional. Execution section starts with BEGIN and ends with END keyword.This is a mandatory section and here the program logic is written to perform any task like loops and conditional statements. It supports all DML commands, DDL commands and SQL*PLUS built-in functions as well. Exception section starts with EXCEPTION keyword.This section is optional which contains statements that are executed when a run-time error occurs. Any exceptions can be handled in this section. There are several PL/SQL identifiers such as variables, constants, procedures, cursors, triggers etc. Variables:Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well.Syntax for declaration of variables:variable_name datatype [NOT NULL := value ]; Example to show how to declare variables in PL/SQL :SQL> SET SERVEROUTPUT ON; SQL> DECLARE var1 INTEGER; var2 REAL; var3 varchar2(20) ; BEGIN null;END;/Output:PL/SQL procedure successfully completed. Explanation:SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc.PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully.Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.1.1) INITIALISING VARIABLES:The variables can also be initialised just like in other programming languages. Let us see an example for the same:SQL> SET SERVEROUTPUT ON;SQL> DECLARE var1 INTEGER := 2 ; var3 varchar2(20) := 'I Love GeeksForGeeks' ; BEGIN null; END; /Output:PL/SQL procedure successfully completed. Explanation:Assignment operator (:=) : It is used to assign a value to a variable.Displaying Output:The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.Let us see an example to see how to display a message using PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks PL/SQL procedure successfully completed. Explanation:dbms_output.put_line : This command is used to direct the PL/SQL output to a screen.Using Comments:Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL :Single Line Comment: To create a single line comment , the symbol – – is used.Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.Example to show how to create comments in PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE -- I am a comment, so i will be ignored. var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks PL/SQL procedure successfully completed. Taking input from user:Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL:SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a number := &a; -- taking input for variable b b varchar2(30) := &b; BEGIN null; END; /Output:Enter value for a: 24 old 2: a number := &a; new 2: a number := 24; Enter value for b: 'GeeksForGeeks' old 3: b varchar2(30) := &b; new 3: b varchar2(30) := 'GeeksForGeeks'; PL/SQL procedure successfully completed. (***) Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.--PL/SQL code to print sum of two numbers taken from the user.SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a integer := &a ; -- taking input for variable b b integer := &b ; c integer ; BEGIN c := a + b ; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c); END; /Enter value for a: 2 Enter value for b: 3 Sum of 2 and 3 is = 5 PL/SQL procedure successfully completed. Variables:Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well.Syntax for declaration of variables:variable_name datatype [NOT NULL := value ]; Example to show how to declare variables in PL/SQL :SQL> SET SERVEROUTPUT ON; SQL> DECLARE var1 INTEGER; var2 REAL; var3 varchar2(20) ; BEGIN null;END;/Output:PL/SQL procedure successfully completed. Explanation:SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc.PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully.Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.1.1) INITIALISING VARIABLES:The variables can also be initialised just like in other programming languages. Let us see an example for the same:SQL> SET SERVEROUTPUT ON;SQL> DECLARE var1 INTEGER := 2 ; var3 varchar2(20) := 'I Love GeeksForGeeks' ; BEGIN null; END; /Output:PL/SQL procedure successfully completed. Explanation:Assignment operator (:=) : It is used to assign a value to a variable. Variables:Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well. Syntax for declaration of variables: variable_name datatype [NOT NULL := value ]; Example to show how to declare variables in PL/SQL : SQL> SET SERVEROUTPUT ON; SQL> DECLARE var1 INTEGER; var2 REAL; var3 varchar2(20) ; BEGIN null;END;/ Output: PL/SQL procedure successfully completed. Explanation: SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output. var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc. PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully. Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block. 1.1) INITIALISING VARIABLES:The variables can also be initialised just like in other programming languages. Let us see an example for the same: SQL> SET SERVEROUTPUT ON;SQL> DECLARE var1 INTEGER := 2 ; var3 varchar2(20) := 'I Love GeeksForGeeks' ; BEGIN null; END; / Output: PL/SQL procedure successfully completed. Explanation: Assignment operator (:=) : It is used to assign a value to a variable. Displaying Output:The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.Let us see an example to see how to display a message using PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks PL/SQL procedure successfully completed. Explanation:dbms_output.put_line : This command is used to direct the PL/SQL output to a screen. Displaying Output:The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers. Let us see an example to see how to display a message using PL/SQL : SQL> SET SERVEROUTPUT ON;SQL> DECLARE var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; / Output: I love GeeksForGeeks PL/SQL procedure successfully completed. Explanation: dbms_output.put_line : This command is used to direct the PL/SQL output to a screen. Using Comments:Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL :Single Line Comment: To create a single line comment , the symbol – – is used.Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.Example to show how to create comments in PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE -- I am a comment, so i will be ignored. var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks PL/SQL procedure successfully completed. Using Comments:Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL : Single Line Comment: To create a single line comment , the symbol – – is used. Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used. Example to show how to create comments in PL/SQL : SQL> SET SERVEROUTPUT ON;SQL> DECLARE -- I am a comment, so i will be ignored. var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; / Output: I love GeeksForGeeks PL/SQL procedure successfully completed. Taking input from user:Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL:SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a number := &a; -- taking input for variable b b varchar2(30) := &b; BEGIN null; END; /Output:Enter value for a: 24 old 2: a number := &a; new 2: a number := 24; Enter value for b: 'GeeksForGeeks' old 3: b varchar2(30) := &b; new 3: b varchar2(30) := 'GeeksForGeeks'; PL/SQL procedure successfully completed. Taking input from user:Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL: SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a number := &a; -- taking input for variable b b varchar2(30) := &b; BEGIN null; END; / Output: Enter value for a: 24 old 2: a number := &a; new 2: a number := 24; Enter value for b: 'GeeksForGeeks' old 3: b varchar2(30) := &b; new 3: b varchar2(30) := 'GeeksForGeeks'; PL/SQL procedure successfully completed. (***) Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.--PL/SQL code to print sum of two numbers taken from the user.SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a integer := &a ; -- taking input for variable b b integer := &b ; c integer ; BEGIN c := a + b ; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c); END; /Enter value for a: 2 Enter value for b: 3 Sum of 2 and 3 is = 5 PL/SQL procedure successfully completed. --PL/SQL code to print sum of two numbers taken from the user.SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a integer := &a ; -- taking input for variable b b integer := &b ; c integer ; BEGIN c := a + b ; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c); END; / Enter value for a: 2 Enter value for b: 3 Sum of 2 and 3 is = 5 PL/SQL procedure successfully completed. PL/SQL Execution Environment: The PL/SQL engine resides in the Oracle engine.The Oracle engine can process not only single SQL statement but also block of many statements.The call to Oracle engine needs to be made only once to execute any number of SQL statements if these SQL statements are bundled inside a PL/SQL block. SQL-PL/SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Apr, 2018" }, { "code": null, "e": 299, "s": 52, "text": "PL/SQL is a block structured language that enables developers to combine the power of SQL with procedural statements.All the statements of a block are passed to oracle engine all at once which increases processing speed and decreases the traffic." }, { "code": null, "e": 321, "s": 299, "text": "Disadvantages of SQL:" }, { "code": null, "e": 420, "s": 321, "text": "SQL doesn’t provide the programmers with a technique of condition checking, looping and branching." }, { "code": null, "e": 522, "s": 420, "text": "SQL statements are passed to Oracle engine one at a time which increases traffic and decreases speed." }, { "code": null, "e": 589, "s": 522, "text": "SQL has no facility of error checking during manipulation of data." }, { "code": null, "e": 609, "s": 589, "text": "Features of PL/SQL:" }, { "code": null, "e": 1263, "s": 609, "text": "PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages.PL/SQL can execute a number of queries in one block using single command.One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications.PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block.Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational.PL/SQL Offers extensive error checking." }, { "code": null, "e": 1429, "s": 1263, "text": "PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages." }, { "code": null, "e": 1503, "s": 1429, "text": "PL/SQL can execute a number of queries in one block using single command." }, { "code": null, "e": 1654, "s": 1503, "text": "One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications." }, { "code": null, "e": 1768, "s": 1654, "text": "PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block." }, { "code": null, "e": 1882, "s": 1768, "text": "Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational." }, { "code": null, "e": 1922, "s": 1882, "text": "PL/SQL Offers extensive error checking." }, { "code": null, "e": 1958, "s": 1922, "text": "Differences between SQL and PL/SQL:" }, { "code": null, "e": 1985, "s": 1958, "text": "Structure of PL/SQL Block:" }, { "code": null, "e": 2242, "s": 1985, "text": "PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other." }, { "code": null, "e": 2343, "s": 2242, "text": "Typically, each block performs a logical action in the program. A block has the following structure:" }, { "code": null, "e": 2465, "s": 2343, "text": "DECLARE\n declaration statements;\n\nBEGIN\n executable statements\n\nEXCEPTIONS\n exception handling statements\n\nEND;\n" }, { "code": null, "e": 2697, "s": 2465, "text": "Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be declared which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part of the code is optional." }, { "code": null, "e": 2968, "s": 2697, "text": "Execution section starts with BEGIN and ends with END keyword.This is a mandatory section and here the program logic is written to perform any task like loops and conditional statements. It supports all DML commands, DDL commands and SQL*PLUS built-in functions as well." }, { "code": null, "e": 3162, "s": 2968, "text": "Exception section starts with EXCEPTION keyword.This section is optional which contains statements that are executed when a run-time error occurs. Any exceptions can be handled in this section." }, { "code": null, "e": 3264, "s": 3162, "text": "There are several PL/SQL identifiers such as variables, constants, procedures, cursors, triggers etc." }, { "code": null, "e": 7170, "s": 3264, "text": "Variables:Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well.Syntax for declaration of variables:variable_name datatype [NOT NULL := value ];\nExample to show how to declare variables in PL/SQL :SQL> SET SERVEROUTPUT ON; SQL> DECLARE var1 INTEGER; var2 REAL; var3 varchar2(20) ; BEGIN null;END;/Output:PL/SQL procedure successfully completed.\nExplanation:SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc.PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully.Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.1.1) INITIALISING VARIABLES:The variables can also be initialised just like in other programming languages. Let us see an example for the same:SQL> SET SERVEROUTPUT ON;SQL> DECLARE var1 INTEGER := 2 ; var3 varchar2(20) := 'I Love GeeksForGeeks' ; BEGIN null; END; /Output:PL/SQL procedure successfully completed.\nExplanation:Assignment operator (:=) : It is used to assign a value to a variable.Displaying Output:The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.Let us see an example to see how to display a message using PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks\n\nPL/SQL procedure successfully completed.\nExplanation:dbms_output.put_line : This command is used to direct the PL/SQL output to a screen.Using Comments:Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL :Single Line Comment: To create a single line comment , the symbol – – is used.Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.Example to show how to create comments in PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE -- I am a comment, so i will be ignored. var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks\n\nPL/SQL procedure successfully completed.\nTaking input from user:Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL:SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a number := &a; -- taking input for variable b b varchar2(30) := &b; BEGIN null; END; /Output:Enter value for a: 24\nold 2: a number := &a;\nnew 2: a number := 24;\nEnter value for b: 'GeeksForGeeks'\nold 3: b varchar2(30) := &b;\nnew 3: b varchar2(30) := 'GeeksForGeeks';\n\nPL/SQL procedure successfully completed.\n(***) Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.--PL/SQL code to print sum of two numbers taken from the user.SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a integer := &a ; -- taking input for variable b b integer := &b ; c integer ; BEGIN c := a + b ; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c); END; /Enter value for a: 2\nEnter value for b: 3\n\nSum of 2 and 3 is = 5\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 8589, "s": 7170, "text": "Variables:Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well.Syntax for declaration of variables:variable_name datatype [NOT NULL := value ];\nExample to show how to declare variables in PL/SQL :SQL> SET SERVEROUTPUT ON; SQL> DECLARE var1 INTEGER; var2 REAL; var3 varchar2(20) ; BEGIN null;END;/Output:PL/SQL procedure successfully completed.\nExplanation:SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc.PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully.Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.1.1) INITIALISING VARIABLES:The variables can also be initialised just like in other programming languages. Let us see an example for the same:SQL> SET SERVEROUTPUT ON;SQL> DECLARE var1 INTEGER := 2 ; var3 varchar2(20) := 'I Love GeeksForGeeks' ; BEGIN null; END; /Output:PL/SQL procedure successfully completed.\nExplanation:Assignment operator (:=) : It is used to assign a value to a variable." }, { "code": null, "e": 8749, "s": 8589, "text": "Variables:Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well." }, { "code": null, "e": 8786, "s": 8749, "text": "Syntax for declaration of variables:" }, { "code": null, "e": 8832, "s": 8786, "text": "variable_name datatype [NOT NULL := value ];\n" }, { "code": null, "e": 8885, "s": 8832, "text": "Example to show how to declare variables in PL/SQL :" }, { "code": "SQL> SET SERVEROUTPUT ON; SQL> DECLARE var1 INTEGER; var2 REAL; var3 varchar2(20) ; BEGIN null;END;/", "e": 9000, "s": 8885, "text": null }, { "code": null, "e": 9008, "s": 9000, "text": "Output:" }, { "code": null, "e": 9050, "s": 9008, "text": "PL/SQL procedure successfully completed.\n" }, { "code": null, "e": 9063, "s": 9050, "text": "Explanation:" }, { "code": null, "e": 9142, "s": 9063, "text": "SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output." }, { "code": null, "e": 9417, "s": 9142, "text": "var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc." }, { "code": null, "e": 9528, "s": 9417, "text": "PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully." }, { "code": null, "e": 9605, "s": 9528, "text": "Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block." }, { "code": null, "e": 9749, "s": 9605, "text": "1.1) INITIALISING VARIABLES:The variables can also be initialised just like in other programming languages. Let us see an example for the same:" }, { "code": "SQL> SET SERVEROUTPUT ON;SQL> DECLARE var1 INTEGER := 2 ; var3 varchar2(20) := 'I Love GeeksForGeeks' ; BEGIN null; END; /", "e": 9891, "s": 9749, "text": null }, { "code": null, "e": 9899, "s": 9891, "text": "Output:" }, { "code": null, "e": 9941, "s": 9899, "text": "PL/SQL procedure successfully completed.\n" }, { "code": null, "e": 9954, "s": 9941, "text": "Explanation:" }, { "code": null, "e": 10025, "s": 9954, "text": "Assignment operator (:=) : It is used to assign a value to a variable." }, { "code": null, "e": 10628, "s": 10025, "text": "Displaying Output:The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.Let us see an example to see how to display a message using PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks\n\nPL/SQL procedure successfully completed.\nExplanation:dbms_output.put_line : This command is used to direct the PL/SQL output to a screen." }, { "code": null, "e": 10860, "s": 10628, "text": "Displaying Output:The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers." }, { "code": null, "e": 10929, "s": 10860, "text": "Let us see an example to see how to display a message using PL/SQL :" }, { "code": "SQL> SET SERVEROUTPUT ON;SQL> DECLARE var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /", "e": 11067, "s": 10929, "text": null }, { "code": null, "e": 11075, "s": 11067, "text": "Output:" }, { "code": null, "e": 11139, "s": 11075, "text": "I love GeeksForGeeks\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 11152, "s": 11139, "text": "Explanation:" }, { "code": null, "e": 11237, "s": 11152, "text": "dbms_output.put_line : This command is used to direct the PL/SQL output to a screen." }, { "code": null, "e": 11914, "s": 11237, "text": "Using Comments:Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL :Single Line Comment: To create a single line comment , the symbol – – is used.Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.Example to show how to create comments in PL/SQL :SQL> SET SERVEROUTPUT ON;SQL> DECLARE -- I am a comment, so i will be ignored. var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /Output:I love GeeksForGeeks\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 12110, "s": 11914, "text": "Using Comments:Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL :" }, { "code": null, "e": 12189, "s": 12110, "text": "Single Line Comment: To create a single line comment , the symbol – – is used." }, { "code": null, "e": 12288, "s": 12189, "text": "Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used." }, { "code": null, "e": 12339, "s": 12288, "text": "Example to show how to create comments in PL/SQL :" }, { "code": "SQL> SET SERVEROUTPUT ON;SQL> DECLARE -- I am a comment, so i will be ignored. var varchar2(40) := 'I love GeeksForGeeks' ; BEGIN dbms_output.put_line(var); END; /", "e": 12525, "s": 12339, "text": null }, { "code": null, "e": 12533, "s": 12525, "text": "Output:" }, { "code": null, "e": 12597, "s": 12533, "text": "I love GeeksForGeeks\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 13251, "s": 12597, "text": "Taking input from user:Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL:SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a number := &a; -- taking input for variable b b varchar2(30) := &b; BEGIN null; END; /Output:Enter value for a: 24\nold 2: a number := &a;\nnew 2: a number := 24;\nEnter value for b: 'GeeksForGeeks'\nold 3: b varchar2(30) := &b;\nnew 3: b varchar2(30) := 'GeeksForGeeks';\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 13462, "s": 13251, "text": "Taking input from user:Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL:" }, { "code": "SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a number := &a; -- taking input for variable b b varchar2(30) := &b; BEGIN null; END; /", "e": 13675, "s": 13462, "text": null }, { "code": null, "e": 13683, "s": 13675, "text": "Output:" }, { "code": null, "e": 13908, "s": 13683, "text": "Enter value for a: 24\nold 2: a number := &a;\nnew 2: a number := 24;\nEnter value for b: 'GeeksForGeeks'\nold 3: b varchar2(30) := &b;\nnew 3: b varchar2(30) := 'GeeksForGeeks';\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 14465, "s": 13908, "text": "(***) Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.--PL/SQL code to print sum of two numbers taken from the user.SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a integer := &a ; -- taking input for variable b b integer := &b ; c integer ; BEGIN c := a + b ; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c); END; /Enter value for a: 2\nEnter value for b: 3\n\nSum of 2 and 3 is = 5\n\nPL/SQL procedure successfully completed.\n" }, { "code": "--PL/SQL code to print sum of two numbers taken from the user.SQL> SET SERVEROUTPUT ON; SQL> DECLARE -- taking input for variable a a integer := &a ; -- taking input for variable b b integer := &b ; c integer ; BEGIN c := a + b ; dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c); END; /", "e": 14815, "s": 14465, "text": null }, { "code": null, "e": 14923, "s": 14815, "text": "Enter value for a: 2\nEnter value for b: 3\n\nSum of 2 and 3 is = 5\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 14953, "s": 14923, "text": "PL/SQL Execution Environment:" }, { "code": null, "e": 15246, "s": 14953, "text": "The PL/SQL engine resides in the Oracle engine.The Oracle engine can process not only single SQL statement but also block of many statements.The call to Oracle engine needs to be made only once to execute any number of SQL statements if these SQL statements are bundled inside a PL/SQL block." }, { "code": null, "e": 15257, "s": 15246, "text": "SQL-PL/SQL" }, { "code": null, "e": 15262, "s": 15257, "text": "DBMS" }, { "code": null, "e": 15266, "s": 15262, "text": "SQL" }, { "code": null, "e": 15271, "s": 15266, "text": "DBMS" }, { "code": null, "e": 15275, "s": 15271, "text": "SQL" } ]
Flexbox utilities in bootstrap with examples
28 Apr, 2022 The Flexible Box Layout Module in bootstrap is used for designing the flexible and responsive layout structure. It is used in Bootstrap 4. The d-flex class is used to create a simple flexbox container Syntax: <div class="d-flex p-2"></div> The d-inline-flex class is used to create an inline flexbox container Syntax: <div class="d-inline-flex p-2"></div> .d-flex and .d-inline-flex can be used for all breakpoints(sm, md, lg, xl) like .d-sm-flex, .d-sm-inline-flex, etc. Syntax: <div class="d-sm-flex p-2"></div> <div class="d-sm-inline-flex p-2"></div> Example 1: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Flex</h2> <div class="d-flex p-3 bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success ">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Inline Flex</h2> <div class="d-inline-flex p-3 bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success ">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Horizontal And Vertical Direction of Flexbox: The direction of flex items can be positioned in a flex container. To set a horizontal direction (the browser default) use .flex-row. Syntax: <div class="d-flex flex-row"></div> To start the horizontal direction from the opposite side use .flex-row-reverse. Syntax: <div class="d-flex flex-row-reverse"></div> To set a vertical direction use .flex-column. Syntax: <div class="d-flex flex-column"></div> To start the vertical direction from the opposite side use .flex-column-reverse. Syntax: <div class="d-flex flex-column-reverse"></div> Flex-direction can be used for all breakpoints(sm, md, lg, xl) like .flex-sm-row, flex-sm-row-reverse, etc. Syntax: <div class="d-flex flex-column-reverse"></div> <div class="d-flex flex-column"></div> Example 3: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Horizontal Direction Flex</h2> <br> <div class="d-flex flex-row bg-success mb-3 text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success ">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <br> <div class="d-flex flex-row-reverse bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Example 4: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Vertical Direction Flex</h2> <br> <div class="d-flex flex-column bg-success mb-3 text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success ">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <br> <div class="d-flex flex-column-reverse bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Justify Content: In order to change the alignment of flex items, one can use the .justify-content-* classes. * can be any one of them start (default), end, center, between, or around. Similarly justify-content can be used for all breakpoints(sm, md, lg, xl) like .justify-content-sm-start, .justify-content-sm-end, etc. Syntax: <div class="d-flex justify-content-start"></div> Example 5: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Justify Content</h2> <br> <div class="d-flex justify-content-start bg-success mb-3 text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success ">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <div class="d-flex justify-content-end bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <br> <div class="d-flex justify-content-center bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <br> <div class="d-flex justify-content-between bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <br> <div class="d-flex justify-content-around bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Filling of Widths of flex items: Flex items can be forced into equal widths by using the .flex-fill class. .flex-fill can be used for all breakpoints(sm, md, lg, xl) like .flex-sm-fill, etc. Syntax: <div class="p-2 flex-fill"></div> Example 6: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Fill / Equal Widths</h2> <p>Use .flex-fill on flex items to force them into equal widths:</p> <div class="d-flex bg-success mb-3 text-white"> <div class="p-2 flex-fill bg-success">Geeks 1</div> <div class="p-2 flex-fill bg-success">Geeks 2</div> <div class="p-2 flex-fill bg-success">Geeks 3</div> </div> <p>Example without .flex-fill:</p> <div class="d-flex bg-success mb-3 text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Order: .order classes are used for changing the visualization order of a flex item. Ordering is done on a number basis from 0 to 12. 0 has highest priority. .order can be used for all breakpoints(sm, md, lg, xl) like .order-sm-0 to .order-sm-12, etc. Syntax: <div class="p-2 order-4"></div> Example 7: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Order</h2> <div class="d-flex mb-3 text-white"> <div class="p-2 order-3 bg-success"> Geeks 1</div> <div class="p-2 order-2 bg-success"> Geeks 2</div> <div class="p-2 order-1 bg-success"> Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Automation of margins: .mr-auto used to push items to the right. .ml-auto used to push items to the left Syntax: <div class="p-2 mr-auto"></div> Example 8: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Auto Margins</h2> <div class="d-flex mb-3 bg-success text-white"> <div class="p-2 mr-auto bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 bg-success">Geeks 3</div> </div> <div class="d-flex mb-3 bg-success text-white"> <div class="p-2 bg-success">Geeks 1</div> <div class="p-2 bg-success">Geeks 2</div> <div class="p-2 ml-auto bg-success">Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Wrapping of flex item: .flex-nowrap (default), .flex-wrap and .flex-wrap-reverse are used for wrapping the flex items in a flex container. .flex-wrap can be used for all breakpoints(sm, md, lg, xl) like .flex-sm-nowrap, .flex-sm-wrap, etc. Syntax: <div class="p-2 border"></div> Example 9: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Wrap</h2> <p><code>.flex-wrap:</code></p> <div class="d-flex flex-wrap text-white bg-light"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> <div class="p-2 border bg-success">Geeks 4</div> <div class="p-2 border bg-success">Geeks 5</div> <div class="p-2 border bg-success">Geeks 6</div> <div class="p-2 border bg-success">Geeks 7</div> <div class="p-2 border bg-success">Geeks 8</div> <div class="p-2 border bg-success">Geeks 9</div> </div> <br> <p><code>.flex-wrap-reverse:</code></p> <div class="d-flex flex-wrap-reverse text-white bg-light"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> <div class="p-2 border bg-success">Geeks 4</div> <div class="p-2 border bg-success">Geeks 5</div> <div class="p-2 border bg-success">Geeks 6</div> <div class="p-2 border bg-success">Geeks 7</div> <div class="p-2 border bg-success">Geeks 8</div> <div class="p-2 border bg-success">Geeks 9</div> </div> <br> <p><code>.flex-nowrap:</code></p> <div class="d-flex flex-nowrap text-white bg-light"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> <div class="p-2 border bg-success">Geeks 4</div> <div class="p-2 border bg-success">Geeks 5</div> <div class="p-2 border bg-success">Geeks 6</div> <div class="p-2 border bg-success">Geeks 7</div> <div class="p-2 border bg-success">Geeks 8</div> <div class="p-2 border bg-success">Geeks 9</div> </div> <br> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Align Content: Basically, it is used for the vertical alignment of flex items. align-content can be implemented in various ways. .align-content-start .align-content-end .align-content-center .align-content-around .align-content-stretch .align-content-sm-start Similarly for sm, md, lg, xl Syntax: <div class="p-2 align-content-start"></div> Example 10: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Align Content</h2> <p><code>.align-content-start (default):</code></p> <div class="d-flex flex-wrap align-content-start bg-light" style="height:100px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> <div class="p-2 border bg-success">Geeks 4</div> <div class="p-2 border bg-success">Geeks 5</div> <div class="p-2 border bg-success">Geeks 6</div> <div class="p-2 border bg-success">Geeks 7</div> <div class="p-2 border bg-success">Geeks 8</div> <div class="p-2 border bg-success">Geeks 9</div> </div> <p><code>.align-content-around:</code></p> <div class="d-flex flex-wrap align-content-around bg-light" style="height:100px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> <div class="p-2 border bg-success">Geeks 4</div> <div class="p-2 border bg-success">Geeks 5</div> <div class="p-2 border bg-success">Geeks 6</div> <div class="p-2 border bg-success">Geeks 7</div> <div class="p-2 border bg-success">Geeks 8</div> <div class="p-2 border bg-success">Geeks 9</div> </div> <p><code>.align-content-stretch:</code></p> <div class="d-flex flex-wrap align-content-stretch bg-light" style="height:100px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> <div class="p-2 border bg-success">Geeks 4</div> <div class="p-2 border bg-success">Geeks 5</div> <div class="p-2 border bg-success">Geeks 6</div> <div class="p-2 border bg-success">Geeks 7</div> <div class="p-2 border bg-success">Geeks 8</div> <div class="p-2 border bg-success">Geeks 9</div> </div> <br> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Align items: Use the align-items class to change the alignment of flex items on the cross axis. align-items can be implemented in various ways. .align-items-start .align-items-end .align-items-center .align-items-baseline .align-items-stretch .align-items-sm-start Similarly for sm, md, lg, xl Syntax: <div class="p-2 align-items-start"></div> Example 11: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" items="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Align items</h2> <p><code>.align-items-start:</code></p> <div class="d-flex flex-wrap align-items-start bg-light" style="height:70px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> </div> <p><code>.align-items-end:</code></p> <div class="d-flex flex-wrap align-items-end bg-light" style="height:70px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> </div> <p><code>.align-items-center:</code></p> <div class="d-flex flex-wrap align-items-center bg-light" style="height:70px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> </div> <p><code>.align-items-baseline:</code></p> <div class="d-flex flex-wrap align-items-around bg-light" style="height:70px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> </div> <p><code>.align-items-stretch(default):</code></p> <div class="d-flex flex-wrap align-items-stretch bg-light" style="height:70px"> <div class="p-2 border bg-success">Geeks 1</div> <div class="p-2 border bg-success">Geeks 2</div> <div class="p-2 border bg-success">Geeks 3</div> </div> <br> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Align self: align-self class can be used to change the alignment on the cross axis. align-self can be implemented in various ways. .align-self-start .align-self-end .align-self-center .align-self-around .align-self-stretch .align-self-sm-start Similarly for sm, md, lg, xl Syntax: <div class="p-2 align-self-center"></div> Example 12: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" self="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Align self</h2> <p><code>.align-self-start:</code></p> <div class="d-flex bg-light" style="height:80px"> <div class="p-2 border bg-success"> Geeks 1</div> <div class="p-2 border align-self-start bg-success"> Geeks 2</div> <div class="p-2 border bg-success"> Geeks 3</div> </div> <p><code>.align-self-end:</code></p> <div class="d-flex bg-light" style="height:80px"> <div class="p-2 border bg-success"> Geeks 1</div> <div class="p-2 border align-self-end bg-success"> Geeks 2</div> <div class="p-2 border bg-success"> Geeks 3</div> </div> <p><code>.align-self-center:</code></p> <div class="d-flex bg-light" style="height:80px"> <div class="p-2 border bg-success"> Geeks 1</div> <div class="p-2 border align-self-center bg-success"> Geeks 2</div> <div class="p-2 border bg-success"> Geeks 3</div> </div> <p><code>.align-self-baseline:</code></p> <div class="d-flex bg-light" style="height:80px"> <div class="p-2 border bg-success"> Geeks 1</div> <div class="p-2 border align-self-baseline bg-success"> Geeks 2</div> <div class="p-2 border bg-success"> Geeks 3</div> </div> <p><code>.align-self-stretch(default):</code></p> <div class="d-flex bg-light" style="height:80px"> <div class="p-2 border bg-success"> Geeks 1</div> <div class="p-2 border align-self-stretch bg-success"> Geeks 2</div> <div class="p-2 border bg-success"> Geeks 3</div> </div> <br> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Growing and Shrinking of available space: .flex-grow-* is used to grow flex items to fill available space. .flex-shrink-* is used to shrink the flex item. flex-grow and flex-shrink can be implemented as follows. .flex-{grow|shrink}-0 .flex-{grow|shrink}-1 Similarly for sm, md, lg, xl Syntax: <div class="p-2 flex grow-1"></div> Example 13: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" self="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class="container mt-3"> <h2>Grow</h2> <p>Use <code>.flex-grow-1</code> on a Geeks to take up the rest of the space:</p> <div class="d-flex mb-3"> <div class="p-2 bg-success"> Geeks 1</div> <div class="p-2 bg-success"> Geeks 2</div> <div class="p-2 flex-grow-1 bg-success"> Geeks 3</div> </div> <p>Example without <code>.flex-grow-1</code>:</p> <div class="d-flex mb-3"> <div class="p-2 bg-success"> Geeks 1</div> <div class="p-2 bg-success"> Geeks 2</div> <div class="p-2 bg-success"> Geeks 3</div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"> </script></body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 sahilintern Bootstrap CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to set Bootstrap Timepicker using datetimepicker library ? How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2022" }, { "code": null, "e": 167, "s": 28, "text": "The Flexible Box Layout Module in bootstrap is used for designing the flexible and responsive layout structure. It is used in Bootstrap 4." }, { "code": null, "e": 230, "s": 167, "text": "The d-flex class is used to create a simple flexbox container " }, { "code": null, "e": 238, "s": 230, "text": "Syntax:" }, { "code": null, "e": 269, "s": 238, "text": "<div class=\"d-flex p-2\"></div>" }, { "code": null, "e": 340, "s": 269, "text": "The d-inline-flex class is used to create an inline flexbox container " }, { "code": null, "e": 348, "s": 340, "text": "Syntax:" }, { "code": null, "e": 386, "s": 348, "text": "<div class=\"d-inline-flex p-2\"></div>" }, { "code": null, "e": 503, "s": 386, "text": ".d-flex and .d-inline-flex can be used for all breakpoints(sm, md, lg, xl) like .d-sm-flex, .d-sm-inline-flex, etc. " }, { "code": null, "e": 511, "s": 503, "text": "Syntax:" }, { "code": null, "e": 586, "s": 511, "text": "<div class=\"d-sm-flex p-2\"></div>\n<div class=\"d-sm-inline-flex p-2\"></div>" }, { "code": null, "e": 597, "s": 586, "text": "Example 1:" }, { "code": null, "e": 602, "s": 597, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Flex</h2> <div class=\"d-flex p-3 bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success \">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 1529, "s": 602, "text": null }, { "code": null, "e": 1537, "s": 1529, "text": "Output:" }, { "code": null, "e": 1548, "s": 1537, "text": "Example 2:" }, { "code": null, "e": 1553, "s": 1548, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Inline Flex</h2> <div class=\"d-inline-flex p-3 bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success \">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 2494, "s": 1553, "text": null }, { "code": null, "e": 2502, "s": 2494, "text": "Output:" }, { "code": null, "e": 2548, "s": 2502, "text": "Horizontal And Vertical Direction of Flexbox:" }, { "code": null, "e": 2615, "s": 2548, "text": "The direction of flex items can be positioned in a flex container." }, { "code": null, "e": 2683, "s": 2615, "text": "To set a horizontal direction (the browser default) use .flex-row. " }, { "code": null, "e": 2691, "s": 2683, "text": "Syntax:" }, { "code": null, "e": 2727, "s": 2691, "text": "<div class=\"d-flex flex-row\"></div>" }, { "code": null, "e": 2808, "s": 2727, "text": "To start the horizontal direction from the opposite side use .flex-row-reverse. " }, { "code": null, "e": 2816, "s": 2808, "text": "Syntax:" }, { "code": null, "e": 2860, "s": 2816, "text": "<div class=\"d-flex flex-row-reverse\"></div>" }, { "code": null, "e": 2907, "s": 2860, "text": "To set a vertical direction use .flex-column. " }, { "code": null, "e": 2915, "s": 2907, "text": "Syntax:" }, { "code": null, "e": 2954, "s": 2915, "text": "<div class=\"d-flex flex-column\"></div>" }, { "code": null, "e": 3036, "s": 2954, "text": "To start the vertical direction from the opposite side use .flex-column-reverse. " }, { "code": null, "e": 3044, "s": 3036, "text": "Syntax:" }, { "code": null, "e": 3091, "s": 3044, "text": "<div class=\"d-flex flex-column-reverse\"></div>" }, { "code": null, "e": 3200, "s": 3091, "text": "Flex-direction can be used for all breakpoints(sm, md, lg, xl) like .flex-sm-row, flex-sm-row-reverse, etc. " }, { "code": null, "e": 3208, "s": 3200, "text": "Syntax:" }, { "code": null, "e": 3294, "s": 3208, "text": "<div class=\"d-flex flex-column-reverse\"></div>\n<div class=\"d-flex flex-column\"></div>" }, { "code": null, "e": 3305, "s": 3294, "text": "Example 3:" }, { "code": null, "e": 3310, "s": 3305, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Horizontal Direction Flex</h2> <br> <div class=\"d-flex flex-row bg-success mb-3 text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success \">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <br> <div class=\"d-flex flex-row-reverse bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 4532, "s": 3310, "text": null }, { "code": null, "e": 4540, "s": 4532, "text": "Output:" }, { "code": null, "e": 4551, "s": 4540, "text": "Example 4:" }, { "code": null, "e": 4556, "s": 4551, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Vertical Direction Flex</h2> <br> <div class=\"d-flex flex-column bg-success mb-3 text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success \">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <br> <div class=\"d-flex flex-column-reverse bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 5782, "s": 4556, "text": null }, { "code": null, "e": 5790, "s": 5782, "text": "Output:" }, { "code": null, "e": 5807, "s": 5790, "text": "Justify Content:" }, { "code": null, "e": 5975, "s": 5807, "text": "In order to change the alignment of flex items, one can use the .justify-content-* classes. * can be any one of them start (default), end, center, between, or around. " }, { "code": null, "e": 6111, "s": 5975, "text": "Similarly justify-content can be used for all breakpoints(sm, md, lg, xl) like .justify-content-sm-start, .justify-content-sm-end, etc." }, { "code": null, "e": 6119, "s": 6111, "text": "Syntax:" }, { "code": null, "e": 6168, "s": 6119, "text": "<div class=\"d-flex justify-content-start\"></div>" }, { "code": null, "e": 6179, "s": 6168, "text": "Example 5:" }, { "code": null, "e": 6184, "s": 6179, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Justify Content</h2> <br> <div class=\"d-flex justify-content-start bg-success mb-3 text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success \">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <div class=\"d-flex justify-content-end bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <br> <div class=\"d-flex justify-content-center bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <br> <div class=\"d-flex justify-content-between bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <br> <div class=\"d-flex justify-content-around bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 8266, "s": 6184, "text": null }, { "code": null, "e": 8274, "s": 8266, "text": "Output:" }, { "code": null, "e": 8307, "s": 8274, "text": "Filling of Widths of flex items:" }, { "code": null, "e": 8465, "s": 8307, "text": "Flex items can be forced into equal widths by using the .flex-fill class. .flex-fill can be used for all breakpoints(sm, md, lg, xl) like .flex-sm-fill, etc." }, { "code": null, "e": 8473, "s": 8465, "text": "Syntax:" }, { "code": null, "e": 8507, "s": 8473, "text": "<div class=\"p-2 flex-fill\"></div>" }, { "code": null, "e": 8518, "s": 8507, "text": "Example 6:" }, { "code": null, "e": 8523, "s": 8518, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Fill / Equal Widths</h2> <p>Use .flex-fill on flex items to force them into equal widths:</p> <div class=\"d-flex bg-success mb-3 text-white\"> <div class=\"p-2 flex-fill bg-success\">Geeks 1</div> <div class=\"p-2 flex-fill bg-success\">Geeks 2</div> <div class=\"p-2 flex-fill bg-success\">Geeks 3</div> </div> <p>Example without .flex-fill:</p> <div class=\"d-flex bg-success mb-3 text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 9856, "s": 8523, "text": null }, { "code": null, "e": 9864, "s": 9856, "text": "Output:" }, { "code": null, "e": 9871, "s": 9864, "text": "Order:" }, { "code": null, "e": 10115, "s": 9871, "text": ".order classes are used for changing the visualization order of a flex item. Ordering is done on a number basis from 0 to 12. 0 has highest priority. .order can be used for all breakpoints(sm, md, lg, xl) like .order-sm-0 to .order-sm-12, etc." }, { "code": null, "e": 10123, "s": 10115, "text": "Syntax:" }, { "code": null, "e": 10155, "s": 10123, "text": "<div class=\"p-2 order-4\"></div>" }, { "code": null, "e": 10166, "s": 10155, "text": "Example 7:" }, { "code": null, "e": 10171, "s": 10166, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Order</h2> <div class=\"d-flex mb-3 text-white\"> <div class=\"p-2 order-3 bg-success\"> Geeks 1</div> <div class=\"p-2 order-2 bg-success\"> Geeks 2</div> <div class=\"p-2 order-1 bg-success\"> Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 11161, "s": 10171, "text": null }, { "code": null, "e": 11169, "s": 11161, "text": "Output:" }, { "code": null, "e": 11192, "s": 11169, "text": "Automation of margins:" }, { "code": null, "e": 11234, "s": 11192, "text": ".mr-auto used to push items to the right." }, { "code": null, "e": 11274, "s": 11234, "text": ".ml-auto used to push items to the left" }, { "code": null, "e": 11282, "s": 11274, "text": "Syntax:" }, { "code": null, "e": 11314, "s": 11282, "text": "<div class=\"p-2 mr-auto\"></div>" }, { "code": null, "e": 11325, "s": 11314, "text": "Example 8:" }, { "code": null, "e": 11330, "s": 11325, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Auto Margins</h2> <div class=\"d-flex mb-3 bg-success text-white\"> <div class=\"p-2 mr-auto bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 bg-success\">Geeks 3</div> </div> <div class=\"d-flex mb-3 bg-success text-white\"> <div class=\"p-2 bg-success\">Geeks 1</div> <div class=\"p-2 bg-success\">Geeks 2</div> <div class=\"p-2 ml-auto bg-success\">Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 12518, "s": 11330, "text": null }, { "code": null, "e": 12526, "s": 12518, "text": "Output:" }, { "code": null, "e": 12549, "s": 12526, "text": "Wrapping of flex item:" }, { "code": null, "e": 12766, "s": 12549, "text": ".flex-nowrap (default), .flex-wrap and .flex-wrap-reverse are used for wrapping the flex items in a flex container. .flex-wrap can be used for all breakpoints(sm, md, lg, xl) like .flex-sm-nowrap, .flex-sm-wrap, etc." }, { "code": null, "e": 12774, "s": 12766, "text": "Syntax:" }, { "code": null, "e": 12805, "s": 12774, "text": "<div class=\"p-2 border\"></div>" }, { "code": null, "e": 12817, "s": 12805, "text": "Example 9: " }, { "code": null, "e": 12822, "s": 12817, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Wrap</h2> <p><code>.flex-wrap:</code></p> <div class=\"d-flex flex-wrap text-white bg-light\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> <div class=\"p-2 border bg-success\">Geeks 4</div> <div class=\"p-2 border bg-success\">Geeks 5</div> <div class=\"p-2 border bg-success\">Geeks 6</div> <div class=\"p-2 border bg-success\">Geeks 7</div> <div class=\"p-2 border bg-success\">Geeks 8</div> <div class=\"p-2 border bg-success\">Geeks 9</div> </div> <br> <p><code>.flex-wrap-reverse:</code></p> <div class=\"d-flex flex-wrap-reverse text-white bg-light\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> <div class=\"p-2 border bg-success\">Geeks 4</div> <div class=\"p-2 border bg-success\">Geeks 5</div> <div class=\"p-2 border bg-success\">Geeks 6</div> <div class=\"p-2 border bg-success\">Geeks 7</div> <div class=\"p-2 border bg-success\">Geeks 8</div> <div class=\"p-2 border bg-success\">Geeks 9</div> </div> <br> <p><code>.flex-nowrap:</code></p> <div class=\"d-flex flex-nowrap text-white bg-light\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> <div class=\"p-2 border bg-success\">Geeks 4</div> <div class=\"p-2 border bg-success\">Geeks 5</div> <div class=\"p-2 border bg-success\">Geeks 6</div> <div class=\"p-2 border bg-success\">Geeks 7</div> <div class=\"p-2 border bg-success\">Geeks 8</div> <div class=\"p-2 border bg-success\">Geeks 9</div> </div> <br> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 15536, "s": 12822, "text": null }, { "code": null, "e": 15544, "s": 15536, "text": "Output:" }, { "code": null, "e": 15559, "s": 15544, "text": "Align Content:" }, { "code": null, "e": 15674, "s": 15559, "text": "Basically, it is used for the vertical alignment of flex items. align-content can be implemented in various ways. " }, { "code": null, "e": 15696, "s": 15674, "text": ".align-content-start " }, { "code": null, "e": 15716, "s": 15696, "text": ".align-content-end " }, { "code": null, "e": 15738, "s": 15716, "text": ".align-content-center" }, { "code": null, "e": 15760, "s": 15738, "text": ".align-content-around" }, { "code": null, "e": 15783, "s": 15760, "text": ".align-content-stretch" }, { "code": null, "e": 15807, "s": 15783, "text": ".align-content-sm-start" }, { "code": null, "e": 15836, "s": 15807, "text": "Similarly for sm, md, lg, xl" }, { "code": null, "e": 15844, "s": 15836, "text": "Syntax:" }, { "code": null, "e": 15888, "s": 15844, "text": "<div class=\"p-2 align-content-start\"></div>" }, { "code": null, "e": 15900, "s": 15888, "text": "Example 10:" }, { "code": null, "e": 15905, "s": 15900, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Align Content</h2> <p><code>.align-content-start (default):</code></p> <div class=\"d-flex flex-wrap align-content-start bg-light\" style=\"height:100px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> <div class=\"p-2 border bg-success\">Geeks 4</div> <div class=\"p-2 border bg-success\">Geeks 5</div> <div class=\"p-2 border bg-success\">Geeks 6</div> <div class=\"p-2 border bg-success\">Geeks 7</div> <div class=\"p-2 border bg-success\">Geeks 8</div> <div class=\"p-2 border bg-success\">Geeks 9</div> </div> <p><code>.align-content-around:</code></p> <div class=\"d-flex flex-wrap align-content-around bg-light\" style=\"height:100px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> <div class=\"p-2 border bg-success\">Geeks 4</div> <div class=\"p-2 border bg-success\">Geeks 5</div> <div class=\"p-2 border bg-success\">Geeks 6</div> <div class=\"p-2 border bg-success\">Geeks 7</div> <div class=\"p-2 border bg-success\">Geeks 8</div> <div class=\"p-2 border bg-success\">Geeks 9</div> </div> <p><code>.align-content-stretch:</code></p> <div class=\"d-flex flex-wrap align-content-stretch bg-light\" style=\"height:100px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> <div class=\"p-2 border bg-success\">Geeks 4</div> <div class=\"p-2 border bg-success\">Geeks 5</div> <div class=\"p-2 border bg-success\">Geeks 6</div> <div class=\"p-2 border bg-success\">Geeks 7</div> <div class=\"p-2 border bg-success\">Geeks 8</div> <div class=\"p-2 border bg-success\">Geeks 9</div> </div> <br> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 18753, "s": 15905, "text": null }, { "code": null, "e": 18761, "s": 18753, "text": "Output:" }, { "code": null, "e": 18774, "s": 18761, "text": "Align items:" }, { "code": null, "e": 18905, "s": 18774, "text": "Use the align-items class to change the alignment of flex items on the cross axis. align-items can be implemented in various ways." }, { "code": null, "e": 18925, "s": 18905, "text": ".align-items-start " }, { "code": null, "e": 18943, "s": 18925, "text": ".align-items-end " }, { "code": null, "e": 18963, "s": 18943, "text": ".align-items-center" }, { "code": null, "e": 18985, "s": 18963, "text": ".align-items-baseline" }, { "code": null, "e": 19006, "s": 18985, "text": ".align-items-stretch" }, { "code": null, "e": 19028, "s": 19006, "text": ".align-items-sm-start" }, { "code": null, "e": 19057, "s": 19028, "text": "Similarly for sm, md, lg, xl" }, { "code": null, "e": 19065, "s": 19057, "text": "Syntax:" }, { "code": null, "e": 19107, "s": 19065, "text": "<div class=\"p-2 align-items-start\"></div>" }, { "code": null, "e": 19119, "s": 19107, "text": "Example 11:" }, { "code": null, "e": 19124, "s": 19119, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" items=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Align items</h2> <p><code>.align-items-start:</code></p> <div class=\"d-flex flex-wrap align-items-start bg-light\" style=\"height:70px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> </div> <p><code>.align-items-end:</code></p> <div class=\"d-flex flex-wrap align-items-end bg-light\" style=\"height:70px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> </div> <p><code>.align-items-center:</code></p> <div class=\"d-flex flex-wrap align-items-center bg-light\" style=\"height:70px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> </div> <p><code>.align-items-baseline:</code></p> <div class=\"d-flex flex-wrap align-items-around bg-light\" style=\"height:70px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> </div> <p><code>.align-items-stretch(default):</code></p> <div class=\"d-flex flex-wrap align-items-stretch bg-light\" style=\"height:70px\"> <div class=\"p-2 border bg-success\">Geeks 1</div> <div class=\"p-2 border bg-success\">Geeks 2</div> <div class=\"p-2 border bg-success\">Geeks 3</div> </div> <br> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 21550, "s": 19124, "text": null }, { "code": null, "e": 21558, "s": 21550, "text": "Output:" }, { "code": null, "e": 21570, "s": 21558, "text": "Align self:" }, { "code": null, "e": 21689, "s": 21570, "text": "align-self class can be used to change the alignment on the cross axis. align-self can be implemented in various ways." }, { "code": null, "e": 21708, "s": 21689, "text": ".align-self-start " }, { "code": null, "e": 21725, "s": 21708, "text": ".align-self-end " }, { "code": null, "e": 21744, "s": 21725, "text": ".align-self-center" }, { "code": null, "e": 21763, "s": 21744, "text": ".align-self-around" }, { "code": null, "e": 21783, "s": 21763, "text": ".align-self-stretch" }, { "code": null, "e": 21804, "s": 21783, "text": ".align-self-sm-start" }, { "code": null, "e": 21833, "s": 21804, "text": "Similarly for sm, md, lg, xl" }, { "code": null, "e": 21841, "s": 21833, "text": "Syntax:" }, { "code": null, "e": 21883, "s": 21841, "text": "<div class=\"p-2 align-self-center\"></div>" }, { "code": null, "e": 21895, "s": 21883, "text": "Example 12:" }, { "code": null, "e": 21900, "s": 21895, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" self=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Align self</h2> <p><code>.align-self-start:</code></p> <div class=\"d-flex bg-light\" style=\"height:80px\"> <div class=\"p-2 border bg-success\"> Geeks 1</div> <div class=\"p-2 border align-self-start bg-success\"> Geeks 2</div> <div class=\"p-2 border bg-success\"> Geeks 3</div> </div> <p><code>.align-self-end:</code></p> <div class=\"d-flex bg-light\" style=\"height:80px\"> <div class=\"p-2 border bg-success\"> Geeks 1</div> <div class=\"p-2 border align-self-end bg-success\"> Geeks 2</div> <div class=\"p-2 border bg-success\"> Geeks 3</div> </div> <p><code>.align-self-center:</code></p> <div class=\"d-flex bg-light\" style=\"height:80px\"> <div class=\"p-2 border bg-success\"> Geeks 1</div> <div class=\"p-2 border align-self-center bg-success\"> Geeks 2</div> <div class=\"p-2 border bg-success\"> Geeks 3</div> </div> <p><code>.align-self-baseline:</code></p> <div class=\"d-flex bg-light\" style=\"height:80px\"> <div class=\"p-2 border bg-success\"> Geeks 1</div> <div class=\"p-2 border align-self-baseline bg-success\"> Geeks 2</div> <div class=\"p-2 border bg-success\"> Geeks 3</div> </div> <p><code>.align-self-stretch(default):</code></p> <div class=\"d-flex bg-light\" style=\"height:80px\"> <div class=\"p-2 border bg-success\"> Geeks 1</div> <div class=\"p-2 border align-self-stretch bg-success\"> Geeks 2</div> <div class=\"p-2 border bg-success\"> Geeks 3</div> </div> <br> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 24451, "s": 21900, "text": null }, { "code": null, "e": 24459, "s": 24451, "text": "Output:" }, { "code": null, "e": 24501, "s": 24459, "text": "Growing and Shrinking of available space:" }, { "code": null, "e": 24672, "s": 24501, "text": ".flex-grow-* is used to grow flex items to fill available space. .flex-shrink-* is used to shrink the flex item. flex-grow and flex-shrink can be implemented as follows. " }, { "code": null, "e": 24694, "s": 24672, "text": ".flex-{grow|shrink}-0" }, { "code": null, "e": 24716, "s": 24694, "text": ".flex-{grow|shrink}-1" }, { "code": null, "e": 24745, "s": 24716, "text": "Similarly for sm, md, lg, xl" }, { "code": null, "e": 24753, "s": 24745, "text": "Syntax:" }, { "code": null, "e": 24789, "s": 24753, "text": "<div class=\"p-2 flex grow-1\"></div>" }, { "code": null, "e": 24801, "s": 24789, "text": "Example 13:" }, { "code": null, "e": 24806, "s": 24801, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" self=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\"> <title>GeeksForGeeks Bootstrap Example</title></head><body> <div class=\"container mt-3\"> <h2>Grow</h2> <p>Use <code>.flex-grow-1</code> on a Geeks to take up the rest of the space:</p> <div class=\"d-flex mb-3\"> <div class=\"p-2 bg-success\"> Geeks 1</div> <div class=\"p-2 bg-success\"> Geeks 2</div> <div class=\"p-2 flex-grow-1 bg-success\"> Geeks 3</div> </div> <p>Example without <code>.flex-grow-1</code>:</p> <div class=\"d-flex mb-3\"> <div class=\"p-2 bg-success\"> Geeks 1</div> <div class=\"p-2 bg-success\"> Geeks 2</div> <div class=\"p-2 bg-success\"> Geeks 3</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js\"> </script></body></html>", "e": 26183, "s": 24806, "text": null }, { "code": null, "e": 26191, "s": 26183, "text": "Output:" }, { "code": null, "e": 26210, "s": 26191, "text": "Supported Browser:" }, { "code": null, "e": 26224, "s": 26210, "text": "Google Chrome" }, { "code": null, "e": 26242, "s": 26224, "text": "Internet Explorer" }, { "code": null, "e": 26250, "s": 26242, "text": "Firefox" }, { "code": null, "e": 26256, "s": 26250, "text": "Opera" }, { "code": null, "e": 26263, "s": 26256, "text": "Safari" }, { "code": null, "e": 26275, "s": 26263, "text": "ysachin2314" }, { "code": null, "e": 26287, "s": 26275, "text": "sahilintern" }, { "code": null, "e": 26297, "s": 26287, "text": "Bootstrap" }, { "code": null, "e": 26301, "s": 26297, "text": "CSS" }, { "code": null, "e": 26306, "s": 26301, "text": "HTML" }, { "code": null, "e": 26323, "s": 26306, "text": "Web Technologies" }, { "code": null, "e": 26328, "s": 26323, "text": "HTML" }, { "code": null, "e": 26426, "s": 26328, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26476, "s": 26426, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 26505, "s": 26476, "text": "Form validation using jQuery" }, { "code": null, "e": 26568, "s": 26505, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 26609, "s": 26568, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 26665, "s": 26609, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 26713, "s": 26665, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26775, "s": 26713, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26825, "s": 26775, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26883, "s": 26825, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Flexbox-Layout in Android
10 Aug, 2021 Before playing, let’s learn about what FlexBox actually is. Hey, do you know the front-end also? If yes, then you should know what actually flexbox is in CSS. To learn more about CSS Flexible Box Layout Module click here. And if not, then don’t worry; here is the explanation: Here the word “Flex” stands for Flexible. In this layout, items will “flex” to different sizes to fill the space. It helps us to make a responsive UI. Now the question is why we are discussing Front-end technology instead of Android. Because in Android also we need to make such responsive UI. Just like CSS FlexBox Layout, Google has also made the FlexboxLayout library to use in android. We will discuss five different attributes of this Layout step by step through some simple examples. These five attributes are, flexDirectionflexWrapjustifyContentalignItems alignContent flexDirection flexWrap justifyContent alignItems alignContent At first, look at a quick overview of these attributes: Basically, the flexDirection attribute determines the direction of the main axis. It has four possible parameters and they are, row row_reverse column colum_reverse Now, we can use these parameters in our flexbox layout in the following ways: In XML, app:flexDirection=”parameter“ Programmatically, flexboxLayout.flexDirection = FlexDirection.PARAMETER // Kotlin (Property access syntax) flexboxLayout.setFlexDirection(FlexDirection.PARAMETER); // Java * In place of the word, parameter write down relevant parameters. Let us use the following flexbox layout to test all parameters of the corresponding attribute. XML <!-- to test flexDirection --><com.google.android.flexbox.FlexboxLayout android:id="@+id/flexboxLayout1" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="50dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="100dp" android:src="@drawable/gfg_3" android:scaleType="centerCrop"/> <ImageView android:layout_width="60dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> </com.google.android.flexbox.FlexboxLayout> Let’s see the result: The flexWrap attribute controls whether the flex container is single-line or multi-line, and the direction of the cross axis (Perpendicular to the main axis). In simple words, It is like the LinearLayout with supported line breaks. It has three possible parameters and they are, nowrap wrap wrap_reverse Now, we can use these parameters in our flexbox layout in the following ways: In XML, app:flexWrap=”parameter” Programmatically, flexboxLayout.flexWrap = FlexWrap.PARAMETER // Kotlin (Property access syntax) flexboxLayout.setFlexWrap(FlexWrap.PARAMETER); // Java * In place of the word, parameter write down relevant parameters. Let us use the following flexbox layout to test all parameters of the corresponding attribute. XML <!-- to test flewWrap --><com.google.android.flexbox.FlexboxLayout android:id="@+id/flexboxLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" app:flexWrap="wrap" app:alignContent="flex_start"> <ImageView android:layout_width="50dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="80dp" android:src="@drawable/gfg_3" android:scaleType="centerCrop"/> <ImageView android:layout_width="60dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_4" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="80dp" android:src="@drawable/gfg_4" android:scaleType="centerCrop"/> </com.google.android.flexbox.FlexboxLayout> Let’s see the result: The justifyContent attribute controls the alignment along the main axis. It has six possible parameters and they are : flex_start flex_end center space_between space_around space_evenly Now, we can use these parameters in our flexbox layout in the following ways:- In XML, app:justifyContent=”parameter” Programmatically, flexboxLayout.justifyContent = JustifyContent.PARAMETER // Kotlin (Property access syntax) flexboxLayout.setJustifyContent(JustifyContent.PARAMETER); // Java * In place of the word, parameter write down relevant parameters. Let us use the following flexbox layout to test all parameters of the corresponding attribute. XML <!-- to test justifyContent --><com.google.android.flexbox.FlexboxLayout android:id="@+id/flexboxLayout3" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="50dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="100dp" android:src="@drawable/gfg_3" android:scaleType="centerCrop"/> <ImageView android:layout_width="60dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> </com.google.android.flexbox.FlexboxLayout> Let’s see the result: The alignItems attribute controls the alignment along the cross axis. It has five possible parameters and they are, flex_start flex_end center baseline stretch Now, we can use these parameters in our flexbox layout in the following ways: In XML, app:alignItems=”parameter” Programmatically, flexboxLayout.alignItems =AlignItems.PARAMETER // Kotlin (Property access syntax) flexboxLayout.setAlignItems(AlignItems.PARAMETER); // Java * In place of the word, parameter write down relevant parameters. Let us use the following flexbox layout to test all parameters of the corresponding attribute. XML <!-- to test alignItems --><com.google.android.flexbox.FlexboxLayout android:id="@+id/flexboxLayout4" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="50dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="100dp" android:src="@drawable/gfg_3" android:scaleType="centerCrop"/> <ImageView android:layout_width="60dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> </com.google.android.flexbox.FlexboxLayout> Let’s see the result: This attribute controls the alignment of the flex lines in the flex container. If there has only one axis, the attribute does not work. It has six possible parameters and they are, flex_start (default) flex_end center space_between space_around stretch Now, we can use these parameters in our flexbox layout in the following ways: In XML, app:alignContent=”parameter” Programmatically, flexboxLayout.alignContent = AlignContent.PARAMETER // Kotlin (Property access syntax) flexboxLayout.setAlignContent(AlignContent.PARAMETER); // Java * In place of the word, parameter write down relevant parameters. Let us use the following flexbox layout to test all parameters of the corresponding attribute. XML <!-- to test alignContent --><com.google.android.flexbox.FlexboxLayout android:id="@+id/flexboxLayout5" android:layout_width="match_parent" android:layout_height="match_parent" app:flexWrap="wrap" app:alignContent="flex_start"> <ImageView android:layout_width="50dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="80dp" android:src="@drawable/gfg_3" android:scaleType="centerCrop"/> <ImageView android:layout_width="60dp" android:layout_height="80dp" android:src="@drawable/gfg_2" android:scaleType="centerCrop"/> <ImageView android:layout_width="100dp" android:layout_height="80dp" android:src="@drawable/gfg_4" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="80dp" android:src="@drawable/gfg_1" android:scaleType="centerCrop"/> <ImageView android:layout_width="90dp" android:layout_height="80dp" android:src="@drawable/gfg_4" android:scaleType="centerCrop"/> </com.google.android.flexbox.FlexboxLayout> Let’s see the result: Now, do you want to play with all these attributes in this application? Firstly, You can try to make this on your own. Otherwise, you can take help from the source code of my project. For the project’s source code -> CLICK HERE. gabaa406 Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Introduction to Android Development Animation in Android with Example Data Binding in Android with Example Fragment Lifecycle in Android Activity Lifecycle in Android with Demo App
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Aug, 2021" }, { "code": null, "e": 115, "s": 54, "text": "Before playing, let’s learn about what FlexBox actually is. " }, { "code": null, "e": 333, "s": 115, "text": "Hey, do you know the front-end also? If yes, then you should know what actually flexbox is in CSS. To learn more about CSS Flexible Box Layout Module click here. And if not, then don’t worry; here is the explanation: " }, { "code": null, "e": 484, "s": 333, "text": "Here the word “Flex” stands for Flexible. In this layout, items will “flex” to different sizes to fill the space. It helps us to make a responsive UI." }, { "code": null, "e": 850, "s": 484, "text": "Now the question is why we are discussing Front-end technology instead of Android. Because in Android also we need to make such responsive UI. Just like CSS FlexBox Layout, Google has also made the FlexboxLayout library to use in android. We will discuss five different attributes of this Layout step by step through some simple examples. These five attributes are," }, { "code": null, "e": 909, "s": 850, "text": "flexDirectionflexWrapjustifyContentalignItems alignContent" }, { "code": null, "e": 923, "s": 909, "text": "flexDirection" }, { "code": null, "e": 932, "s": 923, "text": "flexWrap" }, { "code": null, "e": 947, "s": 932, "text": "justifyContent" }, { "code": null, "e": 959, "s": 947, "text": "alignItems " }, { "code": null, "e": 972, "s": 959, "text": "alignContent" }, { "code": null, "e": 1028, "s": 972, "text": "At first, look at a quick overview of these attributes:" }, { "code": null, "e": 1156, "s": 1028, "text": "Basically, the flexDirection attribute determines the direction of the main axis. It has four possible parameters and they are," }, { "code": null, "e": 1160, "s": 1156, "text": "row" }, { "code": null, "e": 1172, "s": 1160, "text": "row_reverse" }, { "code": null, "e": 1179, "s": 1172, "text": "column" }, { "code": null, "e": 1194, "s": 1179, "text": "colum_reverse " }, { "code": null, "e": 1272, "s": 1194, "text": "Now, we can use these parameters in our flexbox layout in the following ways:" }, { "code": null, "e": 1311, "s": 1272, "text": "In XML, app:flexDirection=”parameter“" }, { "code": null, "e": 1329, "s": 1311, "text": "Programmatically," }, { "code": null, "e": 1443, "s": 1329, "text": " flexboxLayout.flexDirection = FlexDirection.PARAMETER // Kotlin (Property access syntax)" }, { "code": null, "e": 1529, "s": 1443, "text": " flexboxLayout.setFlexDirection(FlexDirection.PARAMETER); // Java" }, { "code": null, "e": 1595, "s": 1529, "text": "* In place of the word, parameter write down relevant parameters." }, { "code": null, "e": 1690, "s": 1595, "text": "Let us use the following flexbox layout to test all parameters of the corresponding attribute." }, { "code": null, "e": 1694, "s": 1690, "text": "XML" }, { "code": "<!-- to test flexDirection --><com.google.android.flexbox.FlexboxLayout android:id=\"@+id/flexboxLayout1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"100dp\" android:src=\"@drawable/gfg_3\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"60dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> </com.google.android.flexbox.FlexboxLayout>", "e": 2766, "s": 1694, "text": null }, { "code": null, "e": 2788, "s": 2766, "text": "Let’s see the result:" }, { "code": null, "e": 3067, "s": 2788, "text": "The flexWrap attribute controls whether the flex container is single-line or multi-line, and the direction of the cross axis (Perpendicular to the main axis). In simple words, It is like the LinearLayout with supported line breaks. It has three possible parameters and they are," }, { "code": null, "e": 3074, "s": 3067, "text": "nowrap" }, { "code": null, "e": 3079, "s": 3074, "text": "wrap" }, { "code": null, "e": 3092, "s": 3079, "text": "wrap_reverse" }, { "code": null, "e": 3170, "s": 3092, "text": "Now, we can use these parameters in our flexbox layout in the following ways:" }, { "code": null, "e": 3204, "s": 3170, "text": "In XML, app:flexWrap=”parameter”" }, { "code": null, "e": 3222, "s": 3204, "text": "Programmatically," }, { "code": null, "e": 3325, "s": 3222, "text": " flexboxLayout.flexWrap = FlexWrap.PARAMETER // Kotlin (Property access syntax)" }, { "code": null, "e": 3401, "s": 3325, "text": " flexboxLayout.setFlexWrap(FlexWrap.PARAMETER); // Java" }, { "code": null, "e": 3468, "s": 3401, "text": " * In place of the word, parameter write down relevant parameters." }, { "code": null, "e": 3564, "s": 3468, "text": "Let us use the following flexbox layout to test all parameters of the corresponding attribute. " }, { "code": null, "e": 3568, "s": 3564, "text": "XML" }, { "code": "<!-- to test flewWrap --><com.google.android.flexbox.FlexboxLayout android:id=\"@+id/flexboxLayout2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:flexWrap=\"wrap\" app:alignContent=\"flex_start\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_3\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"60dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_4\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_4\" android:scaleType=\"centerCrop\"/> </com.google.android.flexbox.FlexboxLayout>", "e": 5313, "s": 3568, "text": null }, { "code": null, "e": 5335, "s": 5313, "text": "Let’s see the result:" }, { "code": null, "e": 5455, "s": 5335, "text": "The justifyContent attribute controls the alignment along the main axis. It has six possible parameters and they are : " }, { "code": null, "e": 5466, "s": 5455, "text": "flex_start" }, { "code": null, "e": 5475, "s": 5466, "text": "flex_end" }, { "code": null, "e": 5482, "s": 5475, "text": "center" }, { "code": null, "e": 5497, "s": 5482, "text": "space_between " }, { "code": null, "e": 5511, "s": 5497, "text": "space_around " }, { "code": null, "e": 5525, "s": 5511, "text": "space_evenly " }, { "code": null, "e": 5606, "s": 5527, "text": "Now, we can use these parameters in our flexbox layout in the following ways:-" }, { "code": null, "e": 5646, "s": 5606, "text": "In XML, app:justifyContent=”parameter”" }, { "code": null, "e": 5664, "s": 5646, "text": "Programmatically," }, { "code": null, "e": 5778, "s": 5664, "text": " flexboxLayout.justifyContent = JustifyContent.PARAMETER // Kotlin (Property access syntax)" }, { "code": null, "e": 5865, "s": 5778, "text": " flexboxLayout.setJustifyContent(JustifyContent.PARAMETER); // Java" }, { "code": null, "e": 5937, "s": 5865, "text": " * In place of the word, parameter write down relevant parameters." }, { "code": null, "e": 6032, "s": 5937, "text": "Let us use the following flexbox layout to test all parameters of the corresponding attribute." }, { "code": null, "e": 6036, "s": 6032, "text": "XML" }, { "code": "<!-- to test justifyContent --><com.google.android.flexbox.FlexboxLayout android:id=\"@+id/flexboxLayout3\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"100dp\" android:src=\"@drawable/gfg_3\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"60dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> </com.google.android.flexbox.FlexboxLayout>", "e": 7114, "s": 6036, "text": null }, { "code": null, "e": 7139, "s": 7117, "text": "Let’s see the result:" }, { "code": null, "e": 7256, "s": 7139, "text": "The alignItems attribute controls the alignment along the cross axis. It has five possible parameters and they are, " }, { "code": null, "e": 7267, "s": 7256, "text": "flex_start" }, { "code": null, "e": 7276, "s": 7267, "text": "flex_end" }, { "code": null, "e": 7283, "s": 7276, "text": "center" }, { "code": null, "e": 7293, "s": 7283, "text": "baseline " }, { "code": null, "e": 7302, "s": 7293, "text": "stretch " }, { "code": null, "e": 7381, "s": 7302, "text": " Now, we can use these parameters in our flexbox layout in the following ways:" }, { "code": null, "e": 7417, "s": 7381, "text": "In XML, app:alignItems=”parameter”" }, { "code": null, "e": 7435, "s": 7417, "text": "Programmatically," }, { "code": null, "e": 7539, "s": 7435, "text": " flexboxLayout.alignItems =AlignItems.PARAMETER // Kotlin (Property access syntax)" }, { "code": null, "e": 7617, "s": 7539, "text": " flexboxLayout.setAlignItems(AlignItems.PARAMETER); // Java" }, { "code": null, "e": 7688, "s": 7617, "text": " * In place of the word, parameter write down relevant parameters." }, { "code": null, "e": 7783, "s": 7688, "text": "Let us use the following flexbox layout to test all parameters of the corresponding attribute." }, { "code": null, "e": 7787, "s": 7783, "text": "XML" }, { "code": "<!-- to test alignItems --><com.google.android.flexbox.FlexboxLayout android:id=\"@+id/flexboxLayout4\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"100dp\" android:src=\"@drawable/gfg_3\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"60dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> </com.google.android.flexbox.FlexboxLayout>", "e": 8862, "s": 7787, "text": null }, { "code": null, "e": 8884, "s": 8862, "text": "Let’s see the result:" }, { "code": null, "e": 9066, "s": 8884, "text": "This attribute controls the alignment of the flex lines in the flex container. If there has only one axis, the attribute does not work. It has six possible parameters and they are, " }, { "code": null, "e": 9087, "s": 9066, "text": "flex_start (default)" }, { "code": null, "e": 9096, "s": 9087, "text": "flex_end" }, { "code": null, "e": 9103, "s": 9096, "text": "center" }, { "code": null, "e": 9117, "s": 9103, "text": "space_between" }, { "code": null, "e": 9130, "s": 9117, "text": "space_around" }, { "code": null, "e": 9138, "s": 9130, "text": "stretch" }, { "code": null, "e": 9217, "s": 9138, "text": "Now, we can use these parameters in our flexbox layout in the following ways: " }, { "code": null, "e": 9255, "s": 9217, "text": "In XML, app:alignContent=”parameter”" }, { "code": null, "e": 9273, "s": 9255, "text": "Programmatically," }, { "code": null, "e": 9381, "s": 9273, "text": " flexboxLayout.alignContent = AlignContent.PARAMETER // Kotlin (Property access syntax)" }, { "code": null, "e": 9462, "s": 9381, "text": " flexboxLayout.setAlignContent(AlignContent.PARAMETER); // Java" }, { "code": null, "e": 9528, "s": 9462, "text": "* In place of the word, parameter write down relevant parameters." }, { "code": null, "e": 9624, "s": 9528, "text": "Let us use the following flexbox layout to test all parameters of the corresponding attribute. " }, { "code": null, "e": 9628, "s": 9624, "text": "XML" }, { "code": "<!-- to test alignContent --><com.google.android.flexbox.FlexboxLayout android:id=\"@+id/flexboxLayout5\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:flexWrap=\"wrap\" app:alignContent=\"flex_start\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_3\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"60dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_2\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"100dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_4\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_1\" android:scaleType=\"centerCrop\"/> <ImageView android:layout_width=\"90dp\" android:layout_height=\"80dp\" android:src=\"@drawable/gfg_4\" android:scaleType=\"centerCrop\"/> </com.google.android.flexbox.FlexboxLayout>", "e": 11385, "s": 9628, "text": null }, { "code": null, "e": 11408, "s": 11385, "text": " Let’s see the result:" }, { "code": null, "e": 11637, "s": 11408, "text": "Now, do you want to play with all these attributes in this application? Firstly, You can try to make this on your own. Otherwise, you can take help from the source code of my project. For the project’s source code -> CLICK HERE." }, { "code": null, "e": 11648, "s": 11639, "text": "gabaa406" }, { "code": null, "e": 11655, "s": 11648, "text": "Picked" }, { "code": null, "e": 11663, "s": 11655, "text": "Android" }, { "code": null, "e": 11671, "s": 11663, "text": "Android" }, { "code": null, "e": 11769, "s": 11671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11801, "s": 11769, "text": "Android SDK and it's Components" }, { "code": null, "e": 11840, "s": 11801, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 11882, "s": 11840, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 11933, "s": 11882, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 11956, "s": 11933, "text": "Flutter - Stack Widget" }, { "code": null, "e": 11992, "s": 11956, "text": "Introduction to Android Development" }, { "code": null, "e": 12026, "s": 11992, "text": "Animation in Android with Example" }, { "code": null, "e": 12063, "s": 12026, "text": "Data Binding in Android with Example" }, { "code": null, "e": 12093, "s": 12063, "text": "Fragment Lifecycle in Android" } ]
How to disable a button depending on a checkbox’s state in AngularJS ?
27 Jul, 2021 In this article, we will learn to disable the button depending upon the check-box status in Angular. We will use the Angular JS directive named ng-disabled to disable the button by unchecking the box. Please refer to AngularJS ng-disabled Directive. The ng-disabled directive is used to enable or disable the HTML elements. If the expression inside the ng-disabled directive returns true then the HTML element would be disabled and vice versa. Approach: Here in the example, we have taken a checkbox and based on the checkbox, we are checking that whether the submit button is to be enabled or disabled. Here ng-model directive is used for binding the checkbox with the submit button & the ng-disabled directive is to handle the disable or enable operations. Here if the checkbox is checked it will return TRUE and that TRUE will be passed to the ng-disabled directive. As a result, the submit button would be disabled but we need to enable it whenever the checkbox is checked. So for that, we need to have a NOT operation at the ng-disabled directive so that whenever the checkbox returns TRUE, the value that will go to the ng-disabled directive will be FALSE so that the submit button is enabled. Example: HTML <!DOCTYPE html><html lang="en"> <head> <!-- Including the Angular JS CDN --> <script src="http://code.angularjs.org/1.2.0/angular.min.js"> </script></head> <body> <!-- Defining the Angular Application --> <div ng-app=""> <!-- Here we define the ng-model to the checkbox so that we can refer to it whether it checked or not --> <input type="checkbox" name="isAgreed" ng-model="isAgreed" /> <p>I agree with the Terms and Conditions</p> <br /> <!-- If the checkbox is checked then button would be enabled and if not checked then button would be disabled --> <button ng-disabled="!isAgreed">Submit</button> </div></body> </html> Output: AngularJS-Questions Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jul, 2021" }, { "code": null, "e": 278, "s": 28, "text": "In this article, we will learn to disable the button depending upon the check-box status in Angular. We will use the Angular JS directive named ng-disabled to disable the button by unchecking the box. Please refer to AngularJS ng-disabled Directive." }, { "code": null, "e": 473, "s": 278, "text": "The ng-disabled directive is used to enable or disable the HTML elements. If the expression inside the ng-disabled directive returns true then the HTML element would be disabled and vice versa. " }, { "code": null, "e": 788, "s": 473, "text": "Approach: Here in the example, we have taken a checkbox and based on the checkbox, we are checking that whether the submit button is to be enabled or disabled. Here ng-model directive is used for binding the checkbox with the submit button & the ng-disabled directive is to handle the disable or enable operations." }, { "code": null, "e": 1229, "s": 788, "text": "Here if the checkbox is checked it will return TRUE and that TRUE will be passed to the ng-disabled directive. As a result, the submit button would be disabled but we need to enable it whenever the checkbox is checked. So for that, we need to have a NOT operation at the ng-disabled directive so that whenever the checkbox returns TRUE, the value that will go to the ng-disabled directive will be FALSE so that the submit button is enabled." }, { "code": null, "e": 1238, "s": 1229, "text": "Example:" }, { "code": null, "e": 1243, "s": 1238, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Including the Angular JS CDN --> <script src=\"http://code.angularjs.org/1.2.0/angular.min.js\"> </script></head> <body> <!-- Defining the Angular Application --> <div ng-app=\"\"> <!-- Here we define the ng-model to the checkbox so that we can refer to it whether it checked or not --> <input type=\"checkbox\" name=\"isAgreed\" ng-model=\"isAgreed\" /> <p>I agree with the Terms and Conditions</p> <br /> <!-- If the checkbox is checked then button would be enabled and if not checked then button would be disabled --> <button ng-disabled=\"!isAgreed\">Submit</button> </div></body> </html>", "e": 2000, "s": 1243, "text": null }, { "code": null, "e": 2008, "s": 2000, "text": "Output:" }, { "code": null, "e": 2028, "s": 2008, "text": "AngularJS-Questions" }, { "code": null, "e": 2035, "s": 2028, "text": "Picked" }, { "code": null, "e": 2045, "s": 2035, "text": "AngularJS" }, { "code": null, "e": 2062, "s": 2045, "text": "Web Technologies" } ]
Kotlin Class and Objects
01 May, 2022 Kotlin supports both functional and object-oriented programming. In previous articles, we have learned about functions, higher-order functions, and lambdas which represent Kotlin as a functional language. Here, we will learn about the basic OOPs concepts which represent Kotlin as an Object-Oriented programming language. Object-Oriented Programming Language Class and Objects are the basic concepts of object-oriented programming language. These support the OOPs concepts of inheritance, abstraction, etc. Like Java, class is a blueprint for objects having similar properties. We need to define a class before creating an object and the class keyword is used to define a class. The class declaration consists of the class name, class header, and class body enclosed with curly braces. Syntax of the class declaration: class className { // class header // property // member function } Class name: every class has a specific name Class header: header consists of parameters and constructors of a class Class body: surrounded by curly braces, contains member functions and other property Both the header and the class body are optional; if there is nothing in between curly braces then the class body can be omitted. class emptyClass If we want to provide a constructor, we need to write a keyword constructor just after the class name. Creating constructor: class className constructor(parameters) { // property // member function } Example of Kotlin class: Kotlin class employee { // properties var name: String = "" var age: Int = 0 var gender: Char = 'M' var salary: Double = 0.toDouble() // member functions fun name(){ } fun age() { } fun salary(){ }} It is a basic unit of Object-Oriented Programming and represents the real-life entities, which have states and behavior. Objects are used to access the properties and member functions of a class. In Kotlin, we can create multiple objects of a class. An object consists of: State: It is represented by the attributes of an object. It also reflects the properties of an object. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Create an object We can create an object using the reference of the class. var obj = className() Accessing the property of the class: We can access the properties of a class using an object. First, create an object using the class reference and then access the property. obj.nameOfProperty Accessing the member function of the class: We can access the member function of the class using the object. obj.funtionName(parameters) Kotlin program of creating multiple objects and accessing the property and member function of class: Kotlin class employee { // Constructor Declaration of Class var name: String = "" var age: Int = 0 var gender: Char = 'M' var salary: Double = 0.toDouble() fun insertValues(n: String, a: Int, g: Char, s: Double) { name = n age = a gender = g salary = s println("Name of the employee: $name") println("Age of the employee: $age") println("Gender: $gender") println("Salary of the employee: $salary") } fun insertName(n: String) { this.name = n } }fun main(args: Array<String>) { // creating multiple objects var obj = employee() // object 2 of class employee var obj2 = employee() //accessing the member function obj.insertValues("Praveen", 50, 'M', 500000.00) // accessing the member function obj2.insertName("Aliena") // accessing the name property of class println("Name of the new employee: ${obj2.name}") } Output: Name of the employee: Praveen Age of the employee: 50 Gender: M Salary of the employee: 500000.0 Name of the new employee: Aliena rajeev0719singh aadityapburujwale Kotlin OOPs Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 May, 2022" }, { "code": null, "e": 375, "s": 52, "text": "Kotlin supports both functional and object-oriented programming. In previous articles, we have learned about functions, higher-order functions, and lambdas which represent Kotlin as a functional language. Here, we will learn about the basic OOPs concepts which represent Kotlin as an Object-Oriented programming language. " }, { "code": null, "e": 413, "s": 375, "text": "Object-Oriented Programming Language " }, { "code": null, "e": 562, "s": 413, "text": "Class and Objects are the basic concepts of object-oriented programming language. These support the OOPs concepts of inheritance, abstraction, etc. " }, { "code": null, "e": 842, "s": 562, "text": "Like Java, class is a blueprint for objects having similar properties. We need to define a class before creating an object and the class keyword is used to define a class. The class declaration consists of the class name, class header, and class body enclosed with curly braces. " }, { "code": null, "e": 877, "s": 842, "text": "Syntax of the class declaration: " }, { "code": null, "e": 955, "s": 877, "text": "class className { // class header\n // property\n // member function\n}" }, { "code": null, "e": 1000, "s": 955, "text": "Class name: every class has a specific name " }, { "code": null, "e": 1073, "s": 1000, "text": "Class header: header consists of parameters and constructors of a class " }, { "code": null, "e": 1159, "s": 1073, "text": "Class body: surrounded by curly braces, contains member functions and other property " }, { "code": null, "e": 1290, "s": 1159, "text": "Both the header and the class body are optional; if there is nothing in between curly braces then the class body can be omitted. " }, { "code": null, "e": 1307, "s": 1290, "text": "class emptyClass" }, { "code": null, "e": 1411, "s": 1307, "text": "If we want to provide a constructor, we need to write a keyword constructor just after the class name. " }, { "code": null, "e": 1435, "s": 1411, "text": "Creating constructor: " }, { "code": null, "e": 1520, "s": 1435, "text": "class className constructor(parameters) { \n // property\n // member function\n}" }, { "code": null, "e": 1546, "s": 1520, "text": "Example of Kotlin class: " }, { "code": null, "e": 1553, "s": 1546, "text": "Kotlin" }, { "code": "class employee { // properties var name: String = \"\" var age: Int = 0 var gender: Char = 'M' var salary: Double = 0.toDouble() // member functions fun name(){ } fun age() { } fun salary(){ }}", "e": 1793, "s": 1553, "text": null }, { "code": null, "e": 2066, "s": 1793, "text": "It is a basic unit of Object-Oriented Programming and represents the real-life entities, which have states and behavior. Objects are used to access the properties and member functions of a class. In Kotlin, we can create multiple objects of a class. An object consists of:" }, { "code": null, "e": 2170, "s": 2066, "text": "State: It is represented by the attributes of an object. It also reflects the properties of an object. " }, { "code": null, "e": 2289, "s": 2170, "text": "Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. " }, { "code": null, "e": 2391, "s": 2289, "text": "Identity: It gives a unique name to an object and enables one object to interact with other objects. " }, { "code": null, "e": 2408, "s": 2391, "text": "Create an object" }, { "code": null, "e": 2467, "s": 2408, "text": "We can create an object using the reference of the class. " }, { "code": null, "e": 2489, "s": 2467, "text": "var obj = className()" }, { "code": null, "e": 2526, "s": 2489, "text": "Accessing the property of the class:" }, { "code": null, "e": 2664, "s": 2526, "text": "We can access the properties of a class using an object. First, create an object using the class reference and then access the property. " }, { "code": null, "e": 2683, "s": 2664, "text": "obj.nameOfProperty" }, { "code": null, "e": 2727, "s": 2683, "text": "Accessing the member function of the class:" }, { "code": null, "e": 2793, "s": 2727, "text": "We can access the member function of the class using the object. " }, { "code": null, "e": 2821, "s": 2793, "text": "obj.funtionName(parameters)" }, { "code": null, "e": 2922, "s": 2821, "text": "Kotlin program of creating multiple objects and accessing the property and member function of class:" }, { "code": null, "e": 2929, "s": 2922, "text": "Kotlin" }, { "code": "class employee { // Constructor Declaration of Class var name: String = \"\" var age: Int = 0 var gender: Char = 'M' var salary: Double = 0.toDouble() fun insertValues(n: String, a: Int, g: Char, s: Double) { name = n age = a gender = g salary = s println(\"Name of the employee: $name\") println(\"Age of the employee: $age\") println(\"Gender: $gender\") println(\"Salary of the employee: $salary\") } fun insertName(n: String) { this.name = n } }fun main(args: Array<String>) { // creating multiple objects var obj = employee() // object 2 of class employee var obj2 = employee() //accessing the member function obj.insertValues(\"Praveen\", 50, 'M', 500000.00) // accessing the member function obj2.insertName(\"Aliena\") // accessing the name property of class println(\"Name of the new employee: ${obj2.name}\") }", "e": 3873, "s": 2929, "text": null }, { "code": null, "e": 3883, "s": 3873, "text": "Output: " }, { "code": null, "e": 4013, "s": 3883, "text": "Name of the employee: Praveen\nAge of the employee: 50\nGender: M\nSalary of the employee: 500000.0\nName of the new employee: Aliena" }, { "code": null, "e": 4029, "s": 4013, "text": "rajeev0719singh" }, { "code": null, "e": 4047, "s": 4029, "text": "aadityapburujwale" }, { "code": null, "e": 4059, "s": 4047, "text": "Kotlin OOPs" }, { "code": null, "e": 4066, "s": 4059, "text": "Kotlin" } ]
Software Testing | Fuzz Testing
16 May, 2019 Fuzz Testing is a Software Testing technique which uses invalid, unexpected or random data as input and then check for exceptions such as crashes and potential memory leaks. It is a automated testing technique that is performed to describe the system testing processes involving randomized or distributed approach. During fuzz testing, system or software application can have a lot of different bugs or glitches related to data input. Barton Miller at the University of Wisconsin in 1989 firstly developed the fuzz testing. Objective of Fuzz Testing:The objective of the Fuzz Testing is: To check the vulnerability of the system or software application. To detect the security faults and defects. To determine the defects in effective cost. Phases of Fuzz Testing: Identify Target System:Th system or the software application which is going to be tested is marked. That system is know as the target system. Target system is identified by testing team.Identify Inputs:Once the target system is set after that the random inputs are created for the purpose of the testing. These random test cases are used as inputs to test the system or software application.Generate Fuzzed Data:After getting the random inputs i.e. unexpected and invalid, these invalid and unexpected inputs are converted into the fuzzed data. Fuzzed data is basically random input in form of fuzzy logic.Execute the test using fuzzed data:Now using the fuzzed data testing process is performed. Basically in this section, the code of program or the software is executed by giving the random input i.e. fuzzed data .Monitor System Behavior:After the execution of the system or the software application, operated for crashes or any other exceptions like potential memory leaks. System behavior is tested under the random input.Log Defects:In the last phase defects are identified and these defects are fixed in order to get the better quality system or software application. Identify Target System:Th system or the software application which is going to be tested is marked. That system is know as the target system. Target system is identified by testing team. Identify Inputs:Once the target system is set after that the random inputs are created for the purpose of the testing. These random test cases are used as inputs to test the system or software application. Generate Fuzzed Data:After getting the random inputs i.e. unexpected and invalid, these invalid and unexpected inputs are converted into the fuzzed data. Fuzzed data is basically random input in form of fuzzy logic. Execute the test using fuzzed data:Now using the fuzzed data testing process is performed. Basically in this section, the code of program or the software is executed by giving the random input i.e. fuzzed data . Monitor System Behavior:After the execution of the system or the software application, operated for crashes or any other exceptions like potential memory leaks. System behavior is tested under the random input. Log Defects:In the last phase defects are identified and these defects are fixed in order to get the better quality system or software application. Types of defects detected by Fuzz Testing: 1. Number Fuzzing 2. Character Fuzzing 3. Application Fuzzing 4. Protocol Fuzzing 5. File Format Fuzzing Advantages of Fuzz Testing: It ensures the software security. It detects the defects including crashes and potential memory leaks. It is less time consuming. Disadvantages of Fuzz Testing: It is not able to provide complete security of the system. It is not effective for dealing with security threats that don’t have viruses, bugs or program crashing cause. It detects simple faults and threats. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2019" }, { "code": null, "e": 552, "s": 28, "text": "Fuzz Testing is a Software Testing technique which uses invalid, unexpected or random data as input and then check for exceptions such as crashes and potential memory leaks. It is a automated testing technique that is performed to describe the system testing processes involving randomized or distributed approach. During fuzz testing, system or software application can have a lot of different bugs or glitches related to data input. Barton Miller at the University of Wisconsin in 1989 firstly developed the fuzz testing." }, { "code": null, "e": 616, "s": 552, "text": "Objective of Fuzz Testing:The objective of the Fuzz Testing is:" }, { "code": null, "e": 682, "s": 616, "text": "To check the vulnerability of the system or software application." }, { "code": null, "e": 725, "s": 682, "text": "To detect the security faults and defects." }, { "code": null, "e": 769, "s": 725, "text": "To determine the defects in effective cost." }, { "code": null, "e": 793, "s": 769, "text": "Phases of Fuzz Testing:" }, { "code": null, "e": 1968, "s": 793, "text": "Identify Target System:Th system or the software application which is going to be tested is marked. That system is know as the target system. Target system is identified by testing team.Identify Inputs:Once the target system is set after that the random inputs are created for the purpose of the testing. These random test cases are used as inputs to test the system or software application.Generate Fuzzed Data:After getting the random inputs i.e. unexpected and invalid, these invalid and unexpected inputs are converted into the fuzzed data. Fuzzed data is basically random input in form of fuzzy logic.Execute the test using fuzzed data:Now using the fuzzed data testing process is performed. Basically in this section, the code of program or the software is executed by giving the random input i.e. fuzzed data .Monitor System Behavior:After the execution of the system or the software application, operated for crashes or any other exceptions like potential memory leaks. System behavior is tested under the random input.Log Defects:In the last phase defects are identified and these defects are fixed in order to get the better quality system or software application." }, { "code": null, "e": 2155, "s": 1968, "text": "Identify Target System:Th system or the software application which is going to be tested is marked. That system is know as the target system. Target system is identified by testing team." }, { "code": null, "e": 2361, "s": 2155, "text": "Identify Inputs:Once the target system is set after that the random inputs are created for the purpose of the testing. These random test cases are used as inputs to test the system or software application." }, { "code": null, "e": 2577, "s": 2361, "text": "Generate Fuzzed Data:After getting the random inputs i.e. unexpected and invalid, these invalid and unexpected inputs are converted into the fuzzed data. Fuzzed data is basically random input in form of fuzzy logic." }, { "code": null, "e": 2789, "s": 2577, "text": "Execute the test using fuzzed data:Now using the fuzzed data testing process is performed. Basically in this section, the code of program or the software is executed by giving the random input i.e. fuzzed data ." }, { "code": null, "e": 3000, "s": 2789, "text": "Monitor System Behavior:After the execution of the system or the software application, operated for crashes or any other exceptions like potential memory leaks. System behavior is tested under the random input." }, { "code": null, "e": 3148, "s": 3000, "text": "Log Defects:In the last phase defects are identified and these defects are fixed in order to get the better quality system or software application." }, { "code": null, "e": 3191, "s": 3148, "text": "Types of defects detected by Fuzz Testing:" }, { "code": null, "e": 3297, "s": 3191, "text": "1. Number Fuzzing\n2. Character Fuzzing\n3. Application Fuzzing\n4. Protocol Fuzzing\n5. File Format Fuzzing " }, { "code": null, "e": 3325, "s": 3297, "text": "Advantages of Fuzz Testing:" }, { "code": null, "e": 3359, "s": 3325, "text": "It ensures the software security." }, { "code": null, "e": 3428, "s": 3359, "text": "It detects the defects including crashes and potential memory leaks." }, { "code": null, "e": 3455, "s": 3428, "text": "It is less time consuming." }, { "code": null, "e": 3486, "s": 3455, "text": "Disadvantages of Fuzz Testing:" }, { "code": null, "e": 3545, "s": 3486, "text": "It is not able to provide complete security of the system." }, { "code": null, "e": 3656, "s": 3545, "text": "It is not effective for dealing with security threats that don’t have viruses, bugs or program crashing cause." }, { "code": null, "e": 3694, "s": 3656, "text": "It detects simple faults and threats." }, { "code": null, "e": 3711, "s": 3694, "text": "Software Testing" }, { "code": null, "e": 3732, "s": 3711, "text": "Software Engineering" } ]
Python | os.listdir() method
20 May, 2019 os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned. Syntax: os.listdir(path) Parameters:path (optional) : path of the directory Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list. Code #1: use of os.listdir() method # Python program to explain os.listdir() method # importing os module import os # Get the list of all files and directories# in the root directorypath = "/"dir_list = os.listdir(path) print("Files and directories in '", path, "' :") # print the listprint(dir_list) Files and directories in ' / ' : ['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr', 'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media'] Code #2: use of os.listdir() method # Python program to explain os.listdir() method # importing os module import os # Get the path of current working directorypath = os.getcwd() # Get the list of all files and directories# in current working directorydir_list = os.listdir(path) print("Files and directories in '", path, "' :") # print the listprint(dir_list) Files and directories in ' /home/ihritik ' : ['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public', 'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music', '.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local', '.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates', '.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images', 'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks'] Code #3: omitting path parameter # Python program to explain os.listdir() method # importing os module import os # If we do not specify any path# os.listdir() method will return# the list of all files and directories# in current working directory dir_list = os.listdir() print("Files and directories in current working directory :") # print the listprint(dir_list) Files and directories in current working directory : ['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public', 'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music', '.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local', '.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates', '.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images', 'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks'] As we can see the output of Code #2 and Code #3 are same. So if we omit the path parameter os.listdir() method will return the list of all files and directories in the current working directory. python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 May, 2019" }, { "code": null, "e": 285, "s": 53, "text": "os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned." }, { "code": null, "e": 310, "s": 285, "text": "Syntax: os.listdir(path)" }, { "code": null, "e": 361, "s": 310, "text": "Parameters:path (optional) : path of the directory" }, { "code": null, "e": 495, "s": 361, "text": "Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list." }, { "code": null, "e": 531, "s": 495, "text": "Code #1: use of os.listdir() method" }, { "code": "# Python program to explain os.listdir() method # importing os module import os # Get the list of all files and directories# in the root directorypath = \"/\"dir_list = os.listdir(path) print(\"Files and directories in '\", path, \"' :\") # print the listprint(dir_list)", "e": 804, "s": 531, "text": null }, { "code": null, "e": 974, "s": 804, "text": "Files and directories in ' / ' :\n['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr', \n'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']\n" }, { "code": null, "e": 1011, "s": 974, "text": " Code #2: use of os.listdir() method" }, { "code": "# Python program to explain os.listdir() method # importing os module import os # Get the path of current working directorypath = os.getcwd() # Get the list of all files and directories# in current working directorydir_list = os.listdir(path) print(\"Files and directories in '\", path, \"' :\") # print the listprint(dir_list)", "e": 1344, "s": 1011, "text": null }, { "code": null, "e": 1859, "s": 1344, "text": "Files and directories in ' /home/ihritik ' :\n['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public',\n'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music', \n'.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local', \n'.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates',\n'.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images', \n'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks']\n" }, { "code": null, "e": 1893, "s": 1859, "text": " Code #3: omitting path parameter" }, { "code": "# Python program to explain os.listdir() method # importing os module import os # If we do not specify any path# os.listdir() method will return# the list of all files and directories# in current working directory dir_list = os.listdir() print(\"Files and directories in current working directory :\") # print the listprint(dir_list)", "e": 2236, "s": 1893, "text": null }, { "code": null, "e": 2759, "s": 2236, "text": "Files and directories in current working directory :\n['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public',\n'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music', \n'.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local', \n'.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates',\n'.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images', \n'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks']\n" }, { "code": null, "e": 2954, "s": 2759, "text": "As we can see the output of Code #2 and Code #3 are same. So if we omit the path parameter os.listdir() method will return the list of all files and directories in the current working directory." }, { "code": null, "e": 2971, "s": 2954, "text": "python-os-module" }, { "code": null, "e": 2978, "s": 2971, "text": "Python" } ]
numpy.argsort() in Python
16 Jun, 2022 numpy.argsort() function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the array. Syntax : numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None) Parameters : arr : [array_like] Input array. axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : [‘quicksort’, ‘mergesort’, ‘heapsort’]Selection algorithm. Default is ‘quicksort’. order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc. Return : [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr. Code #1 : Python3 # Python program explaining# argpartition() function import numpy as geek # input arrayin_arr = geek.array([ 2, 0, 1, 5, 4, 1, 9])print ("Input unsorted array : ", in_arr) out_arr = geek.argsort(in_arr)print ("Output sorted array indices : ", out_arr)print("Output sorted array : ", in_arr[out_arr]) Input unsorted array : [2 0 1 5 4 1 9] Output sorted array indices : [1 2 5 0 4 3 6] Output sorted array : [0 1 1 2 4 5 9] Code #2 : Python3 # Python program explaining# argpartition() function import numpy as geek # input 2d arrayin_arr = geek.array([[ 2, 0, 1], [ 5, 4, 3]])print ("Input array : ", in_arr) # output sorted array indicesout_arr1 = geek.argsort(in_arr, kind ='mergesort', axis = 0)print ("Output sorteded array indices along axis 0: ", out_arr1)out_arr2 = geek.argsort(in_arr, kind ='heapsort', axis = 1)print ("Output sorteded array indices along axis 1: ", out_arr2) Input array : [[2 0 1] [5 4 3]] Output sorteded array indices along axis 0: [[0 0 0] [1 1 1]] Output sorteded array indices along axis 1: [[1 2 0] [2 1 0]] sweetyty Python numpy-Sorting Searching Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 271, "s": 54, "text": "numpy.argsort() function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the array." }, { "code": null, "e": 917, "s": 271, "text": "Syntax : numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None) Parameters : arr : [array_like] Input array. axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : [‘quicksort’, ‘mergesort’, ‘heapsort’]Selection algorithm. Default is ‘quicksort’. order : [str or list of str] When arr is an array with fields defined, this argument specifies which fields to compare first, second, etc. Return : [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr." }, { "code": null, "e": 928, "s": 917, "text": "Code #1 : " }, { "code": null, "e": 936, "s": 928, "text": "Python3" }, { "code": "# Python program explaining# argpartition() function import numpy as geek # input arrayin_arr = geek.array([ 2, 0, 1, 5, 4, 1, 9])print (\"Input unsorted array : \", in_arr) out_arr = geek.argsort(in_arr)print (\"Output sorted array indices : \", out_arr)print(\"Output sorted array : \", in_arr[out_arr])", "e": 1238, "s": 936, "text": null }, { "code": null, "e": 1364, "s": 1238, "text": "Input unsorted array : [2 0 1 5 4 1 9]\nOutput sorted array indices : [1 2 5 0 4 3 6]\nOutput sorted array : [0 1 1 2 4 5 9]" }, { "code": null, "e": 1377, "s": 1364, "text": " Code #2 : " }, { "code": null, "e": 1385, "s": 1377, "text": "Python3" }, { "code": "# Python program explaining# argpartition() function import numpy as geek # input 2d arrayin_arr = geek.array([[ 2, 0, 1], [ 5, 4, 3]])print (\"Input array : \", in_arr) # output sorted array indicesout_arr1 = geek.argsort(in_arr, kind ='mergesort', axis = 0)print (\"Output sorteded array indices along axis 0: \", out_arr1)out_arr2 = geek.argsort(in_arr, kind ='heapsort', axis = 1)print (\"Output sorteded array indices along axis 1: \", out_arr2)", "e": 1830, "s": 1385, "text": null }, { "code": null, "e": 1992, "s": 1830, "text": "Input array : [[2 0 1]\n [5 4 3]]\nOutput sorteded array indices along axis 0: [[0 0 0]\n [1 1 1]]\nOutput sorteded array indices along axis 1: [[1 2 0]\n [2 1 0]]" }, { "code": null, "e": 2001, "s": 1992, "text": "sweetyty" }, { "code": null, "e": 2032, "s": 2001, "text": "Python numpy-Sorting Searching" }, { "code": null, "e": 2039, "s": 2032, "text": "Python" } ]
Python | Optional padding in list elements
05 Feb, 2019 In real world problems, we sometimes require to pad the element of list according to a condition that maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved. Method #1 : Using list comprehensionThis problem can be solved easily using the basic list comprehension in which we just need to use string formatting to perform the optional padding with 0 if size of each element is less than the specified size. # Python3 code to demonstrate # to perform list element padding# using list comprehension # initializing list test_list = [3, 54, 4, 1, 10] # printing original listprint ("The original list is : " + str(test_list)) # using list comprehension# to perform list element paddingres = ["%02d" %i for i in test_list] # printing result print ("The list after element padding " + str(res)) The original list is : [3, 54, 4, 1, 10] The list after element padding ['03', '54', '04', '01', '10'] Method #2 : Using str.rjust()There is a function dedicated in python to do this job. rjust() function does the task of specifying the size of the string and also takes the character in which the character has to be padded. # Python3 code to demonstrate # to perform list element padding# using str.rjust() # initializing list test_list = [3, 54, 4, 1, 10] # printing original listprint ("The original list is : " + str(test_list)) # using str.rjust()# to perform list element paddingres = [str(i).rjust(2, '0') for i in test_list] # printing result print ("The list after element padding " + str(res)) The original list is : [3, 54, 4, 1, 10] The list after element padding ['03', '54', '04', '01', '10'] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2019" }, { "code": null, "e": 370, "s": 28, "text": "In real world problems, we sometimes require to pad the element of list according to a condition that maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved." }, { "code": null, "e": 618, "s": 370, "text": "Method #1 : Using list comprehensionThis problem can be solved easily using the basic list comprehension in which we just need to use string formatting to perform the optional padding with 0 if size of each element is less than the specified size." }, { "code": "# Python3 code to demonstrate # to perform list element padding# using list comprehension # initializing list test_list = [3, 54, 4, 1, 10] # printing original listprint (\"The original list is : \" + str(test_list)) # using list comprehension# to perform list element paddingres = [\"%02d\" %i for i in test_list] # printing result print (\"The list after element padding \" + str(res))", "e": 1006, "s": 618, "text": null }, { "code": null, "e": 1110, "s": 1006, "text": "The original list is : [3, 54, 4, 1, 10]\nThe list after element padding ['03', '54', '04', '01', '10']\n" }, { "code": null, "e": 1334, "s": 1110, "text": " Method #2 : Using str.rjust()There is a function dedicated in python to do this job. rjust() function does the task of specifying the size of the string and also takes the character in which the character has to be padded." }, { "code": "# Python3 code to demonstrate # to perform list element padding# using str.rjust() # initializing list test_list = [3, 54, 4, 1, 10] # printing original listprint (\"The original list is : \" + str(test_list)) # using str.rjust()# to perform list element paddingres = [str(i).rjust(2, '0') for i in test_list] # printing result print (\"The list after element padding \" + str(res))", "e": 1719, "s": 1334, "text": null }, { "code": null, "e": 1823, "s": 1719, "text": "The original list is : [3, 54, 4, 1, 10]\nThe list after element padding ['03', '54', '04', '01', '10']\n" }, { "code": null, "e": 1844, "s": 1823, "text": "Python list-programs" }, { "code": null, "e": 1856, "s": 1844, "text": "python-list" }, { "code": null, "e": 1863, "s": 1856, "text": "Python" }, { "code": null, "e": 1879, "s": 1863, "text": "Python Programs" }, { "code": null, "e": 1891, "s": 1879, "text": "python-list" } ]
Find the Number which contain the digit d
25 May, 2022 Given two integer number n and d. The task is to find the number between 0 to n which contain the specific digit d. Examples: Input : n = 20 d = 5 Output : 5 15 Input : n = 50 d = 2 Output : 2 12 20 21 22 23 24 25 26 27 28 29 32 42 Approach 1: Take a loop from 0 to n and check each number one by one, if the number contains digit d then print it otherwise increase the number. Continue this process until loop ended. C++ Java Python3 C# PHP Javascript // C++ program to print the number which// contain the digit d from 0 to n#include <bits/stdc++.h>using namespace std; // Returns true if d is present as digit// in number x.bool isDigitPresent(int x, int d){ // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0);} // function to display the valuesvoid printNumbers(int n, int d){ // Check all numbers one by one for (int i = 0; i <= n; i++) // checking for digit if (i == d || isDigitPresent(i, d)) cout << i << " ";} // Driver codeint main(){ int n = 47, d = 7; printNumbers(n, d); return 0;} // Java program to print the number which// contain the digit d from 0 to n class GFG{ // Returns true if d is present as digit // in number x. static boolean isDigitPresent(int x, int d) { // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0); } // function to display the values static void printNumbers(int n, int d) { // Check all numbers one by one for (int i = 0; i <= n; i++) // checking for digit if (i == d || isDigitPresent(i, d)) System.out.print(i + " "); } // Driver code public static void main(String[] args) { int n = 47, d = 7; printNumbers(n, d); }} # Python3 program to print the number which# contain the digit d from 0 to n # Returns true if d is present as digit# in number x.def isDigitPresent(x, d): # Break loop if d is present as digit while (x > 0): if (x % 10 == d): break x = x / 10 # If loop broke return (x > 0) # function to display the valuesdef printNumbers(n, d): # Check all numbers one by one for i in range(0, n+1): # checking for digit if (i == d or isDigitPresent(i, d)): print(i,end=" ") # Driver coden = 47d = 7print("The number of values are")printNumbers(n, d)#This code is contributed by#Smitha Dinesh Semwal // C# program to print the number which// contain the digit d from 0 to nusing System; class GFG { // Returns true if d is present as digit // in number x. static bool isDigitPresent(int x, int d) { // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0); } // function to display the values static void printNumbers(int n, int d) { // Check all numbers one by one for (int i = 0; i <= n; i++) // checking for digit if (i == d || isDigitPresent(i, d)) Console.Write(i + " "); } // Driver code public static void Main() { int n = 47, d = 7; printNumbers(n, d); }} // This code contribute by parashar. <?php// PHP program to print the number which// contain the digit d from 0 to n // Returns true if d is present as digit// in number x.function isDigitPresent($x, $d){ // Break loop if d is // present as digit while ($x > 0) { if ($x % 10 == $d) break; $x = $x / 10; } // If loop broke return ($x > 0);} // function to display the valuesfunction printNumbers($n, $d){ // Check all numbers one by one for ($i = 0; $i <= $n; $i++) // checking for digit if ($i == $d || isDigitPresent($i, $d)) echo $i , " ";} // Driver Code $n = 47; $d = 7; printNumbers($n, $d); // This code contributed by ajit.?> <script> // JavaScript program to print the number which// contain the digit d from 0 to n // Returns true if d is present as digit// in number x.function isDigitPresent(x, d){ // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0);} // Function to display the valuesfunction printNumbers(n, d){ // Check all numbers one by one for(let i = 0; i <= n; i++) // Checking for digit if (i == d || isDigitPresent(i, d)) document.write(i + " ");} // Driver codelet n = 47, d = 7; printNumbers(n, d); // This code is contributed by splevel62 </script> The number of values are 7 17 27 37 47 Approach 2: This approach uses every number as a String and checks digit is present or not. This approach use of String.indexOf() function to check if the character is present in the string or not.String.indexOf() >= 0 means character is present and String.indexOf() = -1 means character is not present C++ Java Python3 C# Javascript // CPP program to print the number which// contain the digit d from 0 to n#include<bits/stdc++.h>using namespace std; // function to display the valuesvoid printNumbers(int n, int d){ // Converting d to character string st = ""; st += to_string(d); char ch = st[0]; string p = ""; p += ch; // Loop to check each digit one by one. for (int i = 0; i <= n; i++) { // initialize the string st = ""; st = st + to_string(i); int idx = st.find(p); // checking for digit if (i == d || idx!=-1) cout << (i) << " "; }} // Driver codeint main(){ int n = 100, d = 5; printNumbers(n, d);} // This code is contributed by// Surendra_Gangwar // Java program to print the number which// contain the digit d from 0 to n public class GFG { // function to display the values static void printNumbers(int n, int d) { // Converting d to character String st = "" + d; char ch = st.charAt(0); // Loop to check each digit one by one. for (int i = 0; i <= n; i++) { // initialize the string st = ""; st = st + i; // checking for digit if (i == d || st.indexOf(ch) >= 0) System.out.print(i + " "); } } // Driver code public static void main(String[] args) { int n = 100, d = 5; printNumbers(n, d); }} # Python 3 program to print the number# which contain the digit d from 0 to n def index(st, ch): for i in range(len(st)): if(st[i] == ch): return i; return -1 # function to display the valuesdef printNumbers(n, d): # Converting d to character st = "" + str(d) ch = st[0] # Loop to check each digit one by one. for i in range(0, n + 1, 1): # initialize the string st = "" st = st + str(i) # checking for digit if (i == d or index(st, ch) >= 0): print(i, end = " ") # Driver codeif __name__ == '__main__': n = 100 d = 5 printNumbers(n, d) # This code is contributed by# Shashank_Sharma // C# program to print the number which// contain the digit d from 0 to nusing System; class GFG{ // function to display the values static void printNumbers(int n, int d) { // Converting d to character String st = "" + d; char ch = st[0]; // Loop to check each digit one by one. for (int i = 0; i < n; i++) { // initialize the string st = ""; st = st + i; // checking for digit if (i == d || st.IndexOf(ch) >= 0) Console.Write(i + " "); } } // Driver code public static void Main() { int n = 100, d = 5; printNumbers(n, d); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to print the number which// contain the digit d from 0 to n // Function to display the valuesfunction printNumbers(n, d){ // Converting d to character let st = "" + d; let ch = st[0]; // Loop to check each digit one by one. for(let i = 0; i < n; i++) { // Initialize the string st = ""; st = st + i; // Checking for digit if (i == d || st.indexOf(ch) >= 0) document.write(i + " "); }} // Driver codelet n = 100, d = 5; printNumbers(n, d); // This code is contributed by decode2207 </script> 5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95 Smitha Dinesh Semwal parashar jit_t Shashank_Sharma princiraj1992 SURENDRA_GANGWAR splevel62 decode2207 simmytarika5 surinderdawra388 Java-Strings number-digits Numbers Mathematical Strings Java-Strings Strings Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2022" }, { "code": null, "e": 170, "s": 54, "text": "Given two integer number n and d. The task is to find the number between 0 to n which contain the specific digit d." }, { "code": null, "e": 181, "s": 170, "text": "Examples: " }, { "code": null, "e": 305, "s": 181, "text": "Input : n = 20\n d = 5\nOutput : 5 15\n\nInput : n = 50\n d = 2\nOutput : 2 12 20 21 22 23 24 25 26 27 28 29 32 42 " }, { "code": null, "e": 491, "s": 305, "text": "Approach 1: Take a loop from 0 to n and check each number one by one, if the number contains digit d then print it otherwise increase the number. Continue this process until loop ended." }, { "code": null, "e": 495, "s": 491, "text": "C++" }, { "code": null, "e": 500, "s": 495, "text": "Java" }, { "code": null, "e": 508, "s": 500, "text": "Python3" }, { "code": null, "e": 511, "s": 508, "text": "C#" }, { "code": null, "e": 515, "s": 511, "text": "PHP" }, { "code": null, "e": 526, "s": 515, "text": "Javascript" }, { "code": "// C++ program to print the number which// contain the digit d from 0 to n#include <bits/stdc++.h>using namespace std; // Returns true if d is present as digit// in number x.bool isDigitPresent(int x, int d){ // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0);} // function to display the valuesvoid printNumbers(int n, int d){ // Check all numbers one by one for (int i = 0; i <= n; i++) // checking for digit if (i == d || isDigitPresent(i, d)) cout << i << \" \";} // Driver codeint main(){ int n = 47, d = 7; printNumbers(n, d); return 0;}", "e": 1228, "s": 526, "text": null }, { "code": "// Java program to print the number which// contain the digit d from 0 to n class GFG{ // Returns true if d is present as digit // in number x. static boolean isDigitPresent(int x, int d) { // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0); } // function to display the values static void printNumbers(int n, int d) { // Check all numbers one by one for (int i = 0; i <= n; i++) // checking for digit if (i == d || isDigitPresent(i, d)) System.out.print(i + \" \"); } // Driver code public static void main(String[] args) { int n = 47, d = 7; printNumbers(n, d); }}", "e": 2056, "s": 1228, "text": null }, { "code": "# Python3 program to print the number which# contain the digit d from 0 to n # Returns true if d is present as digit# in number x.def isDigitPresent(x, d): # Break loop if d is present as digit while (x > 0): if (x % 10 == d): break x = x / 10 # If loop broke return (x > 0) # function to display the valuesdef printNumbers(n, d): # Check all numbers one by one for i in range(0, n+1): # checking for digit if (i == d or isDigitPresent(i, d)): print(i,end=\" \") # Driver coden = 47d = 7print(\"The number of values are\")printNumbers(n, d)#This code is contributed by#Smitha Dinesh Semwal", "e": 2726, "s": 2056, "text": null }, { "code": "// C# program to print the number which// contain the digit d from 0 to nusing System; class GFG { // Returns true if d is present as digit // in number x. static bool isDigitPresent(int x, int d) { // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0); } // function to display the values static void printNumbers(int n, int d) { // Check all numbers one by one for (int i = 0; i <= n; i++) // checking for digit if (i == d || isDigitPresent(i, d)) Console.Write(i + \" \"); } // Driver code public static void Main() { int n = 47, d = 7; printNumbers(n, d); }} // This code contribute by parashar.", "e": 3616, "s": 2726, "text": null }, { "code": "<?php// PHP program to print the number which// contain the digit d from 0 to n // Returns true if d is present as digit// in number x.function isDigitPresent($x, $d){ // Break loop if d is // present as digit while ($x > 0) { if ($x % 10 == $d) break; $x = $x / 10; } // If loop broke return ($x > 0);} // function to display the valuesfunction printNumbers($n, $d){ // Check all numbers one by one for ($i = 0; $i <= $n; $i++) // checking for digit if ($i == $d || isDigitPresent($i, $d)) echo $i , \" \";} // Driver Code $n = 47; $d = 7; printNumbers($n, $d); // This code contributed by ajit.?>", "e": 4320, "s": 3616, "text": null }, { "code": "<script> // JavaScript program to print the number which// contain the digit d from 0 to n // Returns true if d is present as digit// in number x.function isDigitPresent(x, d){ // Break loop if d is present as digit while (x > 0) { if (x % 10 == d) break; x = x / 10; } // If loop broke return (x > 0);} // Function to display the valuesfunction printNumbers(n, d){ // Check all numbers one by one for(let i = 0; i <= n; i++) // Checking for digit if (i == d || isDigitPresent(i, d)) document.write(i + \" \");} // Driver codelet n = 47, d = 7; printNumbers(n, d); // This code is contributed by splevel62 </script>", "e": 5030, "s": 4320, "text": null }, { "code": null, "e": 5069, "s": 5030, "text": "The number of values are\n7 17 27 37 47" }, { "code": null, "e": 5375, "s": 5071, "text": "Approach 2: This approach uses every number as a String and checks digit is present or not. This approach use of String.indexOf() function to check if the character is present in the string or not.String.indexOf() >= 0 means character is present and String.indexOf() = -1 means character is not present " }, { "code": null, "e": 5379, "s": 5375, "text": "C++" }, { "code": null, "e": 5384, "s": 5379, "text": "Java" }, { "code": null, "e": 5392, "s": 5384, "text": "Python3" }, { "code": null, "e": 5395, "s": 5392, "text": "C#" }, { "code": null, "e": 5406, "s": 5395, "text": "Javascript" }, { "code": "// CPP program to print the number which// contain the digit d from 0 to n#include<bits/stdc++.h>using namespace std; // function to display the valuesvoid printNumbers(int n, int d){ // Converting d to character string st = \"\"; st += to_string(d); char ch = st[0]; string p = \"\"; p += ch; // Loop to check each digit one by one. for (int i = 0; i <= n; i++) { // initialize the string st = \"\"; st = st + to_string(i); int idx = st.find(p); // checking for digit if (i == d || idx!=-1) cout << (i) << \" \"; }} // Driver codeint main(){ int n = 100, d = 5; printNumbers(n, d);} // This code is contributed by// Surendra_Gangwar", "e": 6186, "s": 5406, "text": null }, { "code": "// Java program to print the number which// contain the digit d from 0 to n public class GFG { // function to display the values static void printNumbers(int n, int d) { // Converting d to character String st = \"\" + d; char ch = st.charAt(0); // Loop to check each digit one by one. for (int i = 0; i <= n; i++) { // initialize the string st = \"\"; st = st + i; // checking for digit if (i == d || st.indexOf(ch) >= 0) System.out.print(i + \" \"); } } // Driver code public static void main(String[] args) { int n = 100, d = 5; printNumbers(n, d); }}", "e": 6933, "s": 6186, "text": null }, { "code": "# Python 3 program to print the number# which contain the digit d from 0 to n def index(st, ch): for i in range(len(st)): if(st[i] == ch): return i; return -1 # function to display the valuesdef printNumbers(n, d): # Converting d to character st = \"\" + str(d) ch = st[0] # Loop to check each digit one by one. for i in range(0, n + 1, 1): # initialize the string st = \"\" st = st + str(i) # checking for digit if (i == d or index(st, ch) >= 0): print(i, end = \" \") # Driver codeif __name__ == '__main__': n = 100 d = 5 printNumbers(n, d) # This code is contributed by# Shashank_Sharma", "e": 7635, "s": 6933, "text": null }, { "code": "// C# program to print the number which// contain the digit d from 0 to nusing System; class GFG{ // function to display the values static void printNumbers(int n, int d) { // Converting d to character String st = \"\" + d; char ch = st[0]; // Loop to check each digit one by one. for (int i = 0; i < n; i++) { // initialize the string st = \"\"; st = st + i; // checking for digit if (i == d || st.IndexOf(ch) >= 0) Console.Write(i + \" \"); } } // Driver code public static void Main() { int n = 100, d = 5; printNumbers(n, d); }} /* This code contributed by PrinciRaj1992 */", "e": 8410, "s": 7635, "text": null }, { "code": "<script> // Javascript program to print the number which// contain the digit d from 0 to n // Function to display the valuesfunction printNumbers(n, d){ // Converting d to character let st = \"\" + d; let ch = st[0]; // Loop to check each digit one by one. for(let i = 0; i < n; i++) { // Initialize the string st = \"\"; st = st + i; // Checking for digit if (i == d || st.indexOf(ch) >= 0) document.write(i + \" \"); }} // Driver codelet n = 100, d = 5; printNumbers(n, d); // This code is contributed by decode2207 </script>", "e": 9031, "s": 8410, "text": null }, { "code": null, "e": 9087, "s": 9031, "text": "5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95" }, { "code": null, "e": 9110, "s": 9089, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 9119, "s": 9110, "text": "parashar" }, { "code": null, "e": 9125, "s": 9119, "text": "jit_t" }, { "code": null, "e": 9141, "s": 9125, "text": "Shashank_Sharma" }, { "code": null, "e": 9155, "s": 9141, "text": "princiraj1992" }, { "code": null, "e": 9172, "s": 9155, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 9182, "s": 9172, "text": "splevel62" }, { "code": null, "e": 9193, "s": 9182, "text": "decode2207" }, { "code": null, "e": 9206, "s": 9193, "text": "simmytarika5" }, { "code": null, "e": 9223, "s": 9206, "text": "surinderdawra388" }, { "code": null, "e": 9236, "s": 9223, "text": "Java-Strings" }, { "code": null, "e": 9250, "s": 9236, "text": "number-digits" }, { "code": null, "e": 9258, "s": 9250, "text": "Numbers" }, { "code": null, "e": 9271, "s": 9258, "text": "Mathematical" }, { "code": null, "e": 9279, "s": 9271, "text": "Strings" }, { "code": null, "e": 9292, "s": 9279, "text": "Java-Strings" }, { "code": null, "e": 9300, "s": 9292, "text": "Strings" }, { "code": null, "e": 9313, "s": 9300, "text": "Mathematical" }, { "code": null, "e": 9321, "s": 9313, "text": "Numbers" } ]
Introduction to TensorFlow
04 Sep, 2018 This article is a brief introduction to TensorFlow library using Python programming language. Introduction TensorFlow is an open-source software library. TensorFlow was originally developed by researchers and engineers working on the Google Brain Team within Google’s Machine Intelligence research organization for the purposes of conducting machine learning and deep neural networks research, but the system is general enough to be applicable in a wide variety of other domains as well! Let us first try to understand what the word TensorFlow actually mean! TensorFlow is basically a software library for numerical computation using data flow graphs where: nodes in the graph represent mathematical operations. edges in the graph represent the multidimensional data arrays (called tensors) communicated between them. (Please note that tensor is the central unit of data in TensorFlow). Consider the diagram given below: Here, add is a node which represents addition operation. a and b are input tensors and c is the resultant tensor. This flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API! TensorFlow APIs TensorFlow provides multiple APIs (Application Programming Interfaces). These can be classified into 2 major categories: Low level API:complete programming controlrecommended for machine learning researchersprovides fine levels of control over the modelsTensorFlow Core is the low level API of TensorFlow.High level API:built on top of TensorFlow Coreeasier to learn and use than TensorFlow Coremake repetitive tasks easier and more consistent between different userstf.contrib.learn is an example of a high level API. Low level API:complete programming controlrecommended for machine learning researchersprovides fine levels of control over the modelsTensorFlow Core is the low level API of TensorFlow. complete programming control recommended for machine learning researchers provides fine levels of control over the models TensorFlow Core is the low level API of TensorFlow. High level API:built on top of TensorFlow Coreeasier to learn and use than TensorFlow Coremake repetitive tasks easier and more consistent between different userstf.contrib.learn is an example of a high level API. built on top of TensorFlow Core easier to learn and use than TensorFlow Core make repetitive tasks easier and more consistent between different users tf.contrib.learn is an example of a high level API. In this article, we first discuss the basics of TensorFlow Core and then explore the higher level API, tf.contrib.learn. TensorFlow Core 1. Installing TensorFlow An easy to follow guide for TensorFlow installation is available here:Installing TensorFlow. Once installed, you can ensure a successful installation by running this command in python interpreter: import tensorflow as tf 2. The Computational Graph Any TensorFlow Core program can be divided into two discrete sections: Building the computational graph.A computational graph is nothing but a series of TensorFlow operations arranged into a graph of nodes. Running the computational graph.To actually evaluate the nodes, we must run the computational graph within a session. A session encapsulates the control and state of the TensorFlow runtime. Now, let us write our very first TensorFlow program to understand above concept: # importing tensorflowimport tensorflow as tf # creating nodes in computation graphnode1 = tf.constant(3, dtype=tf.int32)node2 = tf.constant(5, dtype=tf.int32)node3 = tf.add(node1, node2) # create tensorflow session objectsess = tf.Session() # evaluating node3 and printing the resultprint("Sum of node1 and node2 is:",sess.run(node3)) # closing the sessionsess.close() Output: Sum of node1 and node2 is: 8 Let us try to understand above code: Step 1 : Create a computational graphBy creating computational graph, we mean defining the nodes. Tensorflow provides different types of nodes for a variety of tasks. Each node takes zero or more tensors as inputs and produces a tensor as an output.In above program, the nodes node1 and node2 are of tf.constant type. A constant node takes no inputs, and it outputs a value it stores internally. Note that we can also specify the data type of output tensor using dtype argument.node1 = tf.constant(3, dtype=tf.int32) node2 = tf.constant(5, dtype=tf.int32) node3 is of tf.add type. It takes two tensors as input and returns their sum as output tensor.node3 = tf.add(node1, node2) In above program, the nodes node1 and node2 are of tf.constant type. A constant node takes no inputs, and it outputs a value it stores internally. Note that we can also specify the data type of output tensor using dtype argument.node1 = tf.constant(3, dtype=tf.int32) node2 = tf.constant(5, dtype=tf.int32) node1 = tf.constant(3, dtype=tf.int32) node2 = tf.constant(5, dtype=tf.int32) node3 is of tf.add type. It takes two tensors as input and returns their sum as output tensor.node3 = tf.add(node1, node2) node3 = tf.add(node1, node2) Step 2 : Run the computational graphIn order to run the computational graph, we need to create a session. To create a session, we simply do:sess = tf.Session() Now, we can invoke the run method of session object to perform computations on any node:print("Sum of node1 and node2 is:",sess.run(node3)) Here, node3 gets evaluated which further invokes node1 and node2. Finally, we close the session using:sess.close() sess = tf.Session() Now, we can invoke the run method of session object to perform computations on any node: print("Sum of node1 and node2 is:",sess.run(node3)) Here, node3 gets evaluated which further invokes node1 and node2. Finally, we close the session using: sess.close() Note: Another(and better) method of working with sessions is to use with block like this: with tf.Session() as sess: print("Sum of node1 and node2 is:",sess.run(node3)) The benefit of this approach is that you do not need to close the session explicitly as it gets automatically closed once control goes out of the scope of with block. 3. Variables TensorFlow has Variable nodes too which can hold variable data. They are mainly used to hold and update parameters of a training model. Variables are in-memory buffers containing tensors. They must be explicitly initialized and can be saved to disk during and after training. You can later restore saved values to exercise or analyze the model. An important difference to note between a constant and Variable is: A constant’s value is stored in the graph and its value is replicated wherever the graph is loaded. A variable is stored separately, and may live on a parameter server. Given below is an example using Variable: # importing tensorflowimport tensorflow as tf # creating nodes in computation graphnode = tf.Variable(tf.zeros([2,2])) # running computation graphwith tf.Session() as sess: # initialize all global variables sess.run(tf.global_variables_initializer()) # evaluating node print("Tensor value before addition:\n",sess.run(node)) # elementwise addition to tensor node = node.assign(node + tf.ones([2,2])) # evaluate node again print("Tensor value after addition:\n", sess.run(node)) Output: Tensor value before addition: [[ 0. 0.] [ 0. 0.]] Tensor value after addition: [[ 1. 1.] [ 1. 1.]] In above program: We define a node of type Variable and assign it some initial value.node = tf.Variable(tf.zeros([2,2])) node = tf.Variable(tf.zeros([2,2])) To initialize the variable node in current session’s scope, we do:sess.run(tf.global_variables_initializer()) sess.run(tf.global_variables_initializer()) To assign a new value to a variable node, we can use assign method like this:node = node.assign(node + tf.ones([2,2])) node = node.assign(node + tf.ones([2,2])) 4. Placeholders A graph can be parameterized to accept external inputs, known as placeholders. A placeholder is a promise to provide a value later. While evaluating the graph involving placeholder nodes, a feed_dict parameter is passed to the session’s run method to specify Tensors that provide concrete values to these placeholders. Consider the example given below: # importing tensorflowimport tensorflow as tf # creating nodes in computation grapha = tf.placeholder(tf.int32, shape=(3,1))b = tf.placeholder(tf.int32, shape=(1,3))c = tf.matmul(a,b) # running computation graphwith tf.Session() as sess: print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]})) Output: [[3 6 9] [2 4 6] [1 2 3]] Let us try to understand above program: We define placeholder nodes a and b like this:a = tf.placeholder(tf.int32, shape=(3,1)) b = tf.placeholder(tf.int32, shape=(1,3)) The first argument is the data type of the tensor and one of the optional argument is shape of the tensor. a = tf.placeholder(tf.int32, shape=(3,1)) b = tf.placeholder(tf.int32, shape=(1,3)) The first argument is the data type of the tensor and one of the optional argument is shape of the tensor. We define another node c which does the operation of matrix multiplication (matmul). We pass the two placeholder nodes as argument.c = tf.matmul(a,b) c = tf.matmul(a,b) Finally, when we run the session, we pass the value of placeholder nodes in feed_dict argument of sess.run:print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]})) Consider the diagrams shown below to clear the concept: print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]})) Consider the diagrams shown below to clear the concept: Initially: After sess.run: Given below is an implementation of a Linear Regression model using TensorFlow Core API. # importing the dependenciesimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt # Model Parameterslearning_rate = 0.01training_epochs = 2000display_step = 200 # Training Datatrain_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167, 7.042,10.791,5.313,7.997,5.654,9.27,3.1])train_y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221, 2.827,3.465,1.65,2.904,2.42,2.94,1.3])n_samples = train_X.shape[0] # Test Datatest_X = np.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])test_y = np.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03]) # Set placeholders for feature and target vectorsX = tf.placeholder(tf.float32)y = tf.placeholder(tf.float32) # Set model weights and biasW = tf.Variable(np.random.randn(), name="weight")b = tf.Variable(np.random.randn(), name="bias") # Construct a linear modellinear_model = W*X + b # Mean squared errorcost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples) # Gradient descentoptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Initializing the variablesinit = tf.global_variables_initializer() # Launch the graphwith tf.Session() as sess: # Load initialized variables in current session sess.run(init) # Fit all training data for epoch in range(training_epochs): # perform gradient descent step sess.run(optimizer, feed_dict={X: train_X, y: train_y}) # Display logs per epoch step if (epoch+1) % display_step == 0: c = sess.run(cost, feed_dict={X: train_X, y: train_y}) print("Epoch:{0:6} \t Cost:{1:10.4} \t W:{2:6.4} \t b:{3:6.4}". format(epoch+1, c, sess.run(W), sess.run(b))) # Print final parameter values print("Optimization Finished!") training_cost = sess.run(cost, feed_dict={X: train_X, y: train_y}) print("Final training cost:", training_cost, "W:", sess.run(W), "b:", sess.run(b), '\n') # Graphic display plt.plot(train_X, train_y, 'ro', label='Original data') plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') plt.legend() plt.show() # Testing the model testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]), feed_dict={X: test_X, y: test_y}) print("Final testing cost:", testing_cost) print("Absolute mean square loss difference:", abs(training_cost - testing_cost)) # Display fitted line on test data plt.plot(test_X, test_y, 'bo', label='Testing data') plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') plt.legend() plt.show() Epoch: 200 Cost: 0.1715 W: 0.426 b:-0.4371 Epoch: 400 Cost: 0.1351 W:0.3884 b:-0.1706 Epoch: 600 Cost: 0.1127 W:0.3589 b:0.03849 Epoch: 800 Cost: 0.09894 W:0.3358 b:0.2025 Epoch: 1000 Cost: 0.09047 W:0.3176 b:0.3311 Epoch: 1200 Cost: 0.08526 W:0.3034 b:0.4319 Epoch: 1400 Cost: 0.08205 W:0.2922 b:0.5111 Epoch: 1600 Cost: 0.08008 W:0.2835 b:0.5731 Epoch: 1800 Cost: 0.07887 W:0.2766 b:0.6218 Epoch: 2000 Cost: 0.07812 W:0.2712 b: 0.66 Optimization Finished! Final training cost: 0.0781221 W: 0.271219 b: 0.65996 Final testing cost: 0.0756337 Absolute mean square loss difference: 0.00248838 Let us try to understand the above code. First of all, we define some parameters for training our model, like:learning_rate = 0.01 training_epochs = 2000 display_step = 200 learning_rate = 0.01 training_epochs = 2000 display_step = 200 Then we define placeholder nodes for feature and target vector.X = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) X = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) Then, we define variable nodes for weight and bias.W = tf.Variable(np.random.randn(), name="weight") b = tf.Variable(np.random.randn(), name="bias") W = tf.Variable(np.random.randn(), name="weight") b = tf.Variable(np.random.randn(), name="bias") linear_model is an operational node which calculates the hypothesis for the linear regression model.linear_model = W*X + b linear_model = W*X + b Loss (or cost) per gradient descent is calculated as the mean squared error and its node is defined as:cost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples) cost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples) Finally, we have the optimizer node which implements the Gradient Descent Algorithm.optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) Now, the training data is fit into the linear model by applying the Gradient Descent Algorithm. The task is repeated training_epochs number of times. In each epoch, we perform the gradient descent step like this:sess.run(optimizer, feed_dict={X: train_X, y: train_y}) sess.run(optimizer, feed_dict={X: train_X, y: train_y}) After every display_step number of epochs, we print the value of current loss which is found using:c = sess.run(cost, feed_dict={X: train_X, y: train_y}) c = sess.run(cost, feed_dict={X: train_X, y: train_y}) The model is evaluated on test data and testing_cost is calculated using:testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]), feed_dict={X: test_X, y: test_y}) testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]), feed_dict={X: test_X, y: test_y}) tf.contrib.learn tf.contrib.learn is a high-level TensorFlow library that simplifies the mechanics of machine learning, including the following: running training loops running evaluation loops managing data sets managing feeding Let us try to see the implementation of Linear regression on same data we used above using tf.contrib.learn. # importing the dependenciesimport tensorflow as tfimport numpy as np # declaring list of featuresfeatures = [tf.contrib.layers.real_valued_column("X")] # creating a linear regression estimatorestimator = tf.contrib.learn.LinearRegressor(feature_columns=features) # training and test datatrain_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167, 7.042,10.791,5.313,7.997,5.654,9.27,3.1])train_y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221, 2.827,3.465,1.65,2.904,2.42,2.94,1.3])test_X = np.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])test_y = np.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03]) # function to feed dict of numpy arrays into the model for traininginput_fn = tf.contrib.learn.io.numpy_input_fn({"X":train_X}, train_y, batch_size=4, num_epochs=2000) # function to feed dict of numpy arrays into the model for testingtest_input_fn = tf.contrib.learn.io.numpy_input_fn({"X":test_X}, test_y) # fit training data into estimatorestimator.fit(input_fn=input_fn) # print value of weight and biasW = estimator.get_variable_value('linear/X/weight')[0][0]b = estimator.get_variable_value('linear/bias_weight')[0]print("W:", W, "\tb:", b) # evaluating the final losstrain_loss = estimator.evaluate(input_fn=input_fn)['loss']test_loss = estimator.evaluate(input_fn=test_input_fn)['loss']print("Final training loss:", train_loss)print("Final testing loss:", test_loss) W: 0.252928 b: 0.802972 Final training loss: 0.153998 Final testing loss: 0.0777036 Let us try to understand the above code. The shape and type of feature matrix is declared using a list. Each element of the list defines the structure of a column. In above example, we have only 1 feature which stores real values and has been given a name X.features = [tf.contrib.layers.real_valued_column("X")] features = [tf.contrib.layers.real_valued_column("X")] Then, we need an estimator. An estimator is nothing but a pre-defined model with many useful methods and parameters. In above example, we use a Linear Regression model estimator.estimator = tf.contrib.learn.LinearRegressor(feature_columns=features) estimator = tf.contrib.learn.LinearRegressor(feature_columns=features) For training purpose, we need to use an input function which is responsible for feeding data to estimator while training. It takes the feature column values as dictionary. Many other parameters like batch size, number of epochs, etc can be specified.input_fn = tf.contrib.learn.io.numpy_input_fn({"X":train_X}, train_y, batch_size=4, num_epochs=2000) input_fn = tf.contrib.learn.io.numpy_input_fn({"X":train_X}, train_y, batch_size=4, num_epochs=2000) To fit training data to estimator, we simply use fit method of estimator in which input function is passed as an argument.estimator.fit(input_fn=input_fn) estimator.fit(input_fn=input_fn) Once training is complete, we can get the value of different variables using get_variable_value method of estimator. You can get a list of all variables using get_variable_names method.W = estimator.get_variable_value('linear/X/weight')[0][0] b = estimator.get_variable_value('linear/bias_weight')[0] W = estimator.get_variable_value('linear/X/weight')[0][0] b = estimator.get_variable_value('linear/bias_weight')[0] The mean squared error/loss can be computed as:train_loss = estimator.evaluate(input_fn=input_fn)['loss'] test_loss = estimator.evaluate(input_fn=test_input_fn)['loss'] train_loss = estimator.evaluate(input_fn=input_fn)['loss'] test_loss = estimator.evaluate(input_fn=test_input_fn)['loss'] This brings us to the end of this Introduction to TensorFlow article! From here, you can try to explore this tutorial: MNIST For ML Beginners. This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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. Tensorflow GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Sep, 2018" }, { "code": null, "e": 146, "s": 52, "text": "This article is a brief introduction to TensorFlow library using Python programming language." }, { "code": null, "e": 159, "s": 146, "text": "Introduction" }, { "code": null, "e": 540, "s": 159, "text": "TensorFlow is an open-source software library. TensorFlow was originally developed by researchers and engineers working on the Google Brain Team within Google’s Machine Intelligence research organization for the purposes of conducting machine learning and deep neural networks research, but the system is general enough to be applicable in a wide variety of other domains as well!" }, { "code": null, "e": 611, "s": 540, "text": "Let us first try to understand what the word TensorFlow actually mean!" }, { "code": null, "e": 710, "s": 611, "text": "TensorFlow is basically a software library for numerical computation using data flow graphs where:" }, { "code": null, "e": 764, "s": 710, "text": "nodes in the graph represent mathematical operations." }, { "code": null, "e": 939, "s": 764, "text": "edges in the graph represent the multidimensional data arrays (called tensors) communicated between them. (Please note that tensor is the central unit of data in TensorFlow)." }, { "code": null, "e": 973, "s": 939, "text": "Consider the diagram given below:" }, { "code": null, "e": 1087, "s": 973, "text": "Here, add is a node which represents addition operation. a and b are input tensors and c is the resultant tensor." }, { "code": null, "e": 1233, "s": 1087, "text": "This flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API!" }, { "code": null, "e": 1249, "s": 1233, "text": "TensorFlow APIs" }, { "code": null, "e": 1370, "s": 1249, "text": "TensorFlow provides multiple APIs (Application Programming Interfaces). These can be classified into 2 major categories:" }, { "code": null, "e": 1768, "s": 1370, "text": "Low level API:complete programming controlrecommended for machine learning researchersprovides fine levels of control over the modelsTensorFlow Core is the low level API of TensorFlow.High level API:built on top of TensorFlow Coreeasier to learn and use than TensorFlow Coremake repetitive tasks easier and more consistent between different userstf.contrib.learn is an example of a high level API." }, { "code": null, "e": 1953, "s": 1768, "text": "Low level API:complete programming controlrecommended for machine learning researchersprovides fine levels of control over the modelsTensorFlow Core is the low level API of TensorFlow." }, { "code": null, "e": 1982, "s": 1953, "text": "complete programming control" }, { "code": null, "e": 2027, "s": 1982, "text": "recommended for machine learning researchers" }, { "code": null, "e": 2075, "s": 2027, "text": "provides fine levels of control over the models" }, { "code": null, "e": 2127, "s": 2075, "text": "TensorFlow Core is the low level API of TensorFlow." }, { "code": null, "e": 2341, "s": 2127, "text": "High level API:built on top of TensorFlow Coreeasier to learn and use than TensorFlow Coremake repetitive tasks easier and more consistent between different userstf.contrib.learn is an example of a high level API." }, { "code": null, "e": 2373, "s": 2341, "text": "built on top of TensorFlow Core" }, { "code": null, "e": 2418, "s": 2373, "text": "easier to learn and use than TensorFlow Core" }, { "code": null, "e": 2491, "s": 2418, "text": "make repetitive tasks easier and more consistent between different users" }, { "code": null, "e": 2543, "s": 2491, "text": "tf.contrib.learn is an example of a high level API." }, { "code": null, "e": 2664, "s": 2543, "text": "In this article, we first discuss the basics of TensorFlow Core and then explore the higher level API, tf.contrib.learn." }, { "code": null, "e": 2680, "s": 2664, "text": "TensorFlow Core" }, { "code": null, "e": 2705, "s": 2680, "text": "1. Installing TensorFlow" }, { "code": null, "e": 2798, "s": 2705, "text": "An easy to follow guide for TensorFlow installation is available here:Installing TensorFlow." }, { "code": null, "e": 2902, "s": 2798, "text": "Once installed, you can ensure a successful installation by running this command in python interpreter:" }, { "code": null, "e": 2926, "s": 2902, "text": "import tensorflow as tf" }, { "code": null, "e": 2953, "s": 2926, "text": "2. The Computational Graph" }, { "code": null, "e": 3024, "s": 2953, "text": "Any TensorFlow Core program can be divided into two discrete sections:" }, { "code": null, "e": 3160, "s": 3024, "text": "Building the computational graph.A computational graph is nothing but a series of TensorFlow operations arranged into a graph of nodes." }, { "code": null, "e": 3350, "s": 3160, "text": "Running the computational graph.To actually evaluate the nodes, we must run the computational graph within a session. A session encapsulates the control and state of the TensorFlow runtime." }, { "code": null, "e": 3431, "s": 3350, "text": "Now, let us write our very first TensorFlow program to understand above concept:" }, { "code": "# importing tensorflowimport tensorflow as tf # creating nodes in computation graphnode1 = tf.constant(3, dtype=tf.int32)node2 = tf.constant(5, dtype=tf.int32)node3 = tf.add(node1, node2) # create tensorflow session objectsess = tf.Session() # evaluating node3 and printing the resultprint(\"Sum of node1 and node2 is:\",sess.run(node3)) # closing the sessionsess.close()", "e": 3805, "s": 3431, "text": null }, { "code": null, "e": 3813, "s": 3805, "text": "Output:" }, { "code": null, "e": 3843, "s": 3813, "text": "Sum of node1 and node2 is: 8\n" }, { "code": null, "e": 3880, "s": 3843, "text": "Let us try to understand above code:" }, { "code": null, "e": 4560, "s": 3880, "text": "Step 1 : Create a computational graphBy creating computational graph, we mean defining the nodes. Tensorflow provides different types of nodes for a variety of tasks. Each node takes zero or more tensors as inputs and produces a tensor as an output.In above program, the nodes node1 and node2 are of tf.constant type. A constant node takes no inputs, and it outputs a value it stores internally. Note that we can also specify the data type of output tensor using dtype argument.node1 = tf.constant(3, dtype=tf.int32)\nnode2 = tf.constant(5, dtype=tf.int32)\nnode3 is of tf.add type. It takes two tensors as input and returns their sum as output tensor.node3 = tf.add(node1, node2)\n" }, { "code": null, "e": 4868, "s": 4560, "text": "In above program, the nodes node1 and node2 are of tf.constant type. A constant node takes no inputs, and it outputs a value it stores internally. Note that we can also specify the data type of output tensor using dtype argument.node1 = tf.constant(3, dtype=tf.int32)\nnode2 = tf.constant(5, dtype=tf.int32)\n" }, { "code": null, "e": 4947, "s": 4868, "text": "node1 = tf.constant(3, dtype=tf.int32)\nnode2 = tf.constant(5, dtype=tf.int32)\n" }, { "code": null, "e": 5071, "s": 4947, "text": "node3 is of tf.add type. It takes two tensors as input and returns their sum as output tensor.node3 = tf.add(node1, node2)\n" }, { "code": null, "e": 5101, "s": 5071, "text": "node3 = tf.add(node1, node2)\n" }, { "code": null, "e": 5517, "s": 5101, "text": "Step 2 : Run the computational graphIn order to run the computational graph, we need to create a session. To create a session, we simply do:sess = tf.Session()\nNow, we can invoke the run method of session object to perform computations on any node:print(\"Sum of node1 and node2 is:\",sess.run(node3))\nHere, node3 gets evaluated which further invokes node1 and node2. Finally, we close the session using:sess.close()\n" }, { "code": null, "e": 5538, "s": 5517, "text": "sess = tf.Session()\n" }, { "code": null, "e": 5627, "s": 5538, "text": "Now, we can invoke the run method of session object to perform computations on any node:" }, { "code": null, "e": 5680, "s": 5627, "text": "print(\"Sum of node1 and node2 is:\",sess.run(node3))\n" }, { "code": null, "e": 5783, "s": 5680, "text": "Here, node3 gets evaluated which further invokes node1 and node2. Finally, we close the session using:" }, { "code": null, "e": 5797, "s": 5783, "text": "sess.close()\n" }, { "code": null, "e": 5887, "s": 5797, "text": "Note: Another(and better) method of working with sessions is to use with block like this:" }, { "code": null, "e": 5971, "s": 5887, "text": "with tf.Session() as sess:\n print(\"Sum of node1 and node2 is:\",sess.run(node3))\n" }, { "code": null, "e": 6138, "s": 5971, "text": "The benefit of this approach is that you do not need to close the session explicitly as it gets automatically closed once control goes out of the scope of with block." }, { "code": null, "e": 6151, "s": 6138, "text": "3. Variables" }, { "code": null, "e": 6287, "s": 6151, "text": "TensorFlow has Variable nodes too which can hold variable data. They are mainly used to hold and update parameters of a training model." }, { "code": null, "e": 6496, "s": 6287, "text": "Variables are in-memory buffers containing tensors. They must be explicitly initialized and can be saved to disk during and after training. You can later restore saved values to exercise or analyze the model." }, { "code": null, "e": 6564, "s": 6496, "text": "An important difference to note between a constant and Variable is:" }, { "code": null, "e": 6733, "s": 6564, "text": "A constant’s value is stored in the graph and its value is replicated wherever the graph is loaded. A variable is stored separately, and may live on a parameter server." }, { "code": null, "e": 6775, "s": 6733, "text": "Given below is an example using Variable:" }, { "code": "# importing tensorflowimport tensorflow as tf # creating nodes in computation graphnode = tf.Variable(tf.zeros([2,2])) # running computation graphwith tf.Session() as sess: # initialize all global variables sess.run(tf.global_variables_initializer()) # evaluating node print(\"Tensor value before addition:\\n\",sess.run(node)) # elementwise addition to tensor node = node.assign(node + tf.ones([2,2])) # evaluate node again print(\"Tensor value after addition:\\n\", sess.run(node))", "e": 7288, "s": 6775, "text": null }, { "code": null, "e": 7296, "s": 7288, "text": "Output:" }, { "code": null, "e": 7404, "s": 7296, "text": "Tensor value before addition:\n [[ 0. 0.]\n [ 0. 0.]]\nTensor value after addition:\n [[ 1. 1.]\n [ 1. 1.]]\n" }, { "code": null, "e": 7422, "s": 7404, "text": "In above program:" }, { "code": null, "e": 7526, "s": 7422, "text": "We define a node of type Variable and assign it some initial value.node = tf.Variable(tf.zeros([2,2]))\n" }, { "code": null, "e": 7563, "s": 7526, "text": "node = tf.Variable(tf.zeros([2,2]))\n" }, { "code": null, "e": 7674, "s": 7563, "text": "To initialize the variable node in current session’s scope, we do:sess.run(tf.global_variables_initializer())\n" }, { "code": null, "e": 7719, "s": 7674, "text": "sess.run(tf.global_variables_initializer())\n" }, { "code": null, "e": 7839, "s": 7719, "text": "To assign a new value to a variable node, we can use assign method like this:node = node.assign(node + tf.ones([2,2]))\n" }, { "code": null, "e": 7882, "s": 7839, "text": "node = node.assign(node + tf.ones([2,2]))\n" }, { "code": null, "e": 7898, "s": 7882, "text": "4. Placeholders" }, { "code": null, "e": 8030, "s": 7898, "text": "A graph can be parameterized to accept external inputs, known as placeholders. A placeholder is a promise to provide a value later." }, { "code": null, "e": 8217, "s": 8030, "text": "While evaluating the graph involving placeholder nodes, a feed_dict parameter is passed to the session’s run method to specify Tensors that provide concrete values to these placeholders." }, { "code": null, "e": 8251, "s": 8217, "text": "Consider the example given below:" }, { "code": "# importing tensorflowimport tensorflow as tf # creating nodes in computation grapha = tf.placeholder(tf.int32, shape=(3,1))b = tf.placeholder(tf.int32, shape=(1,3))c = tf.matmul(a,b) # running computation graphwith tf.Session() as sess: print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]}))", "e": 8555, "s": 8251, "text": null }, { "code": null, "e": 8563, "s": 8555, "text": "Output:" }, { "code": null, "e": 8592, "s": 8563, "text": "[[3 6 9]\n [2 4 6]\n [1 2 3]]\n" }, { "code": null, "e": 8632, "s": 8592, "text": "Let us try to understand above program:" }, { "code": null, "e": 8869, "s": 8632, "text": "We define placeholder nodes a and b like this:a = tf.placeholder(tf.int32, shape=(3,1))\nb = tf.placeholder(tf.int32, shape=(1,3))\nThe first argument is the data type of the tensor and one of the optional argument is shape of the tensor." }, { "code": null, "e": 8954, "s": 8869, "text": "a = tf.placeholder(tf.int32, shape=(3,1))\nb = tf.placeholder(tf.int32, shape=(1,3))\n" }, { "code": null, "e": 9061, "s": 8954, "text": "The first argument is the data type of the tensor and one of the optional argument is shape of the tensor." }, { "code": null, "e": 9212, "s": 9061, "text": "We define another node c which does the operation of matrix multiplication (matmul). We pass the two placeholder nodes as argument.c = tf.matmul(a,b)\n" }, { "code": null, "e": 9232, "s": 9212, "text": "c = tf.matmul(a,b)\n" }, { "code": null, "e": 9456, "s": 9232, "text": "Finally, when we run the session, we pass the value of placeholder nodes in feed_dict argument of sess.run:print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]}))\nConsider the diagrams shown below to clear the concept:" }, { "code": null, "e": 9518, "s": 9456, "text": "print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]}))\n" }, { "code": null, "e": 9574, "s": 9518, "text": "Consider the diagrams shown below to clear the concept:" }, { "code": null, "e": 9585, "s": 9574, "text": "Initially:" }, { "code": null, "e": 9601, "s": 9585, "text": "After sess.run:" }, { "code": null, "e": 9690, "s": 9601, "text": "Given below is an implementation of a Linear Regression model using TensorFlow Core API." }, { "code": "# importing the dependenciesimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt # Model Parameterslearning_rate = 0.01training_epochs = 2000display_step = 200 # Training Datatrain_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167, 7.042,10.791,5.313,7.997,5.654,9.27,3.1])train_y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221, 2.827,3.465,1.65,2.904,2.42,2.94,1.3])n_samples = train_X.shape[0] # Test Datatest_X = np.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])test_y = np.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03]) # Set placeholders for feature and target vectorsX = tf.placeholder(tf.float32)y = tf.placeholder(tf.float32) # Set model weights and biasW = tf.Variable(np.random.randn(), name=\"weight\")b = tf.Variable(np.random.randn(), name=\"bias\") # Construct a linear modellinear_model = W*X + b # Mean squared errorcost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples) # Gradient descentoptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Initializing the variablesinit = tf.global_variables_initializer() # Launch the graphwith tf.Session() as sess: # Load initialized variables in current session sess.run(init) # Fit all training data for epoch in range(training_epochs): # perform gradient descent step sess.run(optimizer, feed_dict={X: train_X, y: train_y}) # Display logs per epoch step if (epoch+1) % display_step == 0: c = sess.run(cost, feed_dict={X: train_X, y: train_y}) print(\"Epoch:{0:6} \\t Cost:{1:10.4} \\t W:{2:6.4} \\t b:{3:6.4}\". format(epoch+1, c, sess.run(W), sess.run(b))) # Print final parameter values print(\"Optimization Finished!\") training_cost = sess.run(cost, feed_dict={X: train_X, y: train_y}) print(\"Final training cost:\", training_cost, \"W:\", sess.run(W), \"b:\", sess.run(b), '\\n') # Graphic display plt.plot(train_X, train_y, 'ro', label='Original data') plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') plt.legend() plt.show() # Testing the model testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]), feed_dict={X: test_X, y: test_y}) print(\"Final testing cost:\", testing_cost) print(\"Absolute mean square loss difference:\", abs(training_cost - testing_cost)) # Display fitted line on test data plt.plot(test_X, test_y, 'bo', label='Testing data') plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') plt.legend() plt.show()", "e": 12434, "s": 9690, "text": null }, { "code": null, "e": 13220, "s": 12434, "text": "Epoch: 200 Cost: 0.1715 W: 0.426 b:-0.4371\nEpoch: 400 Cost: 0.1351 W:0.3884 b:-0.1706\nEpoch: 600 Cost: 0.1127 W:0.3589 b:0.03849\nEpoch: 800 Cost: 0.09894 W:0.3358 b:0.2025\nEpoch: 1000 Cost: 0.09047 W:0.3176 b:0.3311\nEpoch: 1200 Cost: 0.08526 W:0.3034 b:0.4319\nEpoch: 1400 Cost: 0.08205 W:0.2922 b:0.5111\nEpoch: 1600 Cost: 0.08008 W:0.2835 b:0.5731\nEpoch: 1800 Cost: 0.07887 W:0.2766 b:0.6218\nEpoch: 2000 Cost: 0.07812 W:0.2712 b: 0.66\nOptimization Finished!\nFinal training cost: 0.0781221 W: 0.271219 b: 0.65996 \n\n\n\nFinal testing cost: 0.0756337\nAbsolute mean square loss difference: 0.00248838\n\n\n" }, { "code": null, "e": 13261, "s": 13220, "text": "Let us try to understand the above code." }, { "code": null, "e": 13394, "s": 13261, "text": "First of all, we define some parameters for training our model, like:learning_rate = 0.01\ntraining_epochs = 2000\ndisplay_step = 200\n" }, { "code": null, "e": 13458, "s": 13394, "text": "learning_rate = 0.01\ntraining_epochs = 2000\ndisplay_step = 200\n" }, { "code": null, "e": 13584, "s": 13458, "text": "Then we define placeholder nodes for feature and target vector.X = tf.placeholder(tf.float32)\ny = tf.placeholder(tf.float32)\n" }, { "code": null, "e": 13647, "s": 13584, "text": "X = tf.placeholder(tf.float32)\ny = tf.placeholder(tf.float32)\n" }, { "code": null, "e": 13797, "s": 13647, "text": "Then, we define variable nodes for weight and bias.W = tf.Variable(np.random.randn(), name=\"weight\")\nb = tf.Variable(np.random.randn(), name=\"bias\")\n" }, { "code": null, "e": 13896, "s": 13797, "text": "W = tf.Variable(np.random.randn(), name=\"weight\")\nb = tf.Variable(np.random.randn(), name=\"bias\")\n" }, { "code": null, "e": 14020, "s": 13896, "text": "linear_model is an operational node which calculates the hypothesis for the linear regression model.linear_model = W*X + b\n" }, { "code": null, "e": 14044, "s": 14020, "text": "linear_model = W*X + b\n" }, { "code": null, "e": 14214, "s": 14044, "text": "Loss (or cost) per gradient descent is calculated as the mean squared error and its node is defined as:cost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples)\n" }, { "code": null, "e": 14281, "s": 14214, "text": "cost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples)\n" }, { "code": null, "e": 14442, "s": 14281, "text": "Finally, we have the optimizer node which implements the Gradient Descent Algorithm.optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n" }, { "code": null, "e": 14519, "s": 14442, "text": "optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n" }, { "code": null, "e": 14788, "s": 14519, "text": "Now, the training data is fit into the linear model by applying the Gradient Descent Algorithm. The task is repeated training_epochs number of times. In each epoch, we perform the gradient descent step like this:sess.run(optimizer, feed_dict={X: train_X, y: train_y})\n" }, { "code": null, "e": 14845, "s": 14788, "text": "sess.run(optimizer, feed_dict={X: train_X, y: train_y})\n" }, { "code": null, "e": 15000, "s": 14845, "text": "After every display_step number of epochs, we print the value of current loss which is found using:c = sess.run(cost, feed_dict={X: train_X, y: train_y})\n" }, { "code": null, "e": 15056, "s": 15000, "text": "c = sess.run(cost, feed_dict={X: train_X, y: train_y})\n" }, { "code": null, "e": 15282, "s": 15056, "text": "The model is evaluated on test data and testing_cost is calculated using:testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]),\n feed_dict={X: test_X, y: test_y})\n" }, { "code": null, "e": 15435, "s": 15282, "text": "testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]),\n feed_dict={X: test_X, y: test_y})\n" }, { "code": null, "e": 15452, "s": 15435, "text": "tf.contrib.learn" }, { "code": null, "e": 15580, "s": 15452, "text": "tf.contrib.learn is a high-level TensorFlow library that simplifies the mechanics of machine learning, including the following:" }, { "code": null, "e": 15603, "s": 15580, "text": "running training loops" }, { "code": null, "e": 15628, "s": 15603, "text": "running evaluation loops" }, { "code": null, "e": 15647, "s": 15628, "text": "managing data sets" }, { "code": null, "e": 15664, "s": 15647, "text": "managing feeding" }, { "code": null, "e": 15773, "s": 15664, "text": "Let us try to see the implementation of Linear regression on same data we used above using tf.contrib.learn." }, { "code": "# importing the dependenciesimport tensorflow as tfimport numpy as np # declaring list of featuresfeatures = [tf.contrib.layers.real_valued_column(\"X\")] # creating a linear regression estimatorestimator = tf.contrib.learn.LinearRegressor(feature_columns=features) # training and test datatrain_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167, 7.042,10.791,5.313,7.997,5.654,9.27,3.1])train_y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221, 2.827,3.465,1.65,2.904,2.42,2.94,1.3])test_X = np.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])test_y = np.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03]) # function to feed dict of numpy arrays into the model for traininginput_fn = tf.contrib.learn.io.numpy_input_fn({\"X\":train_X}, train_y, batch_size=4, num_epochs=2000) # function to feed dict of numpy arrays into the model for testingtest_input_fn = tf.contrib.learn.io.numpy_input_fn({\"X\":test_X}, test_y) # fit training data into estimatorestimator.fit(input_fn=input_fn) # print value of weight and biasW = estimator.get_variable_value('linear/X/weight')[0][0]b = estimator.get_variable_value('linear/bias_weight')[0]print(\"W:\", W, \"\\tb:\", b) # evaluating the final losstrain_loss = estimator.evaluate(input_fn=input_fn)['loss']test_loss = estimator.evaluate(input_fn=test_input_fn)['loss']print(\"Final training loss:\", train_loss)print(\"Final testing loss:\", test_loss)", "e": 17303, "s": 15773, "text": null }, { "code": null, "e": 17392, "s": 17303, "text": "W: 0.252928 b: 0.802972\nFinal training loss: 0.153998\nFinal testing loss: 0.0777036\n" }, { "code": null, "e": 17433, "s": 17392, "text": "Let us try to understand the above code." }, { "code": null, "e": 17706, "s": 17433, "text": "The shape and type of feature matrix is declared using a list. Each element of the list defines the structure of a column. In above example, we have only 1 feature which stores real values and has been given a name X.features = [tf.contrib.layers.real_valued_column(\"X\")]\n" }, { "code": null, "e": 17762, "s": 17706, "text": "features = [tf.contrib.layers.real_valued_column(\"X\")]\n" }, { "code": null, "e": 18012, "s": 17762, "text": "Then, we need an estimator. An estimator is nothing but a pre-defined model with many useful methods and parameters. In above example, we use a Linear Regression model estimator.estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)\n" }, { "code": null, "e": 18084, "s": 18012, "text": "estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)\n" }, { "code": null, "e": 18451, "s": 18084, "text": "For training purpose, we need to use an input function which is responsible for feeding data to estimator while training. It takes the feature column values as dictionary. Many other parameters like batch size, number of epochs, etc can be specified.input_fn = tf.contrib.learn.io.numpy_input_fn({\"X\":train_X}, \n train_y, batch_size=4, num_epochs=2000)\n" }, { "code": null, "e": 18568, "s": 18451, "text": "input_fn = tf.contrib.learn.io.numpy_input_fn({\"X\":train_X}, \n train_y, batch_size=4, num_epochs=2000)\n" }, { "code": null, "e": 18724, "s": 18568, "text": "To fit training data to estimator, we simply use fit method of estimator in which input function is passed as an argument.estimator.fit(input_fn=input_fn)\n" }, { "code": null, "e": 18758, "s": 18724, "text": "estimator.fit(input_fn=input_fn)\n" }, { "code": null, "e": 19060, "s": 18758, "text": "Once training is complete, we can get the value of different variables using get_variable_value method of estimator. You can get a list of all variables using get_variable_names method.W = estimator.get_variable_value('linear/X/weight')[0][0]\nb = estimator.get_variable_value('linear/bias_weight')[0]\n" }, { "code": null, "e": 19177, "s": 19060, "text": "W = estimator.get_variable_value('linear/X/weight')[0][0]\nb = estimator.get_variable_value('linear/bias_weight')[0]\n" }, { "code": null, "e": 19347, "s": 19177, "text": "The mean squared error/loss can be computed as:train_loss = estimator.evaluate(input_fn=input_fn)['loss']\ntest_loss = estimator.evaluate(input_fn=test_input_fn)['loss']\n" }, { "code": null, "e": 19470, "s": 19347, "text": "train_loss = estimator.evaluate(input_fn=input_fn)['loss']\ntest_loss = estimator.evaluate(input_fn=test_input_fn)['loss']\n" }, { "code": null, "e": 19540, "s": 19470, "text": "This brings us to the end of this Introduction to TensorFlow article!" }, { "code": null, "e": 19613, "s": 19540, "text": "From here, you can try to explore this tutorial: MNIST For ML Beginners." }, { "code": null, "e": 19913, "s": 19613, "text": "This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 20038, "s": 19913, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 20049, "s": 20038, "text": "Tensorflow" }, { "code": null, "e": 20055, "s": 20049, "text": "GBlog" }, { "code": null, "e": 20062, "s": 20055, "text": "Python" } ]
What is Arduino?
13 Jul, 2021 So you might have heard about Arduino from your friends at school or on the internet, it seemed quite exciting, but you don’t know where to start, fret not as this article will let you know the basics of getting started with your shiny new Arduino. Arduino was a project started at Interaction Design Institute Ivrea (IDII) in Ivrea, Italy, with its primary goal being creating affordable and straightforward tools for non-engineers to use and create digital projects. During its infancy, the project consisted of just three members- Hernando Barragán, Massimo Banzi, and Casey Reas. Hernando Barragán worked under the guidance of Massimo Banzi and Casey Reas and created a development platform called Wiring as his masters’ thesis project at IDII. The development platform consisted of the ATMega168 microcontroller as its brains and used an IDE based on Processing, which was co-created by Casy Reas. Later, Massimo Banzi, along with two other students from IDII, namely- David Mellis and David Cuartielles, added support for the cheaper ATMega8 microcontroller. The three, instead of working on developing and improving Wiring, they forked it and renamed the project to Arduino. The initial core Arduino team consisted of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David Mellis, but Barragán was not included. Now that you know the origin of Arduino, it is essential to get yourself acquainted with the hardware that Arduino as a company offers. One of the main reasons for Arduino being so accessible and affordable across the globe is because all of the Arduino hardware is open-source. Being open-source has a plethora of advantages- anyone can access the design and build of the device and make improvements; anyone can use the same hardware design to create their product lineup. Since Arduino is open-source, it has its own devoted community that strives to help the core company develop and improve its hardware products. Another significant advantage of being open-source, especially in the case of hardware, is that local companies can create replicas of the products, making it more accessible and affordable to the local consumers as it avoids hefty customs and shipping charges. All of these advantages contribute to Arduino being so widespread, affordable and ever-improving. It is necessary to know that Arduino doesn’t necessarily offer just one piece of hardware, it provides a range of boards, each of which caters to a different level of expertise and have different use-cases altogether. Arduino Uno is one of the most basic and popular boards that Arduino offers. This is because it features an ATMega328 microcontroller that is both cheap and powerful enough for most basic beginner-level projects. Once you’re familiar with Arduino IDE, you can move up to boards with more powerful and sophisticated chipsets like the MKR range which is concerned with IoT applications and inter compatibility, or the Nano range which as the name suggests is designed to keep the form factor as small as possible while packing most of the features and power of the full-sized boards. Note: Since this guide is aimed at absolute beginners, this article is limited to getting started with Arduino Uno. So you got yourself an Arduino Uno, and you’re ready to jump into the world of electronics and join the community of makers from around the world, but before you begin with programming and external circuitry through breadboards and whatnot, it is necessary to understand the layout and circuitry of your Arduino Uno. Using the above image as a reference, the labeled components of the board respectively are- USB: can be used for both power and communication with the IDEBarrel Jack: used for power supplyVoltage Regulator: regulates and stabilizes the input and output voltagesCrystal Oscillator: keeps track of time and regulates processor frequencyReset Pin: can be used to reset the Arduino Uno3.3V pin: can be used as a 3.3V output5V pin: can be used as a 5V outputGND pin: can be used to ground the circuitVin pin: can be used to supply power to the boardAnalog pins(A0-A5): can be used to read analog signals to the boardMicrocontroller(ATMega328): the processing and logical unit of the boardICSP pin: a programming header on the board also called SPIPower indicator LED: indicates the power status of the boardRX and TX LEDs: receive(RX) and transmit(TX) LEDs, blink when sending or receiving serial data respectivelyDigital I/O pins: 14 pins capable of reading and outputting digital signals; 6 of these pins are also capable of PWMAREF pins: can be used to set an external reference voltage as the upper limit for the analog pinsReset button: can be used to reset the board USB: can be used for both power and communication with the IDE Barrel Jack: used for power supply Voltage Regulator: regulates and stabilizes the input and output voltages Crystal Oscillator: keeps track of time and regulates processor frequency Reset Pin: can be used to reset the Arduino Uno 3.3V pin: can be used as a 3.3V output 5V pin: can be used as a 5V output GND pin: can be used to ground the circuit Vin pin: can be used to supply power to the board Analog pins(A0-A5): can be used to read analog signals to the board Microcontroller(ATMega328): the processing and logical unit of the board ICSP pin: a programming header on the board also called SPI Power indicator LED: indicates the power status of the board RX and TX LEDs: receive(RX) and transmit(TX) LEDs, blink when sending or receiving serial data respectively Digital I/O pins: 14 pins capable of reading and outputting digital signals; 6 of these pins are also capable of PWM AREF pins: can be used to set an external reference voltage as the upper limit for the analog pins Reset button: can be used to reset the board Now that you’re familiar with the hardware, its time to learn about the development environment using which you’re going to program your Uno. The Arduino IDE is the best place to start your journey in programming your Uno. To get started, visit this page and download the latest build of the Arduino IDE for your Mac or PC. Go ahead and install the IDE on your PC or Mac and open it. As you open the IDE, you’ll be greeted by a window similar to the one shown in the above image. The text editor is where you’ll be writing your code; you’ll use the verify button to compile and debug the written program, the save button to save the program and the upload button to upload the program to the board. Before you click on the upload button, it is necessary to select your board, Uno in this case, from the tools menu in the Menu Bar. After you choose your appropriate board, make sure you specify the correct port on your PC or Mac that you’ve connected your Uno to, in the IDE. In this example program, we’ll be blinking the inbuilt L LED located right above the RX and TX LEDs. The Arduino IDE includes many basic programs to help you get started with your Uno. For this example, we’ll be using the inbuilt ‘Blink’ program. To open this program, go to the Files menu in the Menu Bar; click on Examples; click on 01.Basics; select Blink. Now that you’ve opened the example program, its time to upload the program, to do this, click on the upload button and wait for the process to complete. If your Output Pane header turns amber and shows an error which reads “Serial Port COM’x’ not found”, you’ve not connected your board correctly or that you’ve not specified the correct port that your board is connected to in the IDE. When you advance and start writing your own programs, you might run into errors while compiling and uploading; this can be because of a syntax error in the program. After you’ve corrected the errors and uploaded the program, you’ll see that the inbuilt LED blinks, alternating between the ON and OFF state every second. Congrats on uploading and executing your first piece of code on your Arduino Uno. You can now tinker with the program you just uploaded by changing the values of delay. This will change the pattern and the rate of blinking. Do keep in mind that the default unit of time in the Arduino IDE is milliseconds; also remember that you’ve to upload the program to the board after you’ve made changes in the values of delay to notice the changes in the rate and pattern of the blinking. Now that you’re familiar with the IDE and the hardware on the board, you can move up to programs that require external actuators and sensors using the inbuilt example programs as a reference. After you’ve gained some expertise with the board, you can move on to create projects that inculcate your innovative and innovative ideas. Soon in your journey through electronics, you’ll realize that the Uno is not powerful enough or does not pack the features you require for your expert level programs, that is when you’ll have to consider upgrading your board to something from the MKR line or to more powerful lines like the Yun. gulshankumarar231 Advanced Computer Subject Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jul, 2021" }, { "code": null, "e": 303, "s": 53, "text": "So you might have heard about Arduino from your friends at school or on the internet, it seemed quite exciting, but you don’t know where to start, fret not as this article will let you know the basics of getting started with your shiny new Arduino. " }, { "code": null, "e": 1394, "s": 303, "text": "Arduino was a project started at Interaction Design Institute Ivrea (IDII) in Ivrea, Italy, with its primary goal being creating affordable and straightforward tools for non-engineers to use and create digital projects. During its infancy, the project consisted of just three members- Hernando Barragán, Massimo Banzi, and Casey Reas. Hernando Barragán worked under the guidance of Massimo Banzi and Casey Reas and created a development platform called Wiring as his masters’ thesis project at IDII. The development platform consisted of the ATMega168 microcontroller as its brains and used an IDE based on Processing, which was co-created by Casy Reas. Later, Massimo Banzi, along with two other students from IDII, namely- David Mellis and David Cuartielles, added support for the cheaper ATMega8 microcontroller. The three, instead of working on developing and improving Wiring, they forked it and renamed the project to Arduino. The initial core Arduino team consisted of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David Mellis, but Barragán was not included. " }, { "code": null, "e": 3174, "s": 1394, "text": "Now that you know the origin of Arduino, it is essential to get yourself acquainted with the hardware that Arduino as a company offers. One of the main reasons for Arduino being so accessible and affordable across the globe is because all of the Arduino hardware is open-source. Being open-source has a plethora of advantages- anyone can access the design and build of the device and make improvements; anyone can use the same hardware design to create their product lineup. Since Arduino is open-source, it has its own devoted community that strives to help the core company develop and improve its hardware products. Another significant advantage of being open-source, especially in the case of hardware, is that local companies can create replicas of the products, making it more accessible and affordable to the local consumers as it avoids hefty customs and shipping charges. All of these advantages contribute to Arduino being so widespread, affordable and ever-improving. It is necessary to know that Arduino doesn’t necessarily offer just one piece of hardware, it provides a range of boards, each of which caters to a different level of expertise and have different use-cases altogether. Arduino Uno is one of the most basic and popular boards that Arduino offers. This is because it features an ATMega328 microcontroller that is both cheap and powerful enough for most basic beginner-level projects. Once you’re familiar with Arduino IDE, you can move up to boards with more powerful and sophisticated chipsets like the MKR range which is concerned with IoT applications and inter compatibility, or the Nano range which as the name suggests is designed to keep the form factor as small as possible while packing most of the features and power of the full-sized boards. " }, { "code": null, "e": 3291, "s": 3174, "text": "Note: Since this guide is aimed at absolute beginners, this article is limited to getting started with Arduino Uno. " }, { "code": null, "e": 3609, "s": 3291, "text": "So you got yourself an Arduino Uno, and you’re ready to jump into the world of electronics and join the community of makers from around the world, but before you begin with programming and external circuitry through breadboards and whatnot, it is necessary to understand the layout and circuitry of your Arduino Uno. " }, { "code": null, "e": 3703, "s": 3609, "text": "Using the above image as a reference, the labeled components of the board respectively are- " }, { "code": null, "e": 4779, "s": 3703, "text": "USB: can be used for both power and communication with the IDEBarrel Jack: used for power supplyVoltage Regulator: regulates and stabilizes the input and output voltagesCrystal Oscillator: keeps track of time and regulates processor frequencyReset Pin: can be used to reset the Arduino Uno3.3V pin: can be used as a 3.3V output5V pin: can be used as a 5V outputGND pin: can be used to ground the circuitVin pin: can be used to supply power to the boardAnalog pins(A0-A5): can be used to read analog signals to the boardMicrocontroller(ATMega328): the processing and logical unit of the boardICSP pin: a programming header on the board also called SPIPower indicator LED: indicates the power status of the boardRX and TX LEDs: receive(RX) and transmit(TX) LEDs, blink when sending or receiving serial data respectivelyDigital I/O pins: 14 pins capable of reading and outputting digital signals; 6 of these pins are also capable of PWMAREF pins: can be used to set an external reference voltage as the upper limit for the analog pinsReset button: can be used to reset the board" }, { "code": null, "e": 4842, "s": 4779, "text": "USB: can be used for both power and communication with the IDE" }, { "code": null, "e": 4877, "s": 4842, "text": "Barrel Jack: used for power supply" }, { "code": null, "e": 4951, "s": 4877, "text": "Voltage Regulator: regulates and stabilizes the input and output voltages" }, { "code": null, "e": 5025, "s": 4951, "text": "Crystal Oscillator: keeps track of time and regulates processor frequency" }, { "code": null, "e": 5073, "s": 5025, "text": "Reset Pin: can be used to reset the Arduino Uno" }, { "code": null, "e": 5112, "s": 5073, "text": "3.3V pin: can be used as a 3.3V output" }, { "code": null, "e": 5147, "s": 5112, "text": "5V pin: can be used as a 5V output" }, { "code": null, "e": 5190, "s": 5147, "text": "GND pin: can be used to ground the circuit" }, { "code": null, "e": 5240, "s": 5190, "text": "Vin pin: can be used to supply power to the board" }, { "code": null, "e": 5308, "s": 5240, "text": "Analog pins(A0-A5): can be used to read analog signals to the board" }, { "code": null, "e": 5381, "s": 5308, "text": "Microcontroller(ATMega328): the processing and logical unit of the board" }, { "code": null, "e": 5441, "s": 5381, "text": "ICSP pin: a programming header on the board also called SPI" }, { "code": null, "e": 5502, "s": 5441, "text": "Power indicator LED: indicates the power status of the board" }, { "code": null, "e": 5610, "s": 5502, "text": "RX and TX LEDs: receive(RX) and transmit(TX) LEDs, blink when sending or receiving serial data respectively" }, { "code": null, "e": 5727, "s": 5610, "text": "Digital I/O pins: 14 pins capable of reading and outputting digital signals; 6 of these pins are also capable of PWM" }, { "code": null, "e": 5826, "s": 5727, "text": "AREF pins: can be used to set an external reference voltage as the upper limit for the analog pins" }, { "code": null, "e": 5871, "s": 5826, "text": "Reset button: can be used to reset the board" }, { "code": null, "e": 6256, "s": 5871, "text": "Now that you’re familiar with the hardware, its time to learn about the development environment using which you’re going to program your Uno. The Arduino IDE is the best place to start your journey in programming your Uno. To get started, visit this page and download the latest build of the Arduino IDE for your Mac or PC. Go ahead and install the IDE on your PC or Mac and open it. " }, { "code": null, "e": 6850, "s": 6256, "text": "As you open the IDE, you’ll be greeted by a window similar to the one shown in the above image. The text editor is where you’ll be writing your code; you’ll use the verify button to compile and debug the written program, the save button to save the program and the upload button to upload the program to the board. Before you click on the upload button, it is necessary to select your board, Uno in this case, from the tools menu in the Menu Bar. After you choose your appropriate board, make sure you specify the correct port on your PC or Mac that you’ve connected your Uno to, in the IDE. " }, { "code": null, "e": 7918, "s": 6850, "text": "In this example program, we’ll be blinking the inbuilt L LED located right above the RX and TX LEDs. The Arduino IDE includes many basic programs to help you get started with your Uno. For this example, we’ll be using the inbuilt ‘Blink’ program. To open this program, go to the Files menu in the Menu Bar; click on Examples; click on 01.Basics; select Blink. Now that you’ve opened the example program, its time to upload the program, to do this, click on the upload button and wait for the process to complete. If your Output Pane header turns amber and shows an error which reads “Serial Port COM’x’ not found”, you’ve not connected your board correctly or that you’ve not specified the correct port that your board is connected to in the IDE. When you advance and start writing your own programs, you might run into errors while compiling and uploading; this can be because of a syntax error in the program. After you’ve corrected the errors and uploaded the program, you’ll see that the inbuilt LED blinks, alternating between the ON and OFF state every second. " }, { "code": null, "e": 8399, "s": 7918, "text": "Congrats on uploading and executing your first piece of code on your Arduino Uno. You can now tinker with the program you just uploaded by changing the values of delay. This will change the pattern and the rate of blinking. Do keep in mind that the default unit of time in the Arduino IDE is milliseconds; also remember that you’ve to upload the program to the board after you’ve made changes in the values of delay to notice the changes in the rate and pattern of the blinking. " }, { "code": null, "e": 9027, "s": 8399, "text": "Now that you’re familiar with the IDE and the hardware on the board, you can move up to programs that require external actuators and sensors using the inbuilt example programs as a reference. After you’ve gained some expertise with the board, you can move on to create projects that inculcate your innovative and innovative ideas. Soon in your journey through electronics, you’ll realize that the Uno is not powerful enough or does not pack the features you require for your expert level programs, that is when you’ll have to consider upgrading your board to something from the MKR line or to more powerful lines like the Yun. " }, { "code": null, "e": 9047, "s": 9029, "text": "gulshankumarar231" }, { "code": null, "e": 9073, "s": 9047, "text": "Advanced Computer Subject" }, { "code": null, "e": 9092, "s": 9073, "text": "Technical Scripter" } ]
Processing of Raw Data to Tidy Data in R - GeeksforGeeks
23 Aug, 2018 The data that is download from web or other resources are often hard to analyze. It is often needed to do some processing or cleaning of the dataset in order to prepare it for further downstream analysis, predictive modeling and so on. This article discusses several methods in R to convert the raw dataset into a tidy data. A Raw data is a dataset that has been downloaded from web (or any other source) and has not been processed yet. Raw data is not ready for use in statistics. It needs various processing tools to be ready for analysis. Example: Below is the image of a Raw IRIS Dataset. It does not have any information as what the data is, or what is it representing. This will be done by tidying the data. On the other hand, a Tidy dataset (also called cooked data) is the data that has following characteristics: Each variable measured should be in one column. Each different observation of that variable should be in a different row. There should be one table for each “kind” of variable. If there are multiple tables, they should include a column in the table that allows them to be linked. Example: Below is the image of a Tidy IRIS Dataset. It contains valuable processed information like column names. The process is explained later below. Loading the dataset in RThe first-most step is to get the data for processing. Here the data taken is from IRIS data.Firstly download the data and make it into a dataframe in R.##Provide the link of the dataseturl < -"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, "iris.txt") ##import the data in a dataframed < -read.table("iris.txt", sep = ", ") ##Rename the columnscolnames(d)< -c("s_len", "s_width", "p_len", "p_width", "variety")Subsetting Rows and ColumnsNow if only s_len(1st column), p_len(3rd column) and variety(5th column) are required for analysis, then subset these columns and assign the new data to a new dataframe.##subsetting columns with column numberd1 <- d[, c(1, 3, 5)]Subsetting can also be done using column names.##subsetting columns with column namesd1 <- d[, c("s_len", "p_len", "variety")]Also, If it is required to know the observations that are either of variety “Iris-setosa” or have “sepal length less than 5”.##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == "Iris-setosa"), ]Note: The “$” operator is used to subset a column.Sorting the data frame by some variableOrder the dataframe by petal length using the order command.d3 < -d[order(d$p_len), ]Adding new rows and columnsAdd a new column by cbind() and add new row by rbind().##Extract the s_width column of dsepal_width <- d$s_width ##Add the column to d1 dataframe.d1 <- cbind(d1, sepal_width)Getting an overview of the data at a glanceTo get a summarised overview of the processed data, call summary() command on the data-frame.summary(d)Output“: s_len s_width p_len p_width variety Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 To get overview like the type of each variable, total number of observations, and their first few values; use str() command.str(d)Output:'data.frame': 150 obs. of 5 variables: $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ variety: Factor w/ 3 levels "Iris-setosa", ..: 1 1 1 1 1 1 1 1 1 1 ... Loading the dataset in RThe first-most step is to get the data for processing. Here the data taken is from IRIS data.Firstly download the data and make it into a dataframe in R.##Provide the link of the dataseturl < -"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, "iris.txt") ##import the data in a dataframed < -read.table("iris.txt", sep = ", ") ##Rename the columnscolnames(d)< -c("s_len", "s_width", "p_len", "p_width", "variety") The first-most step is to get the data for processing. Here the data taken is from IRIS data. Firstly download the data and make it into a dataframe in R.##Provide the link of the dataseturl < -"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, "iris.txt") ##import the data in a dataframed < -read.table("iris.txt", sep = ", ") ##Rename the columnscolnames(d)< -c("s_len", "s_width", "p_len", "p_width", "variety") ##Provide the link of the dataseturl < -"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, "iris.txt") ##import the data in a dataframed < -read.table("iris.txt", sep = ", ") ##Rename the columnscolnames(d)< -c("s_len", "s_width", "p_len", "p_width", "variety") Subsetting Rows and ColumnsNow if only s_len(1st column), p_len(3rd column) and variety(5th column) are required for analysis, then subset these columns and assign the new data to a new dataframe.##subsetting columns with column numberd1 <- d[, c(1, 3, 5)]Subsetting can also be done using column names.##subsetting columns with column namesd1 <- d[, c("s_len", "p_len", "variety")]Also, If it is required to know the observations that are either of variety “Iris-setosa” or have “sepal length less than 5”.##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == "Iris-setosa"), ]Note: The “$” operator is used to subset a column. Now if only s_len(1st column), p_len(3rd column) and variety(5th column) are required for analysis, then subset these columns and assign the new data to a new dataframe.##subsetting columns with column numberd1 <- d[, c(1, 3, 5)] ##subsetting columns with column numberd1 <- d[, c(1, 3, 5)] Subsetting can also be done using column names.##subsetting columns with column namesd1 <- d[, c("s_len", "p_len", "variety")] ##subsetting columns with column namesd1 <- d[, c("s_len", "p_len", "variety")] Also, If it is required to know the observations that are either of variety “Iris-setosa” or have “sepal length less than 5”.##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == "Iris-setosa"), ] ##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == "Iris-setosa"), ] Note: The “$” operator is used to subset a column. Sorting the data frame by some variableOrder the dataframe by petal length using the order command.d3 < -d[order(d$p_len), ] Order the dataframe by petal length using the order command. d3 < -d[order(d$p_len), ] Adding new rows and columnsAdd a new column by cbind() and add new row by rbind().##Extract the s_width column of dsepal_width <- d$s_width ##Add the column to d1 dataframe.d1 <- cbind(d1, sepal_width) Add a new column by cbind() and add new row by rbind(). ##Extract the s_width column of dsepal_width <- d$s_width ##Add the column to d1 dataframe.d1 <- cbind(d1, sepal_width) Getting an overview of the data at a glanceTo get a summarised overview of the processed data, call summary() command on the data-frame.summary(d)Output“: s_len s_width p_len p_width variety Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 To get overview like the type of each variable, total number of observations, and their first few values; use str() command.str(d)Output:'data.frame': 150 obs. of 5 variables: $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ variety: Factor w/ 3 levels "Iris-setosa", ..: 1 1 1 1 1 1 1 1 1 1 ... To get a summarised overview of the processed data, call summary() command on the data-frame.summary(d)Output“: s_len s_width p_len p_width variety Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 summary(d) Output“: s_len s_width p_len p_width variety Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 To get overview like the type of each variable, total number of observations, and their first few values; use str() command.str(d)Output:'data.frame': 150 obs. of 5 variables: $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ variety: Factor w/ 3 levels "Iris-setosa", ..: 1 1 1 1 1 1 1 1 1 1 ... str(d) Output: 'data.frame': 150 obs. of 5 variables: $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ variety: Factor w/ 3 levels "Iris-setosa", ..: 1 1 1 1 1 1 1 1 1 1 ... Another way of re-organizing data is by using melt and cast functions. They are present in reshape2 package.## Create A Dummy Datasetd<-data.frame( name=c("Arnab", "Arnab", "Soumik", "Mukul", "Soumik"), year=c(2011, 2014, 2011, 2015, 2014), height=c(5, 6, 4, 3, 5), Weight=c(90, 89, 76, 85, 84)) ## View the datasetdOutput: name year height Weight 1 Arnab 2011 5 90 2 Arnab 2014 6 89 3 Soumik 2011 4 76 4 Mukul 2015 3 85 5 Soumik 2014 5 84 ## Create A Dummy Datasetd<-data.frame( name=c("Arnab", "Arnab", "Soumik", "Mukul", "Soumik"), year=c(2011, 2014, 2011, 2015, 2014), height=c(5, 6, 4, 3, 5), Weight=c(90, 89, 76, 85, 84)) ## View the datasetd Output: name year height Weight 1 Arnab 2011 5 90 2 Arnab 2014 6 89 3 Soumik 2011 4 76 4 Mukul 2015 3 85 5 Soumik 2014 5 84 Melting of this data means referring some variable as id variable (Others will be taken as measure variables). Now if name and year are taken as id variable and height and weight as measure variables, then there will be 4 columns in the new dataset- name, year, variable and value. For each name and year, there will be the variable to be measured and its value.## Getting the reshape libraryinstall.packages("reshape2")library(reshape2) ## Configure the id variables, name and yearmelt(d, id=c("name", "year"))Output: name year variable value 1 Arnab 2011 height 5 2 Arnab 2014 height 6 3 Soumik 2011 height 4 4 Mukul 2015 height 3 5 Soumik 2014 height 5 6 Arnab 2011 Weight 90 7 Aranb 2014 Weight 89 8 Soumik 2011 Weight 76 9 Mukul 2015 Weight 85 10 Soumik 2014 Weight 84 ## Getting the reshape libraryinstall.packages("reshape2")library(reshape2) ## Configure the id variables, name and yearmelt(d, id=c("name", "year")) Output: name year variable value 1 Arnab 2011 height 5 2 Arnab 2014 height 6 3 Soumik 2011 height 4 4 Mukul 2015 height 3 5 Soumik 2014 height 5 6 Arnab 2011 Weight 90 7 Aranb 2014 Weight 89 8 Soumik 2011 Weight 76 9 Mukul 2015 Weight 85 10 Soumik 2014 Weight 84 Now the molten dataset can be converted in a compact form by cast() function. Compute everyone’s mean height and weight.##Save the molten datasetd1<-melt(d, id=c("name", "year")) ##Now cast the datad2 <-cast(d1, name~variable, mean) ## View the datad2Output:name height Weight 1 Arnab 5.5 89.5 2 Mukul 3.0 85.0 3 Soumik 4.5 80.0 ##Save the molten datasetd1<-melt(d, id=c("name", "year")) ##Now cast the datad2 <-cast(d1, name~variable, mean) ## View the datad2 Output: name height Weight 1 Arnab 5.5 89.5 2 Mukul 3.0 85.0 3 Soumik 4.5 80.0 Note: There are also some other packages like dplyr and tidyr in R that provide functions for preparing tidy data. Advanced Computer Subject Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree System Design Tutorial Decision Tree Introduction with example ML | Linear Regression Reinforcement learning Decision Tree Agents in Artificial Intelligence Activation functions in Neural Networks
[ { "code": null, "e": 25675, "s": 25647, "text": "\n23 Aug, 2018" }, { "code": null, "e": 26000, "s": 25675, "text": "The data that is download from web or other resources are often hard to analyze. It is often needed to do some processing or cleaning of the dataset in order to prepare it for further downstream analysis, predictive modeling and so on. This article discusses several methods in R to convert the raw dataset into a tidy data." }, { "code": null, "e": 26217, "s": 26000, "text": "A Raw data is a dataset that has been downloaded from web (or any other source) and has not been processed yet. Raw data is not ready for use in statistics. It needs various processing tools to be ready for analysis." }, { "code": null, "e": 26389, "s": 26217, "text": "Example: Below is the image of a Raw IRIS Dataset. It does not have any information as what the data is, or what is it representing. This will be done by tidying the data." }, { "code": null, "e": 26497, "s": 26389, "text": "On the other hand, a Tidy dataset (also called cooked data) is the data that has following characteristics:" }, { "code": null, "e": 26545, "s": 26497, "text": "Each variable measured should be in one column." }, { "code": null, "e": 26619, "s": 26545, "text": "Each different observation of that variable should be in a different row." }, { "code": null, "e": 26674, "s": 26619, "text": "There should be one table for each “kind” of variable." }, { "code": null, "e": 26777, "s": 26674, "text": "If there are multiple tables, they should include a column in the table that allows them to be linked." }, { "code": null, "e": 26929, "s": 26777, "text": "Example: Below is the image of a Tidy IRIS Dataset. It contains valuable processed information like column names. The process is explained later below." }, { "code": null, "e": 29727, "s": 26929, "text": "Loading the dataset in RThe first-most step is to get the data for processing. Here the data taken is from IRIS data.Firstly download the data and make it into a dataframe in R.##Provide the link of the dataseturl < -\"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, \"iris.txt\") ##import the data in a dataframed < -read.table(\"iris.txt\", sep = \", \") ##Rename the columnscolnames(d)< -c(\"s_len\", \"s_width\", \"p_len\", \"p_width\", \"variety\")Subsetting Rows and ColumnsNow if only s_len(1st column), p_len(3rd column) and variety(5th column) are required for analysis, then subset these columns and assign the new data to a new dataframe.##subsetting columns with column numberd1 <- d[, c(1, 3, 5)]Subsetting can also be done using column names.##subsetting columns with column namesd1 <- d[, c(\"s_len\", \"p_len\", \"variety\")]Also, If it is required to know the observations that are either of variety “Iris-setosa” or have “sepal length less than 5”.##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == \"Iris-setosa\"), ]Note: The “$” operator is used to subset a column.Sorting the data frame by some variableOrder the dataframe by petal length using the order command.d3 < -d[order(d$p_len), ]Adding new rows and columnsAdd a new column by cbind() and add new row by rbind().##Extract the s_width column of dsepal_width <- d$s_width ##Add the column to d1 dataframe.d1 <- cbind(d1, sepal_width)Getting an overview of the data at a glanceTo get a summarised overview of the processed data, call summary() command on the data-frame.summary(d)Output“: s_len s_width p_len p_width variety \n Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 \n 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 \n Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 \n Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 \n 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 \n Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 \nTo get overview like the type of each variable, total number of observations, and their first few values; use str() command.str(d)Output:'data.frame': 150 obs. of 5 variables:\n $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...\n $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...\n $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...\n $ variety: Factor w/ 3 levels \"Iris-setosa\", ..: 1 1 1 1 1 1 1 1 1 1 ...\n" }, { "code": null, "e": 30322, "s": 29727, "text": "Loading the dataset in RThe first-most step is to get the data for processing. Here the data taken is from IRIS data.Firstly download the data and make it into a dataframe in R.##Provide the link of the dataseturl < -\"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, \"iris.txt\") ##import the data in a dataframed < -read.table(\"iris.txt\", sep = \", \") ##Rename the columnscolnames(d)< -c(\"s_len\", \"s_width\", \"p_len\", \"p_width\", \"variety\")" }, { "code": null, "e": 30416, "s": 30322, "text": "The first-most step is to get the data for processing. Here the data taken is from IRIS data." }, { "code": null, "e": 30894, "s": 30416, "text": "Firstly download the data and make it into a dataframe in R.##Provide the link of the dataseturl < -\"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, \"iris.txt\") ##import the data in a dataframed < -read.table(\"iris.txt\", sep = \", \") ##Rename the columnscolnames(d)< -c(\"s_len\", \"s_width\", \"p_len\", \"p_width\", \"variety\")" }, { "code": "##Provide the link of the dataseturl < -\"http:// archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\" ##download the data in a file iris.txt##will be saved in the working directorydownload.file(url, \"iris.txt\") ##import the data in a dataframed < -read.table(\"iris.txt\", sep = \", \") ##Rename the columnscolnames(d)< -c(\"s_len\", \"s_width\", \"p_len\", \"p_width\", \"variety\")", "e": 31312, "s": 30894, "text": null }, { "code": null, "e": 31944, "s": 31312, "text": "Subsetting Rows and ColumnsNow if only s_len(1st column), p_len(3rd column) and variety(5th column) are required for analysis, then subset these columns and assign the new data to a new dataframe.##subsetting columns with column numberd1 <- d[, c(1, 3, 5)]Subsetting can also be done using column names.##subsetting columns with column namesd1 <- d[, c(\"s_len\", \"p_len\", \"variety\")]Also, If it is required to know the observations that are either of variety “Iris-setosa” or have “sepal length less than 5”.##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == \"Iris-setosa\"), ]Note: The “$” operator is used to subset a column." }, { "code": null, "e": 32174, "s": 31944, "text": "Now if only s_len(1st column), p_len(3rd column) and variety(5th column) are required for analysis, then subset these columns and assign the new data to a new dataframe.##subsetting columns with column numberd1 <- d[, c(1, 3, 5)]" }, { "code": "##subsetting columns with column numberd1 <- d[, c(1, 3, 5)]", "e": 32235, "s": 32174, "text": null }, { "code": null, "e": 32362, "s": 32235, "text": "Subsetting can also be done using column names.##subsetting columns with column namesd1 <- d[, c(\"s_len\", \"p_len\", \"variety\")]" }, { "code": "##subsetting columns with column namesd1 <- d[, c(\"s_len\", \"p_len\", \"variety\")]", "e": 32442, "s": 32362, "text": null }, { "code": null, "e": 32642, "s": 32442, "text": "Also, If it is required to know the observations that are either of variety “Iris-setosa” or have “sepal length less than 5”.##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == \"Iris-setosa\"), ]" }, { "code": "##Subsetting the rowsd2 <- d[(d$s_len < 5 | d$variety == \"Iris-setosa\"), ]", "e": 32717, "s": 32642, "text": null }, { "code": null, "e": 32768, "s": 32717, "text": "Note: The “$” operator is used to subset a column." }, { "code": null, "e": 32893, "s": 32768, "text": "Sorting the data frame by some variableOrder the dataframe by petal length using the order command.d3 < -d[order(d$p_len), ]" }, { "code": null, "e": 32954, "s": 32893, "text": "Order the dataframe by petal length using the order command." }, { "code": "d3 < -d[order(d$p_len), ]", "e": 32980, "s": 32954, "text": null }, { "code": null, "e": 33183, "s": 32980, "text": "Adding new rows and columnsAdd a new column by cbind() and add new row by rbind().##Extract the s_width column of dsepal_width <- d$s_width ##Add the column to d1 dataframe.d1 <- cbind(d1, sepal_width)" }, { "code": null, "e": 33239, "s": 33183, "text": "Add a new column by cbind() and add new row by rbind()." }, { "code": "##Extract the s_width column of dsepal_width <- d$s_width ##Add the column to d1 dataframe.d1 <- cbind(d1, sepal_width)", "e": 33360, "s": 33239, "text": null }, { "code": null, "e": 34607, "s": 33360, "text": "Getting an overview of the data at a glanceTo get a summarised overview of the processed data, call summary() command on the data-frame.summary(d)Output“: s_len s_width p_len p_width variety \n Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 \n 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 \n Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 \n Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 \n 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 \n Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 \nTo get overview like the type of each variable, total number of observations, and their first few values; use str() command.str(d)Output:'data.frame': 150 obs. of 5 variables:\n $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...\n $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...\n $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...\n $ variety: Factor w/ 3 levels \"Iris-setosa\", ..: 1 1 1 1 1 1 1 1 1 1 ...\n" }, { "code": null, "e": 35319, "s": 34607, "text": "To get a summarised overview of the processed data, call summary() command on the data-frame.summary(d)Output“: s_len s_width p_len p_width variety \n Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 \n 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 \n Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 \n Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 \n 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 \n Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 \n" }, { "code": "summary(d)", "e": 35330, "s": 35319, "text": null }, { "code": null, "e": 35339, "s": 35330, "text": "Output“:" }, { "code": null, "e": 35940, "s": 35339, "text": " s_len s_width p_len p_width variety \n Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 Iris-setosa :50 \n 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 Iris-versicolor:50 \n Median :5.800 Median :3.000 Median :4.350 Median :1.300 Iris-virginica :50 \n Mean :5.843 Mean :3.054 Mean :3.759 Mean :1.199 \n 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 \n Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 \n" }, { "code": null, "e": 36433, "s": 35940, "text": "To get overview like the type of each variable, total number of observations, and their first few values; use str() command.str(d)Output:'data.frame': 150 obs. of 5 variables:\n $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...\n $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...\n $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...\n $ variety: Factor w/ 3 levels \"Iris-setosa\", ..: 1 1 1 1 1 1 1 1 1 1 ...\n" }, { "code": "str(d)", "e": 36440, "s": 36433, "text": null }, { "code": null, "e": 36448, "s": 36440, "text": "Output:" }, { "code": null, "e": 36804, "s": 36448, "text": "'data.frame': 150 obs. of 5 variables:\n $ s_len : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n $ s_width: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...\n $ p_len : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...\n $ p_width: num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...\n $ variety: Factor w/ 3 levels \"Iris-setosa\", ..: 1 1 1 1 1 1 1 1 1 1 ...\n" }, { "code": null, "e": 37316, "s": 36804, "text": "Another way of re-organizing data is by using melt and cast functions. They are present in reshape2 package.## Create A Dummy Datasetd<-data.frame( name=c(\"Arnab\", \"Arnab\", \"Soumik\", \"Mukul\", \"Soumik\"), year=c(2011, 2014, 2011, 2015, 2014), height=c(5, 6, 4, 3, 5), Weight=c(90, 89, 76, 85, 84)) ## View the datasetdOutput: name year height Weight\n1 Arnab 2011 5 90\n2 Arnab 2014 6 89\n3 Soumik 2011 4 76\n4 Mukul 2015 3 85\n5 Soumik 2014 5 84\n" }, { "code": "## Create A Dummy Datasetd<-data.frame( name=c(\"Arnab\", \"Arnab\", \"Soumik\", \"Mukul\", \"Soumik\"), year=c(2011, 2014, 2011, 2015, 2014), height=c(5, 6, 4, 3, 5), Weight=c(90, 89, 76, 85, 84)) ## View the datasetd", "e": 37545, "s": 37316, "text": null }, { "code": null, "e": 37553, "s": 37545, "text": "Output:" }, { "code": null, "e": 37722, "s": 37553, "text": " name year height Weight\n1 Arnab 2011 5 90\n2 Arnab 2014 6 89\n3 Soumik 2011 4 76\n4 Mukul 2015 3 85\n5 Soumik 2014 5 84\n" }, { "code": null, "e": 38572, "s": 37722, "text": "Melting of this data means referring some variable as id variable (Others will be taken as measure variables). Now if name and year are taken as id variable and height and weight as measure variables, then there will be 4 columns in the new dataset- name, year, variable and value. For each name and year, there will be the variable to be measured and its value.## Getting the reshape libraryinstall.packages(\"reshape2\")library(reshape2) ## Configure the id variables, name and yearmelt(d, id=c(\"name\", \"year\"))Output: name year variable value\n1 Arnab 2011 height 5\n2 Arnab 2014 height 6\n3 Soumik 2011 height 4\n4 Mukul 2015 height 3\n5 Soumik 2014 height 5\n6 Arnab 2011 Weight 90\n7 Aranb 2014 Weight 89\n8 Soumik 2011 Weight 76\n9 Mukul 2015 Weight 85\n10 Soumik 2014 Weight 84\n" }, { "code": "## Getting the reshape libraryinstall.packages(\"reshape2\")library(reshape2) ## Configure the id variables, name and yearmelt(d, id=c(\"name\", \"year\"))", "e": 38723, "s": 38572, "text": null }, { "code": null, "e": 38731, "s": 38723, "text": "Output:" }, { "code": null, "e": 39062, "s": 38731, "text": " name year variable value\n1 Arnab 2011 height 5\n2 Arnab 2014 height 6\n3 Soumik 2011 height 4\n4 Mukul 2015 height 3\n5 Soumik 2014 height 5\n6 Arnab 2011 Weight 90\n7 Aranb 2014 Weight 89\n8 Soumik 2011 Weight 76\n9 Mukul 2015 Weight 85\n10 Soumik 2014 Weight 84\n" }, { "code": null, "e": 39411, "s": 39062, "text": "Now the molten dataset can be converted in a compact form by cast() function. Compute everyone’s mean height and weight.##Save the molten datasetd1<-melt(d, id=c(\"name\", \"year\")) ##Now cast the datad2 <-cast(d1, name~variable, mean) ## View the datad2Output:name height Weight\n1 Arnab 5.5 89.5\n2 Mukul 3.0 85.0\n3 Soumik 4.5 80.0\n" }, { "code": "##Save the molten datasetd1<-melt(d, id=c(\"name\", \"year\")) ##Now cast the datad2 <-cast(d1, name~variable, mean) ## View the datad2", "e": 39545, "s": 39411, "text": null }, { "code": null, "e": 39553, "s": 39545, "text": "Output:" }, { "code": null, "e": 39642, "s": 39553, "text": "name height Weight\n1 Arnab 5.5 89.5\n2 Mukul 3.0 85.0\n3 Soumik 4.5 80.0\n" }, { "code": null, "e": 39757, "s": 39642, "text": "Note: There are also some other packages like dplyr and tidyr in R that provide functions for preparing tidy data." }, { "code": null, "e": 39783, "s": 39757, "text": "Advanced Computer Subject" }, { "code": null, "e": 39800, "s": 39783, "text": "Machine Learning" }, { "code": null, "e": 39817, "s": 39800, "text": "Machine Learning" }, { "code": null, "e": 39915, "s": 39817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39938, "s": 39915, "text": "ML | Linear Regression" }, { "code": null, "e": 39961, "s": 39938, "text": "Reinforcement learning" }, { "code": null, "e": 39975, "s": 39961, "text": "Decision Tree" }, { "code": null, "e": 39998, "s": 39975, "text": "System Design Tutorial" }, { "code": null, "e": 40038, "s": 39998, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 40061, "s": 40038, "text": "ML | Linear Regression" }, { "code": null, "e": 40084, "s": 40061, "text": "Reinforcement learning" }, { "code": null, "e": 40098, "s": 40084, "text": "Decision Tree" }, { "code": null, "e": 40132, "s": 40098, "text": "Agents in Artificial Intelligence" } ]
Convert minutes to hours/minutes with the help of JQuery - GeeksforGeeks
31 Dec, 2019 The task is to convert the given minutes to Hours/Minutes format with the help of JavaScript. Here, 2 approaches are discussed.Approach 1: Get the input from user. Use Math.floor() method to get the floor value of hours from minutes. Use % operator to get the minutes. Example 1: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> Convert minutes to hours/minutes with the help of JQuery. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> Type Minutes: <input class="mins" /> <br> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN"> </p> <script> var up = document.getElementById('GFG_UP'); var element = document.getElementById("body"); up.innerHTML ="Click on the button to get minutes in Hours/Minutes format."; function GFG_Fun() { // Getting the input from user. var total = $('.mins').val(); // Getting the hours. var hrs = Math.floor(total / 60); // Getting the minutes. var min = total % 60; $('#GFG_DOWN').html(hrs + " Hours and " + min + " Minutes"); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Get the input from user. Use Math.floor() method to get the floor value of hours from minutes. Use % operator to get the minutes. check if the hours are less then 10 then append a zero before the hours. check it for minutes also, if the minutes are less then 10 then append a zero before the minutes. Example 2: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> Convert minutes to hours/minutes with the help of JQuery. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> Type Minutes: <input class="mins" /> <br> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN"> </p> <script> var up = document.getElementById('GFG_UP'); var element = document.getElementById("body"); up.innerHTML = "Click on the button to get minutes in Hours/Minutes format."; function conversion(mins) { // getting the hours. let hrs = Math.floor(mins / 60); // getting the minutes. let min = mins % 60; // formatting the hours. hrs = hrs < 10 ? '0' + hrs : hrs; // formatting the minutes. min = min < 10 ? '0' + min : min; // returning them as a string. return `${hrs}:${min}`; } function GFG_Fun() { var total = $('.mins').val(); $('#GFG_DOWN').html(conversion(total)); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n31 Dec, 2019" }, { "code": null, "e": 26684, "s": 26545, "text": "The task is to convert the given minutes to Hours/Minutes format with the help of JavaScript. Here, 2 approaches are discussed.Approach 1:" }, { "code": null, "e": 26709, "s": 26684, "text": "Get the input from user." }, { "code": null, "e": 26779, "s": 26709, "text": "Use Math.floor() method to get the floor value of hours from minutes." }, { "code": null, "e": 26814, "s": 26779, "text": "Use % operator to get the minutes." }, { "code": null, "e": 26869, "s": 26814, "text": "Example 1: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> Convert minutes to hours/minutes with the help of JQuery. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> Type Minutes: <input class=\"mins\" /> <br> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var up = document.getElementById('GFG_UP'); var element = document.getElementById(\"body\"); up.innerHTML =\"Click on the button to get minutes in Hours/Minutes format.\"; function GFG_Fun() { // Getting the input from user. var total = $('.mins').val(); // Getting the hours. var hrs = Math.floor(total / 60); // Getting the minutes. var min = total % 60; $('#GFG_DOWN').html(hrs + \" Hours and \" + min + \" Minutes\"); } </script></body> </html>", "e": 27971, "s": 26869, "text": null }, { "code": null, "e": 27979, "s": 27971, "text": "Output:" }, { "code": null, "e": 28010, "s": 27979, "text": "Before clicking on the button:" }, { "code": null, "e": 28040, "s": 28010, "text": "After clicking on the button:" }, { "code": null, "e": 28052, "s": 28040, "text": "Approach 2:" }, { "code": null, "e": 28077, "s": 28052, "text": "Get the input from user." }, { "code": null, "e": 28147, "s": 28077, "text": "Use Math.floor() method to get the floor value of hours from minutes." }, { "code": null, "e": 28182, "s": 28147, "text": "Use % operator to get the minutes." }, { "code": null, "e": 28255, "s": 28182, "text": "check if the hours are less then 10 then append a zero before the hours." }, { "code": null, "e": 28353, "s": 28255, "text": "check it for minutes also, if the minutes are less then 10 then append a zero before the minutes." }, { "code": null, "e": 28408, "s": 28353, "text": "Example 2: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> Convert minutes to hours/minutes with the help of JQuery. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> Type Minutes: <input class=\"mins\" /> <br> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var up = document.getElementById('GFG_UP'); var element = document.getElementById(\"body\"); up.innerHTML = \"Click on the button to get minutes in Hours/Minutes format.\"; function conversion(mins) { // getting the hours. let hrs = Math.floor(mins / 60); // getting the minutes. let min = mins % 60; // formatting the hours. hrs = hrs < 10 ? '0' + hrs : hrs; // formatting the minutes. min = min < 10 ? '0' + min : min; // returning them as a string. return `${hrs}:${min}`; } function GFG_Fun() { var total = $('.mins').val(); $('#GFG_DOWN').html(conversion(total)); } </script></body> </html>", "e": 29709, "s": 28408, "text": null }, { "code": null, "e": 29717, "s": 29709, "text": "Output:" }, { "code": null, "e": 29748, "s": 29717, "text": "Before clicking on the button:" }, { "code": null, "e": 29778, "s": 29748, "text": "After clicking on the button:" }, { "code": null, "e": 29794, "s": 29778, "text": "JavaScript-Misc" }, { "code": null, "e": 29805, "s": 29794, "text": "JavaScript" }, { "code": null, "e": 29822, "s": 29805, "text": "Web Technologies" }, { "code": null, "e": 29920, "s": 29822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29960, "s": 29920, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30021, "s": 29960, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30062, "s": 30021, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30084, "s": 30062, "text": "JavaScript | Promises" }, { "code": null, "e": 30138, "s": 30084, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30178, "s": 30138, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30211, "s": 30178, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30254, "s": 30211, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30304, "s": 30254, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Number of ways to choose elements from the array such that their average is K - GeeksforGeeks
03 Mar, 2022 Given an array arr[] of N integers and an integer K. The task is to find the number of ways to select one or more elements from the array such that the average of the selected integers is equal to the given number K. Examples: Input: arr[] = {7, 9, 8, 9}, K = 8 Output: 5 {8}, {7, 9}, {7, 9}, {7, 8, 9} and {7, 8, 9}Input: arr[] = {3, 6, 2, 8, 7, 6, 5, 9}, K = 5 Output: 19Input: arr[] = {6, 6, 9}, K = 8 Output: 0 Simple Approach: A simple solution would be to try for all possibilities since N can be large. Time complexity can be 2N.Efficient Approach: The above approach can be optimized by using dynamic programming to solve this problem. Suppose we are at the i_th index and let val be the current value of that index. We have two possibilities either to choose that element in the answer or discard the element. Hence, we are done now. We will also keep track of the number of elements in our current set of chosen elements. Following is the recursive formula. ways(index, sum, count) = ways(index - 1, sum, count) + ways(index - 1, sum + arr[index], count + 1) Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; #define MAX_INDEX 51#define MAX_SUM 2505 // This dp array is used to store our values// so that we don't have to calculate same// values again and againint dp[MAX_INDEX][MAX_SUM][MAX_INDEX]; int waysutil(int index, int sum, int count, vector<int>& arr, int K){ // Base cases // Index can't be less than 0 if (index < 0) return 0; if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) return 0; int remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) return 0; int average = sum / count; // If we find an average return 1 if (average == K) return 1; } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index][sum][count] != -1) return dp[index][sum][count]; // If we don't pick the current element // simple recur for index -1 int dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 int pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); int total = pick + dontpick; // Store the value for the current function dp[index][sum][count] = total; return total;} // Function to return the number of waysint ways(int N, int K, int* arr){ vector<int> Arr; // Push -1 at the beginning to // make it 1-based indexing Arr.push_back(-1); for (int i = 0; i < N; ++i) { Arr.push_back(arr[i]); } // Initialize dp array by -1 memset(dp, -1, sizeof dp); // Call recursive function // waysutil to calculate total ways int answer = waysutil(N, 0, 0, Arr, K); return answer;} // Driver codeint main(){ int arr[] = { 3, 6, 2, 8, 7, 6, 5, 9 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 5; cout << ways(N, K, arr); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ static int MAX_INDEX = 51; static int MAX_SUM = 2505; // This dp array is used to store our values // so that we don't have to calculate same // values again and again static int[][][] dp = new int[MAX_INDEX][MAX_SUM][MAX_INDEX]; static int waysutil(int index, int sum, int count, Vector<Integer> arr, int K) { // Base cases // Index can't be less than 0 if (index < 0) { return 0; } if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) { return 0; } int remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) { return 0; } int average = sum / count; // If we find an average return 1 if (average == K) { return 1; } } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index][sum][count] != -1) { return dp[index][sum][count]; } // If we don't pick the current element // simple recur for index -1 int dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 int pick = waysutil(index - 1, sum + arr.get(index), count + 1, arr, K); int total = pick + dontpick; // Store the value for the current function dp[index][sum][count] = total; return total; } // Function to return the number of ways static int ways(int N, int K, int[] arr) { Vector<Integer> Arr = new Vector<>(); // Push -1 at the beginning to // make it 1-based indexing Arr.add(-1); for (int i = 0; i < N; ++i) { Arr.add(arr[i]); } // Initialize dp array by -1 for (int i = 0; i < MAX_INDEX; i++) { for (int j = 0; j < MAX_SUM; j++) { for (int l = 0; l < MAX_INDEX; l++) { dp[i][j][l] = -1; } } } // Call recursive function // waysutil to calculate total ways int answer = waysutil(N, 0, 0, Arr, K); return answer; } // Driver code public static void main(String args[]) { int arr[] = {3, 6, 2, 8, 7, 6, 5, 9}; int N = arr.length; int K = 5; System.out.println(ways(N, K, arr)); }} /* This code contributed by PrinciRaj1992 */ # Python implementation of above approachimport numpy as np MAX_INDEX = 51MAX_SUM = 2505 # This dp array is used to store our values# so that we don't have to calculate same# values again and again # Initialize dp array by -1dp = np.ones((MAX_INDEX,MAX_SUM,MAX_INDEX)) * -1; def waysutil(index, sum, count, arr, K) : # Base cases # Index can't be less than 0 if (index < 0) : return 0; if (index == 0) : # No element is picked hence # average cannot be calculated if (count == 0) : return 0; remainder = sum % count; # If remainder is non zero, we cannot # divide the sum by count i.e. the average # will not be an integer if (remainder != 0) : return 0; average = sum // count; # If we find an average return 1 if (average == K) : return 1; # If we have already calculated this function # simply return it instead of calculating it again if (dp[index][sum][count] != -1) : return dp[index][sum][count]; # If we don't pick the current element # simple recur for index -1 dontpick = waysutil(index - 1, sum, count, arr, K); # If we pick the current element add it to # our current sum and increment count by 1 pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); total = pick + dontpick; # Store the value for the current function dp[index][sum][count] = total; return total; # Function to return the number of waysdef ways(N, K, arr) : Arr = []; # Push -1 at the beginning to # make it 1-based indexing Arr.append(-1); for i in range(N) : Arr.append(arr[i]); # Call recursive function # waysutil to calculate total ways answer = waysutil(N, 0, 0, Arr, K); return answer; # Driver codeif __name__ == "__main__" : arr = [ 3, 6, 2, 8, 7, 6, 5, 9 ]; N =len(arr); K = 5; print(ways(N, K, arr)); # This code is contributed by AnkitRai01 // C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ static int MAX_INDEX = 51; static int MAX_SUM = 2505; // This dp array is used to store our values // so that we don't have to calculate same // values again and again static int[,,] dp = new int[MAX_INDEX, MAX_SUM, MAX_INDEX]; static int waysutil(int index, int sum, int count, List<int> arr, int K) { // Base cases // Index can't be less than 0 if (index < 0) { return 0; } if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) { return 0; } int remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) { return 0; } int average = sum / count; // If we find an average return 1 if (average == K) { return 1; } } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index,sum,count] != -1) { return dp[index, sum, count]; } // If we don't pick the current element // simple recur for index -1 int dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 int pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); int total = pick + dontpick; // Store the value for the current function dp[index,sum,count] = total; return total; } // Function to return the number of ways static int ways(int N, int K, int[] arr) { List<int> Arr = new List<int>(); // Push -1 at the beginning to // make it 1-based indexing Arr.Add(-1); for (int i = 0; i < N; ++i) { Arr.Add(arr[i]); } // Initialize dp array by -1 for (int i = 0; i < MAX_INDEX; i++) { for (int j = 0; j < MAX_SUM; j++) { for (int l = 0; l < MAX_INDEX; l++) { dp[i, j, l] = -1; } } } // Call recursive function // waysutil to calculate total ways int answer = waysutil(N, 0, 0, Arr, K); return answer; } // Driver code public static void Main(String []args) { int []arr = {3, 6, 2, 8, 7, 6, 5, 9}; int N = arr.Length; int K = 5; Console.WriteLine(ways(N, K, arr)); }} // This code is contributed by Princi Singh <script>// javascript implementation of the above approach var MAX_INDEX = 51; var MAX_SUM = 2505; // This dp array is used to store our values // so that we don't have to calculate same // values again and again var dp = Array(MAX_INDEX).fill().map(()=>Array(MAX_SUM).fill().map(()=>Array(MAX_INDEX).fill(0)));; function waysutil(index , sum , count, arr , K) { // Base cases // Index can't be less than 0 if (index < 0) { return 0; } if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) { return 0; } var remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) { return 0; } var average = sum / count; // If we find an average return 1 if (average == K) { return 1; } } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index][sum][count] != -1) { return dp[index][sum][count]; } // If we don't pick the current element // simple recur for index -1 var dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 var pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); var total = pick + dontpick; // Store the value for the current function dp[index][sum][count] = total; return total; } // Function to return the number of ways function ways(N , K, arr) { var Arr = []; // Push -1 at the beginning to // make it 1-based indexing Arr.push(-1); for (i = 0; i < N; ++i) { Arr.push(arr[i]); } // Initialize dp array by -1 for (i = 0; i < MAX_INDEX; i++) { for (j = 0; j < MAX_SUM; j++) { for (l = 0; l < MAX_INDEX; l++) { dp[i][j][l] = -1; } } } // Call recursive function // waysutil to calculate total ways var answer = waysutil(N, 0, 0, Arr, K); return answer; } // Driver code var arr = [ 3, 6, 2, 8, 7, 6, 5, 9 ]; var N = arr.length; var K = 5; document.write(ways(N, K, arr)); // This code contributed by gauravrajput1</script> 19 Time Complexity: O(MAX_INDEX * MAX_SUM * MAX_INDEX)Auxiliary Space: O(MAX_INDEX * MAX_SUM * MAX_INDEX) ankthon princiraj1992 princi singh GauravRajput1 singhh3010 Arrays Dynamic Programming Recursion Arrays Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26497, "s": 26469, "text": "\n03 Mar, 2022" }, { "code": null, "e": 26715, "s": 26497, "text": "Given an array arr[] of N integers and an integer K. The task is to find the number of ways to select one or more elements from the array such that the average of the selected integers is equal to the given number K. " }, { "code": null, "e": 26727, "s": 26715, "text": "Examples: " }, { "code": null, "e": 26917, "s": 26727, "text": "Input: arr[] = {7, 9, 8, 9}, K = 8 Output: 5 {8}, {7, 9}, {7, 9}, {7, 8, 9} and {7, 8, 9}Input: arr[] = {3, 6, 2, 8, 7, 6, 5, 9}, K = 5 Output: 19Input: arr[] = {6, 6, 9}, K = 8 Output: 0 " }, { "code": null, "e": 27435, "s": 26917, "text": "Simple Approach: A simple solution would be to try for all possibilities since N can be large. Time complexity can be 2N.Efficient Approach: The above approach can be optimized by using dynamic programming to solve this problem. Suppose we are at the i_th index and let val be the current value of that index. We have two possibilities either to choose that element in the answer or discard the element. Hence, we are done now. We will also keep track of the number of elements in our current set of chosen elements. " }, { "code": null, "e": 27472, "s": 27435, "text": "Following is the recursive formula. " }, { "code": null, "e": 27589, "s": 27472, "text": "ways(index, sum, count) \n = ways(index - 1, sum, count) \n + ways(index - 1, sum + arr[index], count + 1)" }, { "code": null, "e": 27642, "s": 27589, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27646, "s": 27642, "text": "C++" }, { "code": null, "e": 27651, "s": 27646, "text": "Java" }, { "code": null, "e": 27659, "s": 27651, "text": "Python3" }, { "code": null, "e": 27662, "s": 27659, "text": "C#" }, { "code": null, "e": 27673, "s": 27662, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; #define MAX_INDEX 51#define MAX_SUM 2505 // This dp array is used to store our values// so that we don't have to calculate same// values again and againint dp[MAX_INDEX][MAX_SUM][MAX_INDEX]; int waysutil(int index, int sum, int count, vector<int>& arr, int K){ // Base cases // Index can't be less than 0 if (index < 0) return 0; if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) return 0; int remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) return 0; int average = sum / count; // If we find an average return 1 if (average == K) return 1; } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index][sum][count] != -1) return dp[index][sum][count]; // If we don't pick the current element // simple recur for index -1 int dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 int pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); int total = pick + dontpick; // Store the value for the current function dp[index][sum][count] = total; return total;} // Function to return the number of waysint ways(int N, int K, int* arr){ vector<int> Arr; // Push -1 at the beginning to // make it 1-based indexing Arr.push_back(-1); for (int i = 0; i < N; ++i) { Arr.push_back(arr[i]); } // Initialize dp array by -1 memset(dp, -1, sizeof dp); // Call recursive function // waysutil to calculate total ways int answer = waysutil(N, 0, 0, Arr, K); return answer;} // Driver codeint main(){ int arr[] = { 3, 6, 2, 8, 7, 6, 5, 9 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 5; cout << ways(N, K, arr); return 0;}", "e": 29859, "s": 27673, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ static int MAX_INDEX = 51; static int MAX_SUM = 2505; // This dp array is used to store our values // so that we don't have to calculate same // values again and again static int[][][] dp = new int[MAX_INDEX][MAX_SUM][MAX_INDEX]; static int waysutil(int index, int sum, int count, Vector<Integer> arr, int K) { // Base cases // Index can't be less than 0 if (index < 0) { return 0; } if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) { return 0; } int remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) { return 0; } int average = sum / count; // If we find an average return 1 if (average == K) { return 1; } } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index][sum][count] != -1) { return dp[index][sum][count]; } // If we don't pick the current element // simple recur for index -1 int dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 int pick = waysutil(index - 1, sum + arr.get(index), count + 1, arr, K); int total = pick + dontpick; // Store the value for the current function dp[index][sum][count] = total; return total; } // Function to return the number of ways static int ways(int N, int K, int[] arr) { Vector<Integer> Arr = new Vector<>(); // Push -1 at the beginning to // make it 1-based indexing Arr.add(-1); for (int i = 0; i < N; ++i) { Arr.add(arr[i]); } // Initialize dp array by -1 for (int i = 0; i < MAX_INDEX; i++) { for (int j = 0; j < MAX_SUM; j++) { for (int l = 0; l < MAX_INDEX; l++) { dp[i][j][l] = -1; } } } // Call recursive function // waysutil to calculate total ways int answer = waysutil(N, 0, 0, Arr, K); return answer; } // Driver code public static void main(String args[]) { int arr[] = {3, 6, 2, 8, 7, 6, 5, 9}; int N = arr.length; int K = 5; System.out.println(ways(N, K, arr)); }} /* This code contributed by PrinciRaj1992 */", "e": 32796, "s": 29859, "text": null }, { "code": "# Python implementation of above approachimport numpy as np MAX_INDEX = 51MAX_SUM = 2505 # This dp array is used to store our values# so that we don't have to calculate same# values again and again # Initialize dp array by -1dp = np.ones((MAX_INDEX,MAX_SUM,MAX_INDEX)) * -1; def waysutil(index, sum, count, arr, K) : # Base cases # Index can't be less than 0 if (index < 0) : return 0; if (index == 0) : # No element is picked hence # average cannot be calculated if (count == 0) : return 0; remainder = sum % count; # If remainder is non zero, we cannot # divide the sum by count i.e. the average # will not be an integer if (remainder != 0) : return 0; average = sum // count; # If we find an average return 1 if (average == K) : return 1; # If we have already calculated this function # simply return it instead of calculating it again if (dp[index][sum][count] != -1) : return dp[index][sum][count]; # If we don't pick the current element # simple recur for index -1 dontpick = waysutil(index - 1, sum, count, arr, K); # If we pick the current element add it to # our current sum and increment count by 1 pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); total = pick + dontpick; # Store the value for the current function dp[index][sum][count] = total; return total; # Function to return the number of waysdef ways(N, K, arr) : Arr = []; # Push -1 at the beginning to # make it 1-based indexing Arr.append(-1); for i in range(N) : Arr.append(arr[i]); # Call recursive function # waysutil to calculate total ways answer = waysutil(N, 0, 0, Arr, K); return answer; # Driver codeif __name__ == \"__main__\" : arr = [ 3, 6, 2, 8, 7, 6, 5, 9 ]; N =len(arr); K = 5; print(ways(N, K, arr)); # This code is contributed by AnkitRai01", "e": 34904, "s": 32796, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ static int MAX_INDEX = 51; static int MAX_SUM = 2505; // This dp array is used to store our values // so that we don't have to calculate same // values again and again static int[,,] dp = new int[MAX_INDEX, MAX_SUM, MAX_INDEX]; static int waysutil(int index, int sum, int count, List<int> arr, int K) { // Base cases // Index can't be less than 0 if (index < 0) { return 0; } if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) { return 0; } int remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) { return 0; } int average = sum / count; // If we find an average return 1 if (average == K) { return 1; } } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index,sum,count] != -1) { return dp[index, sum, count]; } // If we don't pick the current element // simple recur for index -1 int dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 int pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); int total = pick + dontpick; // Store the value for the current function dp[index,sum,count] = total; return total; } // Function to return the number of ways static int ways(int N, int K, int[] arr) { List<int> Arr = new List<int>(); // Push -1 at the beginning to // make it 1-based indexing Arr.Add(-1); for (int i = 0; i < N; ++i) { Arr.Add(arr[i]); } // Initialize dp array by -1 for (int i = 0; i < MAX_INDEX; i++) { for (int j = 0; j < MAX_SUM; j++) { for (int l = 0; l < MAX_INDEX; l++) { dp[i, j, l] = -1; } } } // Call recursive function // waysutil to calculate total ways int answer = waysutil(N, 0, 0, Arr, K); return answer; } // Driver code public static void Main(String []args) { int []arr = {3, 6, 2, 8, 7, 6, 5, 9}; int N = arr.Length; int K = 5; Console.WriteLine(ways(N, K, arr)); }} // This code is contributed by Princi Singh", "e": 37847, "s": 34904, "text": null }, { "code": "<script>// javascript implementation of the above approach var MAX_INDEX = 51; var MAX_SUM = 2505; // This dp array is used to store our values // so that we don't have to calculate same // values again and again var dp = Array(MAX_INDEX).fill().map(()=>Array(MAX_SUM).fill().map(()=>Array(MAX_INDEX).fill(0)));; function waysutil(index , sum , count, arr , K) { // Base cases // Index can't be less than 0 if (index < 0) { return 0; } if (index == 0) { // No element is picked hence // average cannot be calculated if (count == 0) { return 0; } var remainder = sum % count; // If remainder is non zero, we cannot // divide the sum by count i.e. the average // will not be an integer if (remainder != 0) { return 0; } var average = sum / count; // If we find an average return 1 if (average == K) { return 1; } } // If we have already calculated this function // simply return it instead of calculating it again if (dp[index][sum][count] != -1) { return dp[index][sum][count]; } // If we don't pick the current element // simple recur for index -1 var dontpick = waysutil(index - 1, sum, count, arr, K); // If we pick the current element add it to // our current sum and increment count by 1 var pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K); var total = pick + dontpick; // Store the value for the current function dp[index][sum][count] = total; return total; } // Function to return the number of ways function ways(N , K, arr) { var Arr = []; // Push -1 at the beginning to // make it 1-based indexing Arr.push(-1); for (i = 0; i < N; ++i) { Arr.push(arr[i]); } // Initialize dp array by -1 for (i = 0; i < MAX_INDEX; i++) { for (j = 0; j < MAX_SUM; j++) { for (l = 0; l < MAX_INDEX; l++) { dp[i][j][l] = -1; } } } // Call recursive function // waysutil to calculate total ways var answer = waysutil(N, 0, 0, Arr, K); return answer; } // Driver code var arr = [ 3, 6, 2, 8, 7, 6, 5, 9 ]; var N = arr.length; var K = 5; document.write(ways(N, K, arr)); // This code contributed by gauravrajput1</script>", "e": 40491, "s": 37847, "text": null }, { "code": null, "e": 40494, "s": 40491, "text": "19" }, { "code": null, "e": 40600, "s": 40496, "text": "Time Complexity: O(MAX_INDEX * MAX_SUM * MAX_INDEX)Auxiliary Space: O(MAX_INDEX * MAX_SUM * MAX_INDEX) " }, { "code": null, "e": 40608, "s": 40600, "text": "ankthon" }, { "code": null, "e": 40622, "s": 40608, "text": "princiraj1992" }, { "code": null, "e": 40635, "s": 40622, "text": "princi singh" }, { "code": null, "e": 40649, "s": 40635, "text": "GauravRajput1" }, { "code": null, "e": 40660, "s": 40649, "text": "singhh3010" }, { "code": null, "e": 40667, "s": 40660, "text": "Arrays" }, { "code": null, "e": 40687, "s": 40667, "text": "Dynamic Programming" }, { "code": null, "e": 40697, "s": 40687, "text": "Recursion" }, { "code": null, "e": 40704, "s": 40697, "text": "Arrays" }, { "code": null, "e": 40724, "s": 40704, "text": "Dynamic Programming" }, { "code": null, "e": 40734, "s": 40724, "text": "Recursion" }, { "code": null, "e": 40832, "s": 40734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40900, "s": 40832, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40944, "s": 40900, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40992, "s": 40944, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 41015, "s": 40992, "text": "Introduction to Arrays" }, { "code": null, "e": 41047, "s": 41015, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41076, "s": 41047, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 41106, "s": 41076, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41140, "s": 41106, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 41171, "s": 41140, "text": "Bellman–Ford Algorithm | DP-23" } ]
Project | kNN | Classifying IRIS Dataset - GeeksforGeeks
19 Jan, 2022 Introduction | kNN Algorithm Statistical learning refers to a collection of mathematical and computation tools to understand data.In what is often called supervised learning, the goal is to estimate or predict an output based on one or more inputs.The inputs have many names, like predictors, independent variables, features, and variables being called common.The output or outputs are often called response variables, or dependent variables.If the response is quantitative – say, a number that measures weight or height, we call these problems regression problems.If the response is qualitative– say, yes or no, or blue or green, we call these problems classification problems.This case study deals with one specific approach to classification.The goal is to set up a classifier such that when it’s presented with a new observation whose category is not known, it will attempt to assign that observation to a category, or a class, based on the observations for which it does know the true category.This specific method is known as the k-Nearest Neighbors classifier, or kNN for short.Given a positive integer k, say 5, and a new data point, it first identifies those k points in the data that are nearest to the point and classifies the new data point as belonging to the most common class among those k neighbors.Aim: Build our very own k – Nearest Neighbor classifier to classify data from the IRIS dataset of scikit-learn. Distance between two points We are going to write a function, which will find the distance between two given 2-D points in the x-y plane.We will import numpy, to take help of numpy arrays for storing the coordinates.Finding the distance between two points will help in finding the nearest neighbor of the input point. Python import numpy as np def distance(p1, p2): return np.sqrt(np.sum(np.power(p2-p1, 2))) #distance between two pointsp1 = np.array([1, 1]) #coordinate x = 1, y = 1p2 = np.array([4, 4]) #coordinate x = 4, y = 4distance(p1, p2) Majority vote counter We will create a 3 x 3 matrix of points with the help of numpy array to build the environment of dispersed points in the plane.We will also create a function called majority_vote() to find the highest count/vote of a particular vote list, e.g ( 1, 2, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 3, 2, 3) etc.This is indirectly the mode of the given data, so can also be calculated with the help of scipy statistics module.We will create another function called majority_vote_short() which will perform the same functionality as majority_vote() but will make use of mode() from scipy.stats.Both these functions will be necessary in predicting the points later. Our aim is to build a kNN classifier, so we need to develop an algorithm to find the nearest neighbours of a given set of points.Suppose we need to insert a point into x-y plane within an environment of given set of existing points.We will have to classify the point we wish to insert into one of the category of the existing points and then insert accordingly.So, we will build a function find_nearest_neighbours() to find the nearest neighbor of the given point.It will take in (i)The point we wish to insert (ii)set of existing points and (iii)k helps with the indices, as parameters to the function.We will visualize the situation by plotting the x-y plane filled with points with the help of matplotlib. Python import numpy as npimport randomimport scipy.stats as ssimport matplotlib.pyplot as plt points = np.array([[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]) #points = existing pointsp = np.array([2.5, 2]) #p = point we wish to insert def majority_vote(votes): vote_counts = {} for vote in votes: if vote in vote_counts: vote_counts[vote]+= 1 else: vote_counts[vote]= 1 winners = [] max_count = max(vote_counts.values()) for vote, count in vote_counts.items(): if count == max_count: winners.append(vote) return random.choice(winners) #returns winner randomly if there are more than 1 winner #>>>votes =[1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 3, 2, 2, 2, 3, 2, 3, 1, 1, 2]#sample vote counts above# >>>vote_counts = majority_vote(votes) def majority_vote_short(votes): mode, count = ss.mstats.mode(votes) return mode def find_nearest_neighbours(p, points, k = 5): #algorithm to find the nearest neighbours distances = np.zeros(points.shape[0]) for i in range(len(distances)): distances[i]= distance(p, points[i]) ind = np.argsort(distances) #returns index, according to sorted values in array return ind[:k] ind = find_nearest_neighbours(p, points, 2);print(points[ind]) #gives the nearest neighbour's for this sample case plt.plot(points[:, 0], points[:, 1], "ro")plt.plot(p[0], p[1], "bo")plt.axis([0.5, 3.5, 0.5, 3.5])plt.show() kNN Predict around Synthetic Data After finding the nearest neighbors, we will have to predict the category of the input point.We will build a function called knn_predict() which will predict the category of the point we wish to insert.We can build another function called generate_synth_data() to generate synthetic points in the x-y plane. Python import numpy as npimport randomimport scipy.stats as ssimport matplotlib.pyplot as plt ''' add the functions and libraries from previous programmes ''' def knn_predict(p, points, outcomes, k = 5): ind = find_nearest_neighbours(p, points, k) return majority_vote(outcomes[ind]) outcomes = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1])knn_predict(np.array([2.5, 2.7]), points, outcomes, k = 2) def generate_synth_data(n = 50): points = np.concatenate((ss.norm(0, 1).rvs((n, 2)), ss.norm(1, 1).rvs((n, 2))), axis = 0) outcomes = np.concatenate((np.repeat(0, n), np.repeat(1, n))) return (points, outcomes) n = 20plt.figure()plt.plot(points[:n, 0], points[:n, 1], "ro")plt.plot(points[n:, 0], points[n:, 1], "bo")plt.show() kNN Prediction GRID We will build a function called make_prediction_grid() which will make a grid and allot the different class of points in the grid.Another function plot_prediction_grid() must be created to plot the outputs of make_prediction_grid() using matplotlib. Python import numpy as npimport randomimport scipy.stats as ssimport matplotlib.pyplot as plt def make_prediction_grid(predictors, outcomes, limits, h, k): (x_min, x_max, y_min, y_max) = limits xs = np.arange(x_min, x_max, h) ys = np.arange(y_min, y_max, h) xx, yy = np.meshgrid(xs, ys) prediction_grid = np.zeros(xx.shape, dtype = int) for i, x in enumerate(xs): for j, y in enumerate(ys): p = np.array([x, y]) prediction_grid[j, i] = knn_predict(p, predictors, outcomes, k) return (xx, yy, prediction_grid) def plot_prediction_grid (xx, yy, prediction_grid, filename): """ Plot KNN predictions for every point on the grid.""" from matplotlib.colors import ListedColormap background_colormap = ListedColormap (["hotpink", "lightskyblue", "yellowgreen"]) observation_colormap = ListedColormap (["red", "blue", "green"]) plt.figure(figsize =(10, 10)) plt.pcolormesh(xx, yy, prediction_grid, cmap = background_colormap, alpha = 0.5) plt.scatter(predictors[:, 0], predictors [:, 1], c = outcomes, cmap = observation_colormap, s = 50) plt.xlabel('Variable 1'); plt.ylabel('Variable 2') plt.xticks(()); plt.yticks(()) plt.xlim (np.min(xx), np.max(xx)) plt.ylim (np.min(yy), np.max(yy)) plt.savefig(filename) (predictors, outcomes) = generate_synth_data()# >>>predictors.shape# >>>outcomes.shapek = 5; filename ="knn_synth_5.pdf"; limits =(-3, 4, -3, 4); h = 0.1(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)plot_prediction_grid(xx, yy, prediction_grid, filename)plt.show() Output: The plot shown here is a grid of two class, visually shown as pink and green.We tried to predict the class of the points based on their position and environment.The green points must fall in the green bricks of the grid and the red in the pink bricks of the grid.Look at the enlarged view to visually check the classifiers work. Classifying the IRIS Dataset We will test our classifier on a scikit learn dataset, called “IRIS”.For importing “IRIS”, we need to import datasets from sklearn and call the function datasets.load_iris().The “IRIS” dataset holds information on sepal length, sepal width, petal length & petal width for three different class of Iris flower – Iris-Setosa, Iris-Versicolour & Iris-Verginica.Based on the data from the dataset, we need to classify and visualize them using our classifier.The Sci-kit learn (sklearn) library already holds a pre built classifier.We will compare both the classifiers, [scikitlearn vs the one that we built] and check/compare prediction accuracy of both the classifier . Python from sklearn import datasetsimport numpy as npimport randomimport matplotlib.pyplot as plt iris = datasets.load_iris() # >>>iris["data"]predictors = iris.data[:, 0:2]outcomes = iris.target plt.plot(predictors[outcomes == 0][:, 0], predictors[outcomes == 0][:, 1], "ro")plt.plot(predictors[outcomes == 1][:, 0], predictors[outcomes == 1][:, 1], "go")plt.plot(predictors[outcomes == 2][:, 0], predictors[outcomes == 2][:, 1], "bo") k = 5; filename ="iris_grid.pdf"; limits =(4, 8, 1.5, 4.5); h = 0.1(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)plot_prediction_grid(xx, yy, prediction_grid, filename)plt.show() from sklearn.neighbors import KNeighborsClassifier #predictions from scikitknn = KNeighborsClassifier(n_neighbors = 5)knn.fit(predictors, outcomes)sk_predictions = knn.predict(predictors) my_predictions = np.array([knn_predict(p, predictors, outcomes, 5) for p in predictors]) # >>>sk_predictions == my_predictions # >>>np.mean(sk_predictions == my_predictions)print(" prediction by scikit learn : ")print(100 * np.mean(sk_predictions == outcomes))print(" prediction by own model : ")print(100 * np.mean(my_predictions == outcomes)) # our homemade predicter is actually somewhat better Output: It seems from the output that our classifier is actually performing better than the sklearn classifier.Reference : edX – HarvardX – Using Python for Research This article is contributed by Amaryta Ranjan Saikia. 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. rkbhola5 Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Characteristics of Internet of Things Advantages and Disadvantages of OOP Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Election algorithm and distributed processing Introduction to Internet of Things (IoT) | Set 1 Introduction to Electronic Mail Communication Models in IoT (Internet of Things ) Introduction to Parallel Computing
[ { "code": null, "e": 25917, "s": 25889, "text": "\n19 Jan, 2022" }, { "code": null, "e": 25946, "s": 25917, "text": "Introduction | kNN Algorithm" }, { "code": null, "e": 27345, "s": 25946, "text": "Statistical learning refers to a collection of mathematical and computation tools to understand data.In what is often called supervised learning, the goal is to estimate or predict an output based on one or more inputs.The inputs have many names, like predictors, independent variables, features, and variables being called common.The output or outputs are often called response variables, or dependent variables.If the response is quantitative – say, a number that measures weight or height, we call these problems regression problems.If the response is qualitative– say, yes or no, or blue or green, we call these problems classification problems.This case study deals with one specific approach to classification.The goal is to set up a classifier such that when it’s presented with a new observation whose category is not known, it will attempt to assign that observation to a category, or a class, based on the observations for which it does know the true category.This specific method is known as the k-Nearest Neighbors classifier, or kNN for short.Given a positive integer k, say 5, and a new data point, it first identifies those k points in the data that are nearest to the point and classifies the new data point as belonging to the most common class among those k neighbors.Aim: Build our very own k – Nearest Neighbor classifier to classify data from the IRIS dataset of scikit-learn. " }, { "code": null, "e": 27373, "s": 27345, "text": "Distance between two points" }, { "code": null, "e": 27665, "s": 27373, "text": "We are going to write a function, which will find the distance between two given 2-D points in the x-y plane.We will import numpy, to take help of numpy arrays for storing the coordinates.Finding the distance between two points will help in finding the nearest neighbor of the input point. " }, { "code": null, "e": 27672, "s": 27665, "text": "Python" }, { "code": "import numpy as np def distance(p1, p2): return np.sqrt(np.sum(np.power(p2-p1, 2))) #distance between two pointsp1 = np.array([1, 1]) #coordinate x = 1, y = 1p2 = np.array([4, 4]) #coordinate x = 4, y = 4distance(p1, p2)", "e": 27900, "s": 27672, "text": null }, { "code": null, "e": 27922, "s": 27900, "text": "Majority vote counter" }, { "code": null, "e": 29282, "s": 27922, "text": "We will create a 3 x 3 matrix of points with the help of numpy array to build the environment of dispersed points in the plane.We will also create a function called majority_vote() to find the highest count/vote of a particular vote list, e.g ( 1, 2, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 3, 2, 3) etc.This is indirectly the mode of the given data, so can also be calculated with the help of scipy statistics module.We will create another function called majority_vote_short() which will perform the same functionality as majority_vote() but will make use of mode() from scipy.stats.Both these functions will be necessary in predicting the points later. Our aim is to build a kNN classifier, so we need to develop an algorithm to find the nearest neighbours of a given set of points.Suppose we need to insert a point into x-y plane within an environment of given set of existing points.We will have to classify the point we wish to insert into one of the category of the existing points and then insert accordingly.So, we will build a function find_nearest_neighbours() to find the nearest neighbor of the given point.It will take in (i)The point we wish to insert (ii)set of existing points and (iii)k helps with the indices, as parameters to the function.We will visualize the situation by plotting the x-y plane filled with points with the help of matplotlib. " }, { "code": null, "e": 29289, "s": 29282, "text": "Python" }, { "code": "import numpy as npimport randomimport scipy.stats as ssimport matplotlib.pyplot as plt points = np.array([[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]) #points = existing pointsp = np.array([2.5, 2]) #p = point we wish to insert def majority_vote(votes): vote_counts = {} for vote in votes: if vote in vote_counts: vote_counts[vote]+= 1 else: vote_counts[vote]= 1 winners = [] max_count = max(vote_counts.values()) for vote, count in vote_counts.items(): if count == max_count: winners.append(vote) return random.choice(winners) #returns winner randomly if there are more than 1 winner #>>>votes =[1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 3, 2, 2, 2, 3, 2, 3, 1, 1, 2]#sample vote counts above# >>>vote_counts = majority_vote(votes) def majority_vote_short(votes): mode, count = ss.mstats.mode(votes) return mode def find_nearest_neighbours(p, points, k = 5): #algorithm to find the nearest neighbours distances = np.zeros(points.shape[0]) for i in range(len(distances)): distances[i]= distance(p, points[i]) ind = np.argsort(distances) #returns index, according to sorted values in array return ind[:k] ind = find_nearest_neighbours(p, points, 2);print(points[ind]) #gives the nearest neighbour's for this sample case plt.plot(points[:, 0], points[:, 1], \"ro\")plt.plot(p[0], p[1], \"bo\")plt.axis([0.5, 3.5, 0.5, 3.5])plt.show()", "e": 30758, "s": 29289, "text": null }, { "code": null, "e": 30792, "s": 30758, "text": "kNN Predict around Synthetic Data" }, { "code": null, "e": 31102, "s": 30792, "text": "After finding the nearest neighbors, we will have to predict the category of the input point.We will build a function called knn_predict() which will predict the category of the point we wish to insert.We can build another function called generate_synth_data() to generate synthetic points in the x-y plane. " }, { "code": null, "e": 31109, "s": 31102, "text": "Python" }, { "code": "import numpy as npimport randomimport scipy.stats as ssimport matplotlib.pyplot as plt ''' add the functions and libraries from previous programmes ''' def knn_predict(p, points, outcomes, k = 5): ind = find_nearest_neighbours(p, points, k) return majority_vote(outcomes[ind]) outcomes = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1])knn_predict(np.array([2.5, 2.7]), points, outcomes, k = 2) def generate_synth_data(n = 50): points = np.concatenate((ss.norm(0, 1).rvs((n, 2)), ss.norm(1, 1).rvs((n, 2))), axis = 0) outcomes = np.concatenate((np.repeat(0, n), np.repeat(1, n))) return (points, outcomes) n = 20plt.figure()plt.plot(points[:n, 0], points[:n, 1], \"ro\")plt.plot(points[n:, 0], points[n:, 1], \"bo\")plt.show()", "e": 31836, "s": 31109, "text": null }, { "code": null, "e": 31856, "s": 31836, "text": "kNN Prediction GRID" }, { "code": null, "e": 32107, "s": 31856, "text": "We will build a function called make_prediction_grid() which will make a grid and allot the different class of points in the grid.Another function plot_prediction_grid() must be created to plot the outputs of make_prediction_grid() using matplotlib. " }, { "code": null, "e": 32114, "s": 32107, "text": "Python" }, { "code": "import numpy as npimport randomimport scipy.stats as ssimport matplotlib.pyplot as plt def make_prediction_grid(predictors, outcomes, limits, h, k): (x_min, x_max, y_min, y_max) = limits xs = np.arange(x_min, x_max, h) ys = np.arange(y_min, y_max, h) xx, yy = np.meshgrid(xs, ys) prediction_grid = np.zeros(xx.shape, dtype = int) for i, x in enumerate(xs): for j, y in enumerate(ys): p = np.array([x, y]) prediction_grid[j, i] = knn_predict(p, predictors, outcomes, k) return (xx, yy, prediction_grid) def plot_prediction_grid (xx, yy, prediction_grid, filename): \"\"\" Plot KNN predictions for every point on the grid.\"\"\" from matplotlib.colors import ListedColormap background_colormap = ListedColormap ([\"hotpink\", \"lightskyblue\", \"yellowgreen\"]) observation_colormap = ListedColormap ([\"red\", \"blue\", \"green\"]) plt.figure(figsize =(10, 10)) plt.pcolormesh(xx, yy, prediction_grid, cmap = background_colormap, alpha = 0.5) plt.scatter(predictors[:, 0], predictors [:, 1], c = outcomes, cmap = observation_colormap, s = 50) plt.xlabel('Variable 1'); plt.ylabel('Variable 2') plt.xticks(()); plt.yticks(()) plt.xlim (np.min(xx), np.max(xx)) plt.ylim (np.min(yy), np.max(yy)) plt.savefig(filename) (predictors, outcomes) = generate_synth_data()# >>>predictors.shape# >>>outcomes.shapek = 5; filename =\"knn_synth_5.pdf\"; limits =(-3, 4, -3, 4); h = 0.1(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)plot_prediction_grid(xx, yy, prediction_grid, filename)plt.show()", "e": 33700, "s": 32114, "text": null }, { "code": null, "e": 34038, "s": 33700, "text": "Output: The plot shown here is a grid of two class, visually shown as pink and green.We tried to predict the class of the points based on their position and environment.The green points must fall in the green bricks of the grid and the red in the pink bricks of the grid.Look at the enlarged view to visually check the classifiers work. " }, { "code": null, "e": 34067, "s": 34038, "text": "Classifying the IRIS Dataset" }, { "code": null, "e": 34736, "s": 34067, "text": "We will test our classifier on a scikit learn dataset, called “IRIS”.For importing “IRIS”, we need to import datasets from sklearn and call the function datasets.load_iris().The “IRIS” dataset holds information on sepal length, sepal width, petal length & petal width for three different class of Iris flower – Iris-Setosa, Iris-Versicolour & Iris-Verginica.Based on the data from the dataset, we need to classify and visualize them using our classifier.The Sci-kit learn (sklearn) library already holds a pre built classifier.We will compare both the classifiers, [scikitlearn vs the one that we built] and check/compare prediction accuracy of both the classifier . " }, { "code": null, "e": 34743, "s": 34736, "text": "Python" }, { "code": "from sklearn import datasetsimport numpy as npimport randomimport matplotlib.pyplot as plt iris = datasets.load_iris() # >>>iris[\"data\"]predictors = iris.data[:, 0:2]outcomes = iris.target plt.plot(predictors[outcomes == 0][:, 0], predictors[outcomes == 0][:, 1], \"ro\")plt.plot(predictors[outcomes == 1][:, 0], predictors[outcomes == 1][:, 1], \"go\")plt.plot(predictors[outcomes == 2][:, 0], predictors[outcomes == 2][:, 1], \"bo\") k = 5; filename =\"iris_grid.pdf\"; limits =(4, 8, 1.5, 4.5); h = 0.1(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)plot_prediction_grid(xx, yy, prediction_grid, filename)plt.show() from sklearn.neighbors import KNeighborsClassifier #predictions from scikitknn = KNeighborsClassifier(n_neighbors = 5)knn.fit(predictors, outcomes)sk_predictions = knn.predict(predictors) my_predictions = np.array([knn_predict(p, predictors, outcomes, 5) for p in predictors]) # >>>sk_predictions == my_predictions # >>>np.mean(sk_predictions == my_predictions)print(\" prediction by scikit learn : \")print(100 * np.mean(sk_predictions == outcomes))print(\" prediction by own model : \")print(100 * np.mean(my_predictions == outcomes)) # our homemade predicter is actually somewhat better", "e": 35988, "s": 34743, "text": null }, { "code": null, "e": 36113, "s": 35988, "text": "Output: It seems from the output that our classifier is actually performing better than the sklearn classifier.Reference : " }, { "code": null, "e": 36156, "s": 36113, "text": "edX – HarvardX – Using Python for Research" }, { "code": null, "e": 36586, "s": 36156, "text": "This article is contributed by Amaryta Ranjan Saikia. 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": 36595, "s": 36586, "text": "rkbhola5" }, { "code": null, "e": 36600, "s": 36595, "text": "Misc" }, { "code": null, "e": 36605, "s": 36600, "text": "Misc" }, { "code": null, "e": 36610, "s": 36605, "text": "Misc" }, { "code": null, "e": 36708, "s": 36610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36729, "s": 36708, "text": "Activation Functions" }, { "code": null, "e": 36767, "s": 36729, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 36803, "s": 36767, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 36838, "s": 36803, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 36877, "s": 36838, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 36923, "s": 36877, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 36972, "s": 36923, "text": "Introduction to Internet of Things (IoT) | Set 1" }, { "code": null, "e": 37004, "s": 36972, "text": "Introduction to Electronic Mail" }, { "code": null, "e": 37054, "s": 37004, "text": "Communication Models in IoT (Internet of Things )" } ]
Lodash _.zip() Method - GeeksforGeeks
01 Sep, 2020 The _.zip() method is used to create an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second element of the given arrays, and so on. Syntax: _.zip([arrays]) Parameters: This method accepts a single parameter as mentioned above and described below: [arrays]: This parameter holds the arrays to process. Return Value: This method returns the new array of regrouped elements. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.zip() method let gfg = _.zip(['a', 'b', 'c'], [1, 2, 3], [true, false, true]); // Printing the output console.log(gfg) Output: a,1,true,b,2,false,c,3,true Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.zip() // method let gfg = _.zip(['Amit', 'Akash', 'Avijit'], [1, 2, 3], ['pass', 'pass', 'fail']); // Printing the output console.log(gfg) Output: Amit,1,pass,Akash,2,pass,Avijit,3,fail JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25969, "s": 25941, "text": "\n01 Sep, 2020" }, { "code": null, "e": 26184, "s": 25969, "text": "The _.zip() method is used to create an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second element of the given arrays, and so on." }, { "code": null, "e": 26192, "s": 26184, "text": "Syntax:" }, { "code": null, "e": 26208, "s": 26192, "text": "_.zip([arrays])" }, { "code": null, "e": 26299, "s": 26208, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 26353, "s": 26299, "text": "[arrays]: This parameter holds the arrays to process." }, { "code": null, "e": 26424, "s": 26353, "text": "Return Value: This method returns the new array of regrouped elements." }, { "code": null, "e": 26521, "s": 26424, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file." }, { "code": null, "e": 26532, "s": 26521, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.zip() method let gfg = _.zip(['a', 'b', 'c'], [1, 2, 3], [true, false, true]); // Printing the output console.log(gfg)", "e": 26767, "s": 26532, "text": null }, { "code": null, "e": 26775, "s": 26767, "text": "Output:" }, { "code": null, "e": 26803, "s": 26775, "text": "a,1,true,b,2,false,c,3,true" }, { "code": null, "e": 26816, "s": 26803, "text": "Example 2: " }, { "code": null, "e": 26827, "s": 26816, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.zip() // method let gfg = _.zip(['Amit', 'Akash', 'Avijit'], [1, 2, 3], ['pass', 'pass', 'fail']); // Printing the output console.log(gfg)", "e": 27083, "s": 26827, "text": null }, { "code": null, "e": 27091, "s": 27083, "text": "Output:" }, { "code": null, "e": 27130, "s": 27091, "text": "Amit,1,pass,Akash,2,pass,Avijit,3,fail" }, { "code": null, "e": 27148, "s": 27130, "text": "JavaScript-Lodash" }, { "code": null, "e": 27159, "s": 27148, "text": "JavaScript" }, { "code": null, "e": 27176, "s": 27159, "text": "Web Technologies" }, { "code": null, "e": 27274, "s": 27176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27314, "s": 27274, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27359, "s": 27314, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27420, "s": 27359, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27492, "s": 27420, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27544, "s": 27492, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27584, "s": 27544, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27617, "s": 27584, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27662, "s": 27617, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27705, "s": 27662, "text": "How to fetch data from an API in ReactJS ?" } ]
Program for volume of Pyramid - GeeksforGeeks
17 Mar, 2021 A pyramid is a 3-dimensional geometric shape formed by connecting all the corners of a polygon to a central apex. There are many types of pyramids. Most often, they are named after the type of base they have. Let’s look at some common types of pyramids below. Volume of a square pyramid [base of Pyramid is square] = (1/3) * (b^2) * h Volume of a triangular pyramid [base of Pyramid is triangle] = (1/6) * a * b * h Volume of a pentagonal pyramid [base of Pyramid is pentagonal] = (5/6) * a * b * h Volume of a hexagonal pyramid [base of Pyramid is hexagonal] = a * b * h Below is code for calculating volume of Pyramids : C++ Java Python3 C# PHP Javascript // CPP program to find the volume.#include <bits/stdc++.h>using namespace std; // Function to find the volume// of triangular pyramidfloat volumeTriangular(int a, int b, int h){ float vol = (0.1666) * a * b * h; return vol;} // Function to find the// volume of square pyramidfloat volumeSquare(int b, int h){ float vol = (0.33) * b * b * h; return vol;} // Function to find the volume// of pentagonal pyramidfloat volumePentagonal(int a, int b, int h){ float vol = (0.83) * a * b * h; return vol;} // Function to find the volume// of hexagonal pyramidfloat volumeHexagonal(int a, int b, int h){ float vol = a * b * h; return vol;} // Driver Codeint main(){ int b = 4, h = 9, a = 4; cout << "Volume of triangular" << " base pyramid is " << volumeTriangular(a, b, h) << endl; cout << "Volume of square " << " base pyramid is " << volumeSquare(b, h) << endl; cout << "Volume of pentagonal" << " base pyramid is " << volumePentagonal(a, b, h) << endl; cout << "Volume of Hexagonal" << " base pyramid is " << volumeHexagonal(a, b, h); return 0;} // Java Program for volume// of Pyramid.import java.util.*;import java.lang.*; class GfG{ // Function to find the volume of // triangular pyramid public static float volumeTriangular(int a, int b, int h) { float vol = (float)(0.1666) * a * b * h; return vol; } // Function to find the volume // of square pyramid public static float volumeSquare(int b, int h) { float vol = (float)(0.33) * b * b * h; return vol; } // Function to find the volume of // pentagonal pyramid public static float volumePentagonal(int a, int b, int h) { float vol = (float)(0.83) * a * b * h; return vol; } // Function to find the volume of hexagonal // pyramid public static float volumeHexagonal(int a, int b, int h) { float vol = (float)a * b * h; return vol; } // Driver Code public static void main(String argc[]) { int b = 4, h = 9, a = 4; System.out.println("Volume of triangular"+ " base pyramid is " + volumeTriangular(a, b, h)); System.out.println("Volume of square base" + " pyramid is " + volumeSquare(b, h)); System.out.println("Volume of pentagonal"+ " base pyramid is " + volumePentagonal(a, b, h)); System.out.println("Volume of Hexagonal"+ " base pyramid is " + volumeHexagonal(a, b, h)); }} // This code is contributed by Sagar Shukla # Python3 program to Volume of Pyramid # Function to calculate# Volume of Triangular Pyramiddef volumeTriangular(a, b, h): return (0.1666) * a * b * h # Function To calculate# Volume of Square Pyramiddef volumeSquare(b, h): return (0.33) * b * b * h # Function To calculate Volume# of Pentagonal Pyramiddef volumePentagonal(a, b, h): return (0.83) * a * b * h # Function To calculate Volume# of Hexagonal Pyramiddef volumeHexagonal(a, b, h): return a * b * h # Driver Codeb = float(4)h = float(9)a = float(4)print( "Volume of triangular base pyramid is ", volumeTriangular(a, b, h) )print( "Volume of square base pyramid is ", volumeSquare(b, h) )print( "Volume of pentagonal base pyramid is ", volumePentagonal(a,b, h) )print( "Volume of Hexagonal base pyramid is ", volumeHexagonal(a, b, h)) # This code is contributed by rishabh_jain // C# Program for volume of Pyramid.using System; class GFG{ // Function to find the volume of // triangular pyramid public static float volumeTriangular(int a, int b, int h) { float vol = (float)(0.1666) * a * b * h; return vol; } // Function to find the volume // of square pyramid public static float volumeSquare(int b, int h) { float vol = (float)(0.33) * b * b * h; return vol; } // Function to find the volume // of pentagonal pyramid public static float volumePentagonal(int a, int b, int h) { float vol = (float)(0.83) * a * b * h; return vol; } // Function to find the volume // of hexagonal pyramid public static float volumeHexagonal(int a, int b, int h) { float vol = (float)a * b * h; return vol; } // Driver Code public static void Main() { int b = 4, h = 9, a = 4; Console.WriteLine("Volume of triangular"+ " base pyramid is " + volumeTriangular(a, b, h)); Console.WriteLine("Volume of square "+ "base pyramid is " + volumeSquare(b, h)); Console.WriteLine("Volume of pentagonal"+ " base pyramid is " + volumePentagonal(a, b, h)); Console.WriteLine("Volume of Hexagonal"+ " base pyramid is " + volumeHexagonal(a, b, h)); }} // This code is contributed by vt_m <?php// PHP program to find the volume. // Function to find the volume// of triangular pyramidfunction volumeTriangular($a, $b, $h){ $vol = (0.1666) * $a * $b * $h; return $vol;} // Function to find the// volume of square pyramidfunction volumeSquare($b, $h){ $vol = (0.33) * $b * $b * $h; return $vol;} // Function to find the volume// of pentagonal pyramidfunction volumePentagonal($a, $b, $h){ $vol = (0.83) * $a * $b * $h; return $vol;} // Function to find the volume// of hexagonal pyramidfunction volumeHexagonal($a, $b, $h){ $vol = $a * $b * $h; return $vol;} // Driver Code$b = 4; $h = 9; $a = 4;echo ("Volume of triangular base pyramid is ");echo( volumeTriangular($a, $b, $h));echo("\n");echo ("Volume of square base pyramid is ");echo( volumeSquare($b, $h));echo("\n");echo ("Volume of pentagonal base pyramid is ");echo(volumePentagonal($a, $b, $h));echo("\n");echo("Volume of Hexagonal base pyramid is ");echo(volumeHexagonal($a, $b, $h)); // This code is contributed by vt_m?> <script>// javascript program to find the volume. // Function to find the volume// of triangular pyramidfunction volumeTriangular( a, b, h){ let vol = (0.1666) * a * b * h; return vol;} // Function to find the// volume of square pyramidfunction volumeSquare( b, h){ let vol = (0.33) * b * b * h; return vol;} // Function to find the volume// of pentagonal pyramidfunction volumePentagonal( a, b, h){ let vol = (0.83) * a * b * h; return vol;} // Function to find the volume// of hexagonal pyramidfunction volumeHexagonal( a, b, h){ let vol = a * b * h; return vol;} // Driver Code let b = 4, h = 9, a = 4; document.write( "Volume of triangular" + " base pyramid is " + volumeTriangular(a, b, h) +"<br/>"); document.write( "Volume of square " + " base pyramid is " + volumeSquare(b, h) +"<br/>"); document.write( "Volume of pentagonal" + " base pyramid is " + volumePentagonal(a, b, h) +"<br/>"); document.write("Volume of Hexagonal" + " base pyramid is " + volumeHexagonal(a, b, h)); // This code contributed by Rajput-Ji </script> Output : Volume of triangular base pyramid is 23.9904 Volume of square base pyramid is 47.52 Volume of pentagonal base pyramid is 119.52 Volume of Hexagonal base pyramid is 144 vt_m Rajput-Ji area-volume-programs Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Optimum location of point to minimize total distance Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26203, "s": 26175, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26465, "s": 26203, "text": "A pyramid is a 3-dimensional geometric shape formed by connecting all the corners of a polygon to a central apex. There are many types of pyramids. Most often, they are named after the type of base they have. Let’s look at some common types of pyramids below. " }, { "code": null, "e": 26779, "s": 26467, "text": "Volume of a square pyramid [base of Pyramid is square] = (1/3) * (b^2) * h Volume of a triangular pyramid [base of Pyramid is triangle] = (1/6) * a * b * h Volume of a pentagonal pyramid [base of Pyramid is pentagonal] = (5/6) * a * b * h Volume of a hexagonal pyramid [base of Pyramid is hexagonal] = a * b * h" }, { "code": null, "e": 26832, "s": 26779, "text": "Below is code for calculating volume of Pyramids : " }, { "code": null, "e": 26836, "s": 26832, "text": "C++" }, { "code": null, "e": 26841, "s": 26836, "text": "Java" }, { "code": null, "e": 26849, "s": 26841, "text": "Python3" }, { "code": null, "e": 26852, "s": 26849, "text": "C#" }, { "code": null, "e": 26856, "s": 26852, "text": "PHP" }, { "code": null, "e": 26867, "s": 26856, "text": "Javascript" }, { "code": "// CPP program to find the volume.#include <bits/stdc++.h>using namespace std; // Function to find the volume// of triangular pyramidfloat volumeTriangular(int a, int b, int h){ float vol = (0.1666) * a * b * h; return vol;} // Function to find the// volume of square pyramidfloat volumeSquare(int b, int h){ float vol = (0.33) * b * b * h; return vol;} // Function to find the volume// of pentagonal pyramidfloat volumePentagonal(int a, int b, int h){ float vol = (0.83) * a * b * h; return vol;} // Function to find the volume// of hexagonal pyramidfloat volumeHexagonal(int a, int b, int h){ float vol = a * b * h; return vol;} // Driver Codeint main(){ int b = 4, h = 9, a = 4; cout << \"Volume of triangular\" << \" base pyramid is \" << volumeTriangular(a, b, h) << endl; cout << \"Volume of square \" << \" base pyramid is \" << volumeSquare(b, h) << endl; cout << \"Volume of pentagonal\" << \" base pyramid is \" << volumePentagonal(a, b, h) << endl; cout << \"Volume of Hexagonal\" << \" base pyramid is \" << volumeHexagonal(a, b, h); return 0;}", "e": 28213, "s": 26867, "text": null }, { "code": "// Java Program for volume// of Pyramid.import java.util.*;import java.lang.*; class GfG{ // Function to find the volume of // triangular pyramid public static float volumeTriangular(int a, int b, int h) { float vol = (float)(0.1666) * a * b * h; return vol; } // Function to find the volume // of square pyramid public static float volumeSquare(int b, int h) { float vol = (float)(0.33) * b * b * h; return vol; } // Function to find the volume of // pentagonal pyramid public static float volumePentagonal(int a, int b, int h) { float vol = (float)(0.83) * a * b * h; return vol; } // Function to find the volume of hexagonal // pyramid public static float volumeHexagonal(int a, int b, int h) { float vol = (float)a * b * h; return vol; } // Driver Code public static void main(String argc[]) { int b = 4, h = 9, a = 4; System.out.println(\"Volume of triangular\"+ \" base pyramid is \" + volumeTriangular(a, b, h)); System.out.println(\"Volume of square base\" + \" pyramid is \" + volumeSquare(b, h)); System.out.println(\"Volume of pentagonal\"+ \" base pyramid is \" + volumePentagonal(a, b, h)); System.out.println(\"Volume of Hexagonal\"+ \" base pyramid is \" + volumeHexagonal(a, b, h)); }} // This code is contributed by Sagar Shukla", "e": 30115, "s": 28213, "text": null }, { "code": "# Python3 program to Volume of Pyramid # Function to calculate# Volume of Triangular Pyramiddef volumeTriangular(a, b, h): return (0.1666) * a * b * h # Function To calculate# Volume of Square Pyramiddef volumeSquare(b, h): return (0.33) * b * b * h # Function To calculate Volume# of Pentagonal Pyramiddef volumePentagonal(a, b, h): return (0.83) * a * b * h # Function To calculate Volume# of Hexagonal Pyramiddef volumeHexagonal(a, b, h): return a * b * h # Driver Codeb = float(4)h = float(9)a = float(4)print( \"Volume of triangular base pyramid is \", volumeTriangular(a, b, h) )print( \"Volume of square base pyramid is \", volumeSquare(b, h) )print( \"Volume of pentagonal base pyramid is \", volumePentagonal(a,b, h) )print( \"Volume of Hexagonal base pyramid is \", volumeHexagonal(a, b, h)) # This code is contributed by rishabh_jain", "e": 31041, "s": 30115, "text": null }, { "code": "// C# Program for volume of Pyramid.using System; class GFG{ // Function to find the volume of // triangular pyramid public static float volumeTriangular(int a, int b, int h) { float vol = (float)(0.1666) * a * b * h; return vol; } // Function to find the volume // of square pyramid public static float volumeSquare(int b, int h) { float vol = (float)(0.33) * b * b * h; return vol; } // Function to find the volume // of pentagonal pyramid public static float volumePentagonal(int a, int b, int h) { float vol = (float)(0.83) * a * b * h; return vol; } // Function to find the volume // of hexagonal pyramid public static float volumeHexagonal(int a, int b, int h) { float vol = (float)a * b * h; return vol; } // Driver Code public static void Main() { int b = 4, h = 9, a = 4; Console.WriteLine(\"Volume of triangular\"+ \" base pyramid is \" + volumeTriangular(a, b, h)); Console.WriteLine(\"Volume of square \"+ \"base pyramid is \" + volumeSquare(b, h)); Console.WriteLine(\"Volume of pentagonal\"+ \" base pyramid is \" + volumePentagonal(a, b, h)); Console.WriteLine(\"Volume of Hexagonal\"+ \" base pyramid is \" + volumeHexagonal(a, b, h)); }} // This code is contributed by vt_m", "e": 32863, "s": 31041, "text": null }, { "code": "<?php// PHP program to find the volume. // Function to find the volume// of triangular pyramidfunction volumeTriangular($a, $b, $h){ $vol = (0.1666) * $a * $b * $h; return $vol;} // Function to find the// volume of square pyramidfunction volumeSquare($b, $h){ $vol = (0.33) * $b * $b * $h; return $vol;} // Function to find the volume// of pentagonal pyramidfunction volumePentagonal($a, $b, $h){ $vol = (0.83) * $a * $b * $h; return $vol;} // Function to find the volume// of hexagonal pyramidfunction volumeHexagonal($a, $b, $h){ $vol = $a * $b * $h; return $vol;} // Driver Code$b = 4; $h = 9; $a = 4;echo (\"Volume of triangular base pyramid is \");echo( volumeTriangular($a, $b, $h));echo(\"\\n\");echo (\"Volume of square base pyramid is \");echo( volumeSquare($b, $h));echo(\"\\n\");echo (\"Volume of pentagonal base pyramid is \");echo(volumePentagonal($a, $b, $h));echo(\"\\n\");echo(\"Volume of Hexagonal base pyramid is \");echo(volumeHexagonal($a, $b, $h)); // This code is contributed by vt_m?>", "e": 33878, "s": 32863, "text": null }, { "code": "<script>// javascript program to find the volume. // Function to find the volume// of triangular pyramidfunction volumeTriangular( a, b, h){ let vol = (0.1666) * a * b * h; return vol;} // Function to find the// volume of square pyramidfunction volumeSquare( b, h){ let vol = (0.33) * b * b * h; return vol;} // Function to find the volume// of pentagonal pyramidfunction volumePentagonal( a, b, h){ let vol = (0.83) * a * b * h; return vol;} // Function to find the volume// of hexagonal pyramidfunction volumeHexagonal( a, b, h){ let vol = a * b * h; return vol;} // Driver Code let b = 4, h = 9, a = 4; document.write( \"Volume of triangular\" + \" base pyramid is \" + volumeTriangular(a, b, h) +\"<br/>\"); document.write( \"Volume of square \" + \" base pyramid is \" + volumeSquare(b, h) +\"<br/>\"); document.write( \"Volume of pentagonal\" + \" base pyramid is \" + volumePentagonal(a, b, h) +\"<br/>\"); document.write(\"Volume of Hexagonal\" + \" base pyramid is \" + volumeHexagonal(a, b, h)); // This code contributed by Rajput-Ji </script>", "e": 35135, "s": 33878, "text": null }, { "code": null, "e": 35146, "s": 35135, "text": "Output : " }, { "code": null, "e": 35314, "s": 35146, "text": "Volume of triangular base pyramid is 23.9904\nVolume of square base pyramid is 47.52\nVolume of pentagonal base pyramid is 119.52\nVolume of Hexagonal base pyramid is 144" }, { "code": null, "e": 35321, "s": 35316, "text": "vt_m" }, { "code": null, "e": 35331, "s": 35321, "text": "Rajput-Ji" }, { "code": null, "e": 35352, "s": 35331, "text": "area-volume-programs" }, { "code": null, "e": 35362, "s": 35352, "text": "Geometric" }, { "code": null, "e": 35381, "s": 35362, "text": "School Programming" }, { "code": null, "e": 35391, "s": 35381, "text": "Geometric" }, { "code": null, "e": 35489, "s": 35391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35538, "s": 35489, "text": "Program for distance between two points on earth" }, { "code": null, "e": 35591, "s": 35538, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 35642, "s": 35591, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 35676, "s": 35642, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 35729, "s": 35676, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 35747, "s": 35729, "text": "Python Dictionary" }, { "code": null, "e": 35763, "s": 35747, "text": "Arrays in C/C++" }, { "code": null, "e": 35782, "s": 35763, "text": "Inheritance in C++" }, { "code": null, "e": 35807, "s": 35782, "text": "Reverse a string in Java" } ]
How to align flexbox columns left and right using CSS ? - GeeksforGeeks
28 Jan, 2020 The flex columns can be aligned left or right by using the align-content property in the flex container class. The align-content property changes the behavior of the flex-wrap property. It aligns flex lines. It is used to specify the alignment between the lines inside a flexible container. For aligning columns to the left, the align-content property will set to ‘flex-start’. For aligning columns to the right, the align-content property will set to ‘flex-end’. For aligning columns to the extreme ends, the align-content property will set to ‘space-between’. Example 1: This example display the flex box into the columns. <!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html> Output: Example 2: This example align the flex box columns into the left. <!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; align-content: flex-start; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html> Output: Example 3: This example align the flex box columns into right. <!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; align-content: flex-end; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html> Output: Example 3: This example align the flex box into both end points. <!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; align-content: space-between; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html> Output: CSS-Misc Picked Technical Scripter 2019 CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n28 Jan, 2020" }, { "code": null, "e": 26912, "s": 26621, "text": "The flex columns can be aligned left or right by using the align-content property in the flex container class. The align-content property changes the behavior of the flex-wrap property. It aligns flex lines. It is used to specify the alignment between the lines inside a flexible container." }, { "code": null, "e": 26999, "s": 26912, "text": "For aligning columns to the left, the align-content property will set to ‘flex-start’." }, { "code": null, "e": 27085, "s": 26999, "text": "For aligning columns to the right, the align-content property will set to ‘flex-end’." }, { "code": null, "e": 27183, "s": 27085, "text": "For aligning columns to the extreme ends, the align-content property will set to ‘space-between’." }, { "code": null, "e": 27246, "s": 27183, "text": "Example 1: This example display the flex box into the columns." }, { "code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class=\"flex-container\"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html>", "e": 27915, "s": 27246, "text": null }, { "code": null, "e": 27923, "s": 27915, "text": "Output:" }, { "code": null, "e": 27989, "s": 27923, "text": "Example 2: This example align the flex box columns into the left." }, { "code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; align-content: flex-start; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class=\"flex-container\"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html>", "e": 28696, "s": 27989, "text": null }, { "code": null, "e": 28704, "s": 28696, "text": "Output:" }, { "code": null, "e": 28767, "s": 28704, "text": "Example 3: This example align the flex box columns into right." }, { "code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; align-content: flex-end; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class=\"flex-container\"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html>", "e": 29472, "s": 28767, "text": null }, { "code": null, "e": 29480, "s": 29472, "text": "Output:" }, { "code": null, "e": 29545, "s": 29480, "text": "Example 3: This example align the flex box into both end points." }, { "code": "<!DOCTYPE html><html> <head> <style> .flex-container { display: flex; height:400px; flex-flow: column wrap; background-color: green; align-content: space-between; } .flex-container > div { background-color: #fff; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } </style></head> <body> <div class=\"flex-container\"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div></body> </html>", "e": 30255, "s": 29545, "text": null }, { "code": null, "e": 30263, "s": 30255, "text": "Output:" }, { "code": null, "e": 30272, "s": 30263, "text": "CSS-Misc" }, { "code": null, "e": 30279, "s": 30272, "text": "Picked" }, { "code": null, "e": 30303, "s": 30279, "text": "Technical Scripter 2019" }, { "code": null, "e": 30307, "s": 30303, "text": "CSS" }, { "code": null, "e": 30326, "s": 30307, "text": "Technical Scripter" }, { "code": null, "e": 30343, "s": 30326, "text": "Web Technologies" }, { "code": null, "e": 30441, "s": 30343, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30478, "s": 30441, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30517, "s": 30478, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30546, "s": 30517, "text": "Form validation using jQuery" }, { "code": null, "e": 30588, "s": 30546, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 30623, "s": 30588, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 30663, "s": 30623, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30696, "s": 30663, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30741, "s": 30696, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30784, "s": 30741, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum Length Chain of Pairs | DP-20 - GeeksforGeeks
29 Mar, 2022 You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs. Source: Amazon Interview | Set 2For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }, then the longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}} This problem is a variation of standard Longest Increasing Subsequence problem. Following is a simple two step process. 1) Sort given pairs in increasing order of first (or smaller) element. Why do not need sorting? Consider the example {{6, 8}, {3, 4}} to understand the need of sorting. If we proceed to second step without sorting, we get output as 1. But the correct output is 2. 2) Now run a modified LIS process where we compare the second element of already finalized LIS with the first element of new LIS being constructed. The following code is a slight modification of method 2 of this post. C++ C Java Python3 C# Javascript // CPP program for above approach#include <bits/stdc++.h>using namespace std; // Structure for a Pairclass Pair{ public: int a; int b;}; // This function assumes that arr[]// is sorted in increasing order// according the first// (or smaller) values in Pairs.int maxChainLength( Pair arr[], int n){ int i, j, max = 0; int *mcl = new int[sizeof( int ) * n ]; /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with Pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; /* Free memory to avoid memory leak */ return max;} /* Driver code */int main(){ Pair arr[] = { {5, 24}, {15, 25}, {27, 40}, {50, 60} }; int n = sizeof(arr)/sizeof(arr[0]); cout << "Length of maximum size chain is " << maxChainLength( arr, n ); return 0;} // This code is contributed by rathbhupendra #include<stdio.h>#include<stdlib.h> // Structure for a pairstruct pair{ int a; int b;}; // This function assumes that// arr[] is sorted in increasing order// according the first// (or smaller) values in pairs.int maxChainLength( struct pair arr[], int n){ int i, j, max = 0; int *mcl = (int*) malloc ( sizeof( int ) * n ); /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; /* Free memory to avoid memory leak */ free( mcl ); return max;} /* Driver program to test above function */int main(){ struct pair arr[] = { {5, 24}, {15, 25}, {27, 40}, {50, 60} }; int n = sizeof(arr)/sizeof(arr[0]); printf("Length of maximum size chain is %d\n", maxChainLength( arr, n )); return 0;} // Java program for above approachclass Pair{ int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // This function assumes that // arr[] is sorted in increasing order // according the first (or smaller) // values in pairs. static int maxChainLength(Pair arr[], int n) { int i, j, max = 0; int mcl[] = new int[n]; /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; return max; } /* Driver program to test above function */ public static void main(String[] args) { Pair arr[] = new Pair[] { new Pair(5,24), new Pair(15, 25), new Pair (27, 40), new Pair(50, 60)}; System.out.println("Length of maximum size chain is " + maxChainLength(arr, arr.length)); }} # Python program for above approachclass Pair(object): def __init__(self, a, b): self.a = a self.b = b # This function assumes# that arr[] is sorted in increasing# order according the# first (or smaller) values in pairs.def maxChainLength(arr, n): max = 0 # Initialize MCL(max chain # length) values for all indices mcl = [1 for i in range(n)] # Compute optimized chain # length values in bottom up manner for i in range(1, n): for j in range(0, i): if (arr[i].a > arr[j].b and mcl[i] < mcl[j] + 1): mcl[i] = mcl[j] + 1 # mcl[i] now stores the maximum # chain length ending with pair i # Pick maximum of all MCL values for i in range(n): if (max < mcl[i]): max = mcl[i] return max # Driver program to test above functionarr = [Pair(5, 24), Pair(15, 25), Pair(27, 40), Pair(50, 60)] print('Length of maximum size chain is', maxChainLength(arr, len(arr))) # This code is contributed by Soumen Ghosh // Dynamic C# program to find// Maximum Length Chain of Pairsusing System; class Pair{ int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // This function assumes that arr[] // is sorted in increasing order // according the first (or smaller) // values in pairs. static int maxChainLength(Pair []arr, int n) { int i, j, max = 0; int []mcl = new int[n]; // Initialize MCL (max chain length) // values for all indexes for(i = 0; i < n; i++ ) mcl[i] = 1; // Compute optimized chain length // values in bottom up manner for(i = 1; i < n; i++) for (j = 0; j < i; j++) if(arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) // mcl[i] now stores the maximum // chain length ending with pair i mcl[i] = mcl[j] + 1; // Pick maximum of all MCL values for ( i = 0; i < n; i++ ) if (max < mcl[i] ) max = mcl[i]; return max; } // Driver Code public static void Main() { Pair []arr = new Pair[] {new Pair(5,24), new Pair(15, 25), new Pair (27, 40), new Pair(50, 60)}; Console.Write("Length of maximum size chain is " + maxChainLength(arr, arr.Length)); }} // This code is contributed by nitin mittal. <script> // Javascript program for above approach class Pair{ constructor(a,b) { this.a=a; this.b=b; }} // This function assumes that // arr[] is sorted in increasing order // according the first (or smaller) // values in pairs.function maxChainLength(arr,n){ let i, j, max = 0; let mcl = new Array(n); /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; return max;} /* Driver program to test above function */let arr=[ new Pair(5,24), new Pair(15, 25), new Pair (27, 40), new Pair(50, 60)]; document.write("Length of maximum size chain is " + maxChainLength(arr, arr.length)); // This code is contributed by avanitrachhadiya2155</script> Length of maximum size chain is 3 Time Complexity: O(n^2) where n is the number of pairs. The given problem is also a variation of Activity Selection problem and can be solved in (nLogn) time. To solve it as a activity selection problem, consider the first element of a pair as start time in activity selection problem, and the second element of pair as end time. Another approach( Top-down Dynamic programming):Now we will explore the way of solving this problem using the top-down approach of dynamic programming (recursion + memorization). Since we are going to solve the above problem using top down method our first step is to figure out the recurrence relation. The best and the easiest way to get the recurrence relation is to think about the choices that we have at each state or position. If we look at the above problem carefully, we find two choices to be present at each position/index. The two choices are: Choice 1: To select the element at the particular position and explore the rest, (or) Choice 2: To leave the element at that position and explore the rest. Please note here that we can select the element at a particular position only if first element at that position is greater than the second element that we have previously chosen (this is a constraint given in the question). Hence, in the recursion we maintain a variable which would tell us the previous element that we picked. Also, we have to maximize our answer. Hence, we have to find out the maximum resulting option by exploring the above two choices at each position. The resulting recurrence relation would be: T(n) = max( maxlenchain(p,n,p[pos].second,0)+1,maxlenchain(p,n,prev_choosen_ele,pos+1) ) Please note the function signature is as follows: int cal(struct val p[],int n,int prev_choosen_ele,int pos); Nevertheless, we should not forget our base condition in recursion. If not, our code would enjoy a vacation by just executing forever and not stopping at all. So, our base condition for this problem is quite simple. If we reach the end of our exploration, we just return 0, as no more chains would be possible. if(pos >= n) return 0; To avoid the repetitive task, we do the dynamic programming magic (It is a magic to reduce your time complexity). We store the position and previous element in a map. If we ever happened to come to the same position with the same previous element we do not recompute again. We just return the answer from the map.Below is the implementation of the above approach: C++14 Java Python3 Javascript // CPP program for above approach#include <bits/stdc++.h>using namespace std; // Structure valstruct val{ int first; int second;}; map<pair<int, int>, int> m; // Memoisation functionint findMaxChainLen(struct val p[], int n, int prev, int pos){ // Check if pair { pos, prev } exists // in m if (m.find({ pos, prev }) != m.end()) { return m[{ pos, prev }]; } // Check if pos is >=n if (pos >= n) return 0; // Check if p[pos].first is // less than prev if (p[pos].first <= prev) { return findMaxChainLen(p, n, prev, pos + 1); } else { int ans = max(findMaxChainLen(p, n, p[pos].second, 0) + 1, findMaxChainLen(p, n, prev, pos + 1)); m[{ pos, prev }] = ans; return ans; }} // Function to calculate maximum// chain lengthint maxChainLen(struct val p[], int n){ m.clear(); // Call memoisation function int ans = findMaxChainLen(p, n, 0, 0); return ans;} // Driver Codeint main(){ int n = 5; val p[n]; p[0].first = 5; p[0].second = 24; p[1].first = 39; p[1].second = 60; p[2].first = 15; p[2].second = 28; p[3].first = 27; p[3].second = 40; p[4].first = 50; p[4].second = 90; // Function Call cout << maxChainLen(p, n) << endl; return 0;} // Java program for above approachimport java.util.*; class GFG{ // Structure valstatic class val{ int first; int second;}; static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; pair other = (pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } static Map<pair, Integer> m = new HashMap<>(); // Memoisation functionstatic int findMaxChainLen(val p[], int n, int prev, int pos){ // Check if pair { pos, prev } exists // in m if (m.containsKey(new pair(pos, prev))) { return m.get(new pair(pos, prev)); } // Check if pos is >=n if (pos >= n) return 0; // Check if p[pos].first is // less than prev if (p[pos].first <= prev) { return findMaxChainLen(p, n, prev, pos + 1); } else { int ans = Math.max(findMaxChainLen( p, n, p[pos].second, 0) + 1, findMaxChainLen( p, n, prev, pos + 1)); m.put(new pair(pos, prev), ans); return ans; }} // Function to calculate maximum// chain lengthstatic int maxChainLen(val p[], int n){ m.clear(); // Call memoisation function int ans = findMaxChainLen(p, n, 0, 0); return ans;} // Driver Codepublic static void main(String[] args){ int n = 5; val []p = new val[n]; for(int i = 0; i < n; i++) p[i] = new val(); p[0].first = 5; p[0].second = 24; p[1].first = 39; p[1].second = 60; p[2].first = 15; p[2].second = 28; p[3].first = 27; p[3].second = 40; p[4].first = 50; p[4].second = 90; // Function Call System.out.print(maxChainLen(p, n) + "\n");}} // This code is contributed by 29AjayKumar # Python program for above approach # Structure valclass val: def __init__(self,first,second): self.first = first self.second = second # Memoisation functiondef findMaxChainLen(p, n, prev, pos): global m # Check if pair { pos, prev } exists # in m if (val(pos, prev) in m): return m[val(pos, prev)] # Check if pos is >=n if (pos >= n): return 0 # Check if p[pos].first is # less than prev if (p[pos].first <= prev): return findMaxChainLen(p, n, prev, pos + 1) else: ans = max(findMaxChainLen(p, n, p[pos].second, 0) + 1, findMaxChainLen(p, n, prev, pos + 1)) m[val(pos, prev)] = ans return ans # Function to calculate maximum# chain lengthdef maxChainLen(p,n): global m m.clear() # Call memoisation function ans = findMaxChainLen(p, n, 0, 0) return ans # Driver Coden = 5p = [0]*np[0] = val(5,24) p[1] = val(39,60) p[2] = val(15,28) p[3] = val(27,40) p[4] = val(50,90) m = {} # Function Callprint(maxChainLen(p, n)) # This code is contributed by shinjanpatra <script> // JavaScript program for above approach // Structure valclass val{ constructor(first,second){ this.first = first; this.second = second; }}; let m = new Map(); // Memoisation functionfunction findMaxChainLen(p,n,prev,pos){ // Check if pair { pos, prev } exists // in m if (m.has(new val(pos, prev))) return m.get(new val(pos, prev)); // Check if pos is >=n if (pos >= n) return 0; // Check if p[pos].first is // less than prev if (p[pos].first <= prev) { return findMaxChainLen(p, n, prev, pos + 1); } else { let ans = Math.max(findMaxChainLen(p, n, p[pos].second, 0) + 1, findMaxChainLen(p, n, prev, pos + 1)); m.set(new val(pos, prev),ans); return ans; }} // Function to calculate maximum// chain lengthfunction maxChainLen(p,n){ m.clear(); // Call memoisation function let ans = findMaxChainLen(p, n, 0, 0); return ans;} // Driver Codelet n = 5;let p = new Array(n);p[0] = new val(5,24); p[1] = new val(39,60); p[2] = new val(15,28); p[3] = new val(27,40); p[4] = new val(50,90); // Function Calldocument.write(maxChainLen(p, n),"</br>"); // code is contributed by shinjanpatra </script> 3 https://www.youtube.com/watch?v=v -HIXptqM3Q Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal rathbhupendra sunilkannur98 surajv avanitrachhadiya2155 29AjayKumar shinjanpatra Amazon Dynamic Programming Greedy Amazon Dynamic Programming Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Program for array rotation Write a program to print all permutations of a given string
[ { "code": null, "e": 26641, "s": 26613, "text": "\n29 Mar, 2022" }, { "code": null, "e": 27145, "s": 26641, "text": "You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs. Source: Amazon Interview | Set 2For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }, then the longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}}" }, { "code": null, "e": 27748, "s": 27145, "text": "This problem is a variation of standard Longest Increasing Subsequence problem. Following is a simple two step process. 1) Sort given pairs in increasing order of first (or smaller) element. Why do not need sorting? Consider the example {{6, 8}, {3, 4}} to understand the need of sorting. If we proceed to second step without sorting, we get output as 1. But the correct output is 2. 2) Now run a modified LIS process where we compare the second element of already finalized LIS with the first element of new LIS being constructed. The following code is a slight modification of method 2 of this post. " }, { "code": null, "e": 27752, "s": 27748, "text": "C++" }, { "code": null, "e": 27754, "s": 27752, "text": "C" }, { "code": null, "e": 27759, "s": 27754, "text": "Java" }, { "code": null, "e": 27767, "s": 27759, "text": "Python3" }, { "code": null, "e": 27770, "s": 27767, "text": "C#" }, { "code": null, "e": 27781, "s": 27770, "text": "Javascript" }, { "code": "// CPP program for above approach#include <bits/stdc++.h>using namespace std; // Structure for a Pairclass Pair{ public: int a; int b;}; // This function assumes that arr[]// is sorted in increasing order// according the first// (or smaller) values in Pairs.int maxChainLength( Pair arr[], int n){ int i, j, max = 0; int *mcl = new int[sizeof( int ) * n ]; /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with Pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; /* Free memory to avoid memory leak */ return max;} /* Driver code */int main(){ Pair arr[] = { {5, 24}, {15, 25}, {27, 40}, {50, 60} }; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Length of maximum size chain is \" << maxChainLength( arr, n ); return 0;} // This code is contributed by rathbhupendra", "e": 29106, "s": 27781, "text": null }, { "code": "#include<stdio.h>#include<stdlib.h> // Structure for a pairstruct pair{ int a; int b;}; // This function assumes that// arr[] is sorted in increasing order// according the first// (or smaller) values in pairs.int maxChainLength( struct pair arr[], int n){ int i, j, max = 0; int *mcl = (int*) malloc ( sizeof( int ) * n ); /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; /* Free memory to avoid memory leak */ free( mcl ); return max;} /* Driver program to test above function */int main(){ struct pair arr[] = { {5, 24}, {15, 25}, {27, 40}, {50, 60} }; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Length of maximum size chain is %d\\n\", maxChainLength( arr, n )); return 0;}", "e": 30332, "s": 29106, "text": null }, { "code": "// Java program for above approachclass Pair{ int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // This function assumes that // arr[] is sorted in increasing order // according the first (or smaller) // values in pairs. static int maxChainLength(Pair arr[], int n) { int i, j, max = 0; int mcl[] = new int[n]; /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; return max; } /* Driver program to test above function */ public static void main(String[] args) { Pair arr[] = new Pair[] { new Pair(5,24), new Pair(15, 25), new Pair (27, 40), new Pair(50, 60)}; System.out.println(\"Length of maximum size chain is \" + maxChainLength(arr, arr.length)); }}", "e": 31796, "s": 30332, "text": null }, { "code": "# Python program for above approachclass Pair(object): def __init__(self, a, b): self.a = a self.b = b # This function assumes# that arr[] is sorted in increasing# order according the# first (or smaller) values in pairs.def maxChainLength(arr, n): max = 0 # Initialize MCL(max chain # length) values for all indices mcl = [1 for i in range(n)] # Compute optimized chain # length values in bottom up manner for i in range(1, n): for j in range(0, i): if (arr[i].a > arr[j].b and mcl[i] < mcl[j] + 1): mcl[i] = mcl[j] + 1 # mcl[i] now stores the maximum # chain length ending with pair i # Pick maximum of all MCL values for i in range(n): if (max < mcl[i]): max = mcl[i] return max # Driver program to test above functionarr = [Pair(5, 24), Pair(15, 25), Pair(27, 40), Pair(50, 60)] print('Length of maximum size chain is', maxChainLength(arr, len(arr))) # This code is contributed by Soumen Ghosh", "e": 32835, "s": 31796, "text": null }, { "code": "// Dynamic C# program to find// Maximum Length Chain of Pairsusing System; class Pair{ int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // This function assumes that arr[] // is sorted in increasing order // according the first (or smaller) // values in pairs. static int maxChainLength(Pair []arr, int n) { int i, j, max = 0; int []mcl = new int[n]; // Initialize MCL (max chain length) // values for all indexes for(i = 0; i < n; i++ ) mcl[i] = 1; // Compute optimized chain length // values in bottom up manner for(i = 1; i < n; i++) for (j = 0; j < i; j++) if(arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) // mcl[i] now stores the maximum // chain length ending with pair i mcl[i] = mcl[j] + 1; // Pick maximum of all MCL values for ( i = 0; i < n; i++ ) if (max < mcl[i] ) max = mcl[i]; return max; } // Driver Code public static void Main() { Pair []arr = new Pair[] {new Pair(5,24), new Pair(15, 25), new Pair (27, 40), new Pair(50, 60)}; Console.Write(\"Length of maximum size chain is \" + maxChainLength(arr, arr.Length)); }} // This code is contributed by nitin mittal.", "e": 34312, "s": 32835, "text": null }, { "code": "<script> // Javascript program for above approach class Pair{ constructor(a,b) { this.a=a; this.b=b; }} // This function assumes that // arr[] is sorted in increasing order // according the first (or smaller) // values in pairs.function maxChainLength(arr,n){ let i, j, max = 0; let mcl = new Array(n); /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0; i < n; i++ ) mcl[i] = 1; /* Compute optimized chain length values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1) mcl[i] = mcl[j] + 1; // mcl[i] now stores the maximum // chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; return max;} /* Driver program to test above function */let arr=[ new Pair(5,24), new Pair(15, 25), new Pair (27, 40), new Pair(50, 60)]; document.write(\"Length of maximum size chain is \" + maxChainLength(arr, arr.length)); // This code is contributed by avanitrachhadiya2155</script>", "e": 35654, "s": 34312, "text": null }, { "code": null, "e": 35688, "s": 35654, "text": "Length of maximum size chain is 3" }, { "code": null, "e": 35745, "s": 35688, "text": "Time Complexity: O(n^2) where n is the number of pairs. " }, { "code": null, "e": 36020, "s": 35745, "text": "The given problem is also a variation of Activity Selection problem and can be solved in (nLogn) time. To solve it as a activity selection problem, consider the first element of a pair as start time in activity selection problem, and the second element of pair as end time. " }, { "code": null, "e": 37252, "s": 36020, "text": "Another approach( Top-down Dynamic programming):Now we will explore the way of solving this problem using the top-down approach of dynamic programming (recursion + memorization). Since we are going to solve the above problem using top down method our first step is to figure out the recurrence relation. The best and the easiest way to get the recurrence relation is to think about the choices that we have at each state or position. If we look at the above problem carefully, we find two choices to be present at each position/index. The two choices are: Choice 1: To select the element at the particular position and explore the rest, (or) Choice 2: To leave the element at that position and explore the rest. Please note here that we can select the element at a particular position only if first element at that position is greater than the second element that we have previously chosen (this is a constraint given in the question). Hence, in the recursion we maintain a variable which would tell us the previous element that we picked. Also, we have to maximize our answer. Hence, we have to find out the maximum resulting option by exploring the above two choices at each position. The resulting recurrence relation would be: " }, { "code": null, "e": 37453, "s": 37252, "text": " T(n) = max( maxlenchain(p,n,p[pos].second,0)+1,maxlenchain(p,n,prev_choosen_ele,pos+1) ) Please note the function signature is as follows: int cal(struct val p[],int n,int prev_choosen_ele,int pos);" }, { "code": null, "e": 37764, "s": 37453, "text": "Nevertheless, we should not forget our base condition in recursion. If not, our code would enjoy a vacation by just executing forever and not stopping at all. So, our base condition for this problem is quite simple. If we reach the end of our exploration, we just return 0, as no more chains would be possible." }, { "code": null, "e": 37789, "s": 37764, "text": " if(pos >= n) return 0;" }, { "code": null, "e": 38153, "s": 37789, "text": "To avoid the repetitive task, we do the dynamic programming magic (It is a magic to reduce your time complexity). We store the position and previous element in a map. If we ever happened to come to the same position with the same previous element we do not recompute again. We just return the answer from the map.Below is the implementation of the above approach:" }, { "code": null, "e": 38159, "s": 38153, "text": "C++14" }, { "code": null, "e": 38164, "s": 38159, "text": "Java" }, { "code": null, "e": 38172, "s": 38164, "text": "Python3" }, { "code": null, "e": 38183, "s": 38172, "text": "Javascript" }, { "code": "// CPP program for above approach#include <bits/stdc++.h>using namespace std; // Structure valstruct val{ int first; int second;}; map<pair<int, int>, int> m; // Memoisation functionint findMaxChainLen(struct val p[], int n, int prev, int pos){ // Check if pair { pos, prev } exists // in m if (m.find({ pos, prev }) != m.end()) { return m[{ pos, prev }]; } // Check if pos is >=n if (pos >= n) return 0; // Check if p[pos].first is // less than prev if (p[pos].first <= prev) { return findMaxChainLen(p, n, prev, pos + 1); } else { int ans = max(findMaxChainLen(p, n, p[pos].second, 0) + 1, findMaxChainLen(p, n, prev, pos + 1)); m[{ pos, prev }] = ans; return ans; }} // Function to calculate maximum// chain lengthint maxChainLen(struct val p[], int n){ m.clear(); // Call memoisation function int ans = findMaxChainLen(p, n, 0, 0); return ans;} // Driver Codeint main(){ int n = 5; val p[n]; p[0].first = 5; p[0].second = 24; p[1].first = 39; p[1].second = 60; p[2].first = 15; p[2].second = 28; p[3].first = 27; p[3].second = 40; p[4].first = 50; p[4].second = 90; // Function Call cout << maxChainLen(p, n) << endl; return 0;}", "e": 39625, "s": 38183, "text": null }, { "code": "// Java program for above approachimport java.util.*; class GFG{ // Structure valstatic class val{ int first; int second;}; static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; pair other = (pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } static Map<pair, Integer> m = new HashMap<>(); // Memoisation functionstatic int findMaxChainLen(val p[], int n, int prev, int pos){ // Check if pair { pos, prev } exists // in m if (m.containsKey(new pair(pos, prev))) { return m.get(new pair(pos, prev)); } // Check if pos is >=n if (pos >= n) return 0; // Check if p[pos].first is // less than prev if (p[pos].first <= prev) { return findMaxChainLen(p, n, prev, pos + 1); } else { int ans = Math.max(findMaxChainLen( p, n, p[pos].second, 0) + 1, findMaxChainLen( p, n, prev, pos + 1)); m.put(new pair(pos, prev), ans); return ans; }} // Function to calculate maximum// chain lengthstatic int maxChainLen(val p[], int n){ m.clear(); // Call memoisation function int ans = findMaxChainLen(p, n, 0, 0); return ans;} // Driver Codepublic static void main(String[] args){ int n = 5; val []p = new val[n]; for(int i = 0; i < n; i++) p[i] = new val(); p[0].first = 5; p[0].second = 24; p[1].first = 39; p[1].second = 60; p[2].first = 15; p[2].second = 28; p[3].first = 27; p[3].second = 40; p[4].first = 50; p[4].second = 90; // Function Call System.out.print(maxChainLen(p, n) + \"\\n\");}} // This code is contributed by 29AjayKumar", "e": 42078, "s": 39625, "text": null }, { "code": "# Python program for above approach # Structure valclass val: def __init__(self,first,second): self.first = first self.second = second # Memoisation functiondef findMaxChainLen(p, n, prev, pos): global m # Check if pair { pos, prev } exists # in m if (val(pos, prev) in m): return m[val(pos, prev)] # Check if pos is >=n if (pos >= n): return 0 # Check if p[pos].first is # less than prev if (p[pos].first <= prev): return findMaxChainLen(p, n, prev, pos + 1) else: ans = max(findMaxChainLen(p, n, p[pos].second, 0) + 1, findMaxChainLen(p, n, prev, pos + 1)) m[val(pos, prev)] = ans return ans # Function to calculate maximum# chain lengthdef maxChainLen(p,n): global m m.clear() # Call memoisation function ans = findMaxChainLen(p, n, 0, 0) return ans # Driver Coden = 5p = [0]*np[0] = val(5,24) p[1] = val(39,60) p[2] = val(15,28) p[3] = val(27,40) p[4] = val(50,90) m = {} # Function Callprint(maxChainLen(p, n)) # This code is contributed by shinjanpatra", "e": 43237, "s": 42078, "text": null }, { "code": "<script> // JavaScript program for above approach // Structure valclass val{ constructor(first,second){ this.first = first; this.second = second; }}; let m = new Map(); // Memoisation functionfunction findMaxChainLen(p,n,prev,pos){ // Check if pair { pos, prev } exists // in m if (m.has(new val(pos, prev))) return m.get(new val(pos, prev)); // Check if pos is >=n if (pos >= n) return 0; // Check if p[pos].first is // less than prev if (p[pos].first <= prev) { return findMaxChainLen(p, n, prev, pos + 1); } else { let ans = Math.max(findMaxChainLen(p, n, p[pos].second, 0) + 1, findMaxChainLen(p, n, prev, pos + 1)); m.set(new val(pos, prev),ans); return ans; }} // Function to calculate maximum// chain lengthfunction maxChainLen(p,n){ m.clear(); // Call memoisation function let ans = findMaxChainLen(p, n, 0, 0); return ans;} // Driver Codelet n = 5;let p = new Array(n);p[0] = new val(5,24); p[1] = new val(39,60); p[2] = new val(15,28); p[3] = new val(27,40); p[4] = new val(50,90); // Function Calldocument.write(maxChainLen(p, n),\"</br>\"); // code is contributed by shinjanpatra </script>", "e": 44568, "s": 43237, "text": null }, { "code": null, "e": 44570, "s": 44568, "text": "3" }, { "code": null, "e": 44604, "s": 44570, "text": "https://www.youtube.com/watch?v=v" }, { "code": null, "e": 44616, "s": 44604, "text": "-HIXptqM3Q " }, { "code": null, "e": 44741, "s": 44616, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 44756, "s": 44743, "text": "nitin mittal" }, { "code": null, "e": 44770, "s": 44756, "text": "rathbhupendra" }, { "code": null, "e": 44784, "s": 44770, "text": "sunilkannur98" }, { "code": null, "e": 44791, "s": 44784, "text": "surajv" }, { "code": null, "e": 44812, "s": 44791, "text": "avanitrachhadiya2155" }, { "code": null, "e": 44824, "s": 44812, "text": "29AjayKumar" }, { "code": null, "e": 44837, "s": 44824, "text": "shinjanpatra" }, { "code": null, "e": 44844, "s": 44837, "text": "Amazon" }, { "code": null, "e": 44864, "s": 44844, "text": "Dynamic Programming" }, { "code": null, "e": 44871, "s": 44864, "text": "Greedy" }, { "code": null, "e": 44878, "s": 44871, "text": "Amazon" }, { "code": null, "e": 44898, "s": 44878, "text": "Dynamic Programming" }, { "code": null, "e": 44905, "s": 44898, "text": "Greedy" }, { "code": null, "e": 45003, "s": 44905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45034, "s": 45003, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 45067, "s": 45034, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 45094, "s": 45067, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 45113, "s": 45094, "text": "Coin Change | DP-7" }, { "code": null, "e": 45148, "s": 45113, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 45199, "s": 45148, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 45250, "s": 45199, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 45308, "s": 45250, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 45335, "s": 45308, "text": "Program for array rotation" } ]
C# | Add key and value into StringDictionary - GeeksforGeeks
01 Feb, 2019 StringDictionary.Add(String, String) method is used to add an entry with the specified key and value into the StringDictionary. Syntax: public virtual void Add (string key, string value); Parameters: key: It is the key of the entry which is to be added. value: It is the value of the entry which is to be added. The value can be null. Exceptions: ArgumentNullException : If the key is null. ArgumentException : It is an entry with the same key already exists in the StringDictionary. NotSupportedException : If the StringDictionary is read-only. Below programs illustrate the use of StringDictionary.Add(String, String) method: Example 1: // C# code to add key and value// into the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add("A", "Apple"); myDict.Add("B", "Banana"); myDict.Add("C", "Cat"); myDict.Add("D", "Dog"); myDict.Add("E", "Elephant"); // Displaying the keys and values in StringDictionary foreach(DictionaryEntry dic in myDict) { Console.WriteLine(dic.Key + " " + dic.Value); } }} Output: d Dog b Banana c Cat e Elephant a Apple Example 2: // C# code to add key and value// into the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add("A", "Apple"); myDict.Add("B", "Banana"); myDict.Add("C", "Cat"); myDict.Add("D", "Dog"); // It should raise "ArgumentException" // as an entry with the same key // already exists in the StringDictionary. myDict.Add("C", "Code"); // Displaying the keys and values in StringDictionary foreach(DictionaryEntry dic in myDict) { Console.WriteLine(dic.Key + " " + dic.Value); } }} Runtime Error: Unhandled Exception:System.ArgumentException: Item has already been added. Key in dictionary: ‘c’ Key being added: ‘c’ Note: The key is handled in a case-insensitive manner i.e, it is translated to lowercase before it is added to the string dictionary. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringdictionary.add?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-method CSharp-Specialized-Namespace CSharp-Specialized-StringDictionary C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25675, "s": 25547, "text": "StringDictionary.Add(String, String) method is used to add an entry with the specified key and value into the StringDictionary." }, { "code": null, "e": 25683, "s": 25675, "text": "Syntax:" }, { "code": null, "e": 25736, "s": 25683, "text": "public virtual void Add (string key, string value);\n" }, { "code": null, "e": 25748, "s": 25736, "text": "Parameters:" }, { "code": null, "e": 25802, "s": 25748, "text": "key: It is the key of the entry which is to be added." }, { "code": null, "e": 25883, "s": 25802, "text": "value: It is the value of the entry which is to be added. The value can be null." }, { "code": null, "e": 25895, "s": 25883, "text": "Exceptions:" }, { "code": null, "e": 25939, "s": 25895, "text": "ArgumentNullException : If the key is null." }, { "code": null, "e": 26032, "s": 25939, "text": "ArgumentException : It is an entry with the same key already exists in the StringDictionary." }, { "code": null, "e": 26094, "s": 26032, "text": "NotSupportedException : If the StringDictionary is read-only." }, { "code": null, "e": 26176, "s": 26094, "text": "Below programs illustrate the use of StringDictionary.Add(String, String) method:" }, { "code": null, "e": 26187, "s": 26176, "text": "Example 1:" }, { "code": "// C# code to add key and value// into the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add(\"A\", \"Apple\"); myDict.Add(\"B\", \"Banana\"); myDict.Add(\"C\", \"Cat\"); myDict.Add(\"D\", \"Dog\"); myDict.Add(\"E\", \"Elephant\"); // Displaying the keys and values in StringDictionary foreach(DictionaryEntry dic in myDict) { Console.WriteLine(dic.Key + \" \" + dic.Value); } }}", "e": 26914, "s": 26187, "text": null }, { "code": null, "e": 26922, "s": 26914, "text": "Output:" }, { "code": null, "e": 26968, "s": 26922, "text": "d Dog\nb Banana\nc Cat\ne Elephant\na Apple\n" }, { "code": null, "e": 26979, "s": 26968, "text": "Example 2:" }, { "code": "// C# code to add key and value// into the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a StringDictionary named myDict StringDictionary myDict = new StringDictionary(); // Adding key and value into the StringDictionary myDict.Add(\"A\", \"Apple\"); myDict.Add(\"B\", \"Banana\"); myDict.Add(\"C\", \"Cat\"); myDict.Add(\"D\", \"Dog\"); // It should raise \"ArgumentException\" // as an entry with the same key // already exists in the StringDictionary. myDict.Add(\"C\", \"Code\"); // Displaying the keys and values in StringDictionary foreach(DictionaryEntry dic in myDict) { Console.WriteLine(dic.Key + \" \" + dic.Value); } }}", "e": 27840, "s": 26979, "text": null }, { "code": null, "e": 27855, "s": 27840, "text": "Runtime Error:" }, { "code": null, "e": 27974, "s": 27855, "text": "Unhandled Exception:System.ArgumentException: Item has already been added. Key in dictionary: ‘c’ Key being added: ‘c’" }, { "code": null, "e": 27980, "s": 27974, "text": "Note:" }, { "code": null, "e": 28108, "s": 27980, "text": "The key is handled in a case-insensitive manner i.e, it is translated to lowercase before it is added to the string dictionary." }, { "code": null, "e": 28142, "s": 28108, "text": "This method is an O(1) operation." }, { "code": null, "e": 28153, "s": 28142, "text": "Reference:" }, { "code": null, "e": 28273, "s": 28153, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringdictionary.add?view=netframework-4.7.2" }, { "code": null, "e": 28302, "s": 28273, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 28316, "s": 28302, "text": "CSharp-method" }, { "code": null, "e": 28345, "s": 28316, "text": "CSharp-Specialized-Namespace" }, { "code": null, "e": 28381, "s": 28345, "text": "CSharp-Specialized-StringDictionary" }, { "code": null, "e": 28384, "s": 28381, "text": "C#" }, { "code": null, "e": 28482, "s": 28384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28505, "s": 28482, "text": "Extension Method in C#" }, { "code": null, "e": 28533, "s": 28505, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28550, "s": 28533, "text": "C# | Inheritance" }, { "code": null, "e": 28572, "s": 28550, "text": "Partial Classes in C#" }, { "code": null, "e": 28601, "s": 28572, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28641, "s": 28601, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28664, "s": 28641, "text": "Switch Statement in C#" }, { "code": null, "e": 28704, "s": 28664, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28747, "s": 28704, "text": "C# | How to insert an element in an Array?" } ]
Python | Remove repeated sublists from given list - GeeksforGeeks
06 May, 2019 Given a list of lists, write a Python program to remove all the repeated sublists (also with different order) from given list. Examples: Input : [[1], [1, 2], [3, 4, 5], [2, 1]] Output : [[1], [1, 2], [3, 4, 5]] Input : [['a'], ['x', 'y', 'z'], ['m', 'n'], ['a'], ['m', 'n']] Output : [['a'], ['x', 'y', 'z'], ['m', 'n']] Approach #1 : Set comprehension + Unpacking Our first approach is to use set comprehension with sorted tuple. In every iteration in the list, we convert the current sublist to a sorted tuple, and return a set of all these tuples, which in turn eliminates all repeated occurrences of the sublists and thus, remove all repeated rearranged sublists. # Python3 program to Remove repeated # unordered sublists from list def Remove(lst): return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}]) # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst)) [[1, 2], [3, 4, 5], [1]] Approach #2 : Using map() with set and sorted tuples. # Python3 program to Remove repeated # unordered sublists from list def Remove(lst): return list(map(list, (set(map(lambda x: tuple(sorted(x)), lst))))) # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst)) [[1, 2], [3, 4, 5], [1]] With maintaining order – Approach #3 : Using sorted tuple as hash First, we initialize an empty list as ‘res’ and a set as ‘check’. Now, For each sublist in the list, convert the sublist to sorted tuple and save it in ‘hsh’. Then check if hsh is present in check or not. If not, append the current sublist to ‘.res’ and ‘hsh’ to ‘check’. This way it would be easier to maintain the order to sublists. # Python3 program to Remove repeated # unordered sublists from list def Remove(lst): res = [] check = set() for x in lst: hsh = tuple(sorted(x)) if hsh not in check: res.append(x) check.add(hsh) return res # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst)) [[1], [1, 2], [3, 4, 5]] Python list-programs Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26361, "s": 26333, "text": "\n06 May, 2019" }, { "code": null, "e": 26488, "s": 26361, "text": "Given a list of lists, write a Python program to remove all the repeated sublists (also with different order) from given list." }, { "code": null, "e": 26498, "s": 26488, "text": "Examples:" }, { "code": null, "e": 26686, "s": 26498, "text": "Input : [[1], [1, 2], [3, 4, 5], [2, 1]]\nOutput : [[1], [1, 2], [3, 4, 5]]\n\nInput : [['a'], ['x', 'y', 'z'], ['m', 'n'], ['a'], ['m', 'n']]\nOutput : [['a'], ['x', 'y', 'z'], ['m', 'n']]\n" }, { "code": null, "e": 26731, "s": 26686, "text": " Approach #1 : Set comprehension + Unpacking" }, { "code": null, "e": 27034, "s": 26731, "text": "Our first approach is to use set comprehension with sorted tuple. In every iteration in the list, we convert the current sublist to a sorted tuple, and return a set of all these tuples, which in turn eliminates all repeated occurrences of the sublists and thus, remove all repeated rearranged sublists." }, { "code": "# Python3 program to Remove repeated # unordered sublists from list def Remove(lst): return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}]) # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst))", "e": 27265, "s": 27034, "text": null }, { "code": null, "e": 27291, "s": 27265, "text": "[[1, 2], [3, 4, 5], [1]]\n" }, { "code": null, "e": 27346, "s": 27291, "text": " Approach #2 : Using map() with set and sorted tuples." }, { "code": "# Python3 program to Remove repeated # unordered sublists from list def Remove(lst): return list(map(list, (set(map(lambda x: tuple(sorted(x)), lst))))) # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst))", "e": 27580, "s": 27346, "text": null }, { "code": null, "e": 27606, "s": 27580, "text": "[[1, 2], [3, 4, 5], [1]]\n" }, { "code": null, "e": 27631, "s": 27606, "text": "With maintaining order –" }, { "code": null, "e": 27672, "s": 27631, "text": "Approach #3 : Using sorted tuple as hash" }, { "code": null, "e": 28007, "s": 27672, "text": "First, we initialize an empty list as ‘res’ and a set as ‘check’. Now, For each sublist in the list, convert the sublist to sorted tuple and save it in ‘hsh’. Then check if hsh is present in check or not. If not, append the current sublist to ‘.res’ and ‘hsh’ to ‘check’. This way it would be easier to maintain the order to sublists." }, { "code": "# Python3 program to Remove repeated # unordered sublists from list def Remove(lst): res = [] check = set() for x in lst: hsh = tuple(sorted(x)) if hsh not in check: res.append(x) check.add(hsh) return res # Driver codelst = [[1], [1, 2], [3, 4, 5], [2, 1]]print(Remove(lst))", "e": 28363, "s": 28007, "text": null }, { "code": null, "e": 28389, "s": 28363, "text": "[[1], [1, 2], [3, 4, 5]]\n" }, { "code": null, "e": 28410, "s": 28389, "text": "Python list-programs" }, { "code": null, "e": 28417, "s": 28410, "text": "Python" }, { "code": null, "e": 28433, "s": 28417, "text": "Python Programs" }, { "code": null, "e": 28531, "s": 28433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28549, "s": 28531, "text": "Python Dictionary" }, { "code": null, "e": 28581, "s": 28549, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28603, "s": 28581, "text": "Enumerate() in Python" }, { "code": null, "e": 28645, "s": 28603, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28671, "s": 28645, "text": "Python String | replace()" }, { "code": null, "e": 28714, "s": 28671, "text": "Python program to convert a list to string" }, { "code": null, "e": 28736, "s": 28714, "text": "Defaultdict in Python" }, { "code": null, "e": 28775, "s": 28736, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28821, "s": 28775, "text": "Python | Split string into list of characters" } ]
What are physical tags in HTML? - GeeksforGeeks
22 Mar, 2021 Physical Tags are used to indicate that how specific characters are to be formatted or indicated using HTML tags. Any physical style tag may contain any item allowed in text, including conventional text, images, line breaks, etc. Although each physical tag has a defined style, you can override that style by defining your own look for each tag. All physical tags require ending tags. Syntax: <tag_name> formatting character or para </tag_name> Features of Physical Tags: They are extremely straightforward. They are used to highlighting important sentences. Physical Text Styles indicate the specific type of appearance for a section e.g., bold, italics, etc. Physical Styles are rendered in the same manner by all browsers. Example of Physical Tags: Tags Meaning Purpose <b> <i> <u> <big> <small> <sub> <sup> <strike> <tt> Examples of Physical Tags: 1.<b>: HTML <b> tag acts as a presentation tag used to markup written text as a bold format. If we want to display plain text in bold format you can use text between <b>sentence</b> tag. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <b>amet consectetur</b> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: Lorem ipsum dolor sit amet consectetur adipisicing elit. 2.<i>: HTML <i> tag acts as a presentation tag used to markup written text as an italic format. If we want to display plain text in italics format you can use text between <i></i> tag. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <i>amet consectetur</i> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, tempora. 3.<u>: HTML <u> tag acts as a presentation tag used to markup written text as an underline format. If we want to display plain text in underline format you can use text between <u></u> tag. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <u>amet consectetur</u> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, tempora. 4.<big>: The <big> tag is used to make the text one size bigger i.e small to medium, medium to large, and large to x-large but the <big> tag will not make the font size larger than the browser’s maximum font-size. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <p> Lorem ipsum dolor sit <big>amet consectetur</big> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: 5.<small>: The <small> tag is used to make the text one size smaller i.e x-large to large .... small but <small> tag will not make the font-size smaller than the browser’s minimum font-size. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <small>amet consectetur</small> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: 6.<sub>: Sub tag defines subscript. Subscript appears half below a normal line with small font size. These tags are mostly used while writing chemical formulas. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor <sub>sit amet </sub> consectetur adipisicing elit. Voluptates, tempora. </p> <p> Acetylene C<sub>2</sub> H<sub>2</sub> </p> </body></html> Output: Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, tempora. Acetylene C2H2 7.<sup>: Sup tag defines superscript. Subscript appears half above the normal line with small font size. These tags are mostly used while writing mathematical derivations. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <sup>amet consectetur</sup> adipisicing elit. Voluptates, tempora. </p> <p> (a+b)<sup>2</sup> = a<sup>2</sup>+b<sup>2</sup>+2ab </p> </body></html> Output: Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, tempora. (a+b)2 = a2+b2+2ab 8.<strike>: Strike tag defines Strike through sentences. The strike tag makes the horizontal line over the text which represents that this given text is not for reading ignore it. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <strike>amet consectetur</strike> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, tempora. 9.<tt>: tt tag defines teletype text. This tag changes the given sentence into its default font-family i.e mono space. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head> <body> <p> Lorem ipsum dolor sit <tt>amet consectetur</tt> adipisicing elit. Voluptates, tempora. </p> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Basics HTML-Questions HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 33029, "s": 33001, "text": "\n22 Mar, 2021" }, { "code": null, "e": 33414, "s": 33029, "text": "Physical Tags are used to indicate that how specific characters are to be formatted or indicated using HTML tags. Any physical style tag may contain any item allowed in text, including conventional text, images, line breaks, etc. Although each physical tag has a defined style, you can override that style by defining your own look for each tag. All physical tags require ending tags." }, { "code": null, "e": 33422, "s": 33414, "text": "Syntax:" }, { "code": null, "e": 33474, "s": 33422, "text": "<tag_name> formatting character or para </tag_name>" }, { "code": null, "e": 33501, "s": 33474, "text": "Features of Physical Tags:" }, { "code": null, "e": 33537, "s": 33501, "text": "They are extremely straightforward." }, { "code": null, "e": 33588, "s": 33537, "text": "They are used to highlighting important sentences." }, { "code": null, "e": 33690, "s": 33588, "text": "Physical Text Styles indicate the specific type of appearance for a section e.g., bold, italics, etc." }, { "code": null, "e": 33755, "s": 33690, "text": "Physical Styles are rendered in the same manner by all browsers." }, { "code": null, "e": 33781, "s": 33755, "text": "Example of Physical Tags:" }, { "code": null, "e": 33786, "s": 33781, "text": "Tags" }, { "code": null, "e": 33794, "s": 33786, "text": "Meaning" }, { "code": null, "e": 33802, "s": 33794, "text": "Purpose" }, { "code": null, "e": 33806, "s": 33802, "text": "<b>" }, { "code": null, "e": 33810, "s": 33806, "text": "<i>" }, { "code": null, "e": 33814, "s": 33810, "text": "<u>" }, { "code": null, "e": 33820, "s": 33814, "text": "<big>" }, { "code": null, "e": 33828, "s": 33820, "text": "<small>" }, { "code": null, "e": 33834, "s": 33828, "text": "<sub>" }, { "code": null, "e": 33840, "s": 33834, "text": "<sup>" }, { "code": null, "e": 33849, "s": 33840, "text": "<strike>" }, { "code": null, "e": 33854, "s": 33849, "text": "<tt>" }, { "code": null, "e": 33881, "s": 33854, "text": "Examples of Physical Tags:" }, { "code": null, "e": 34068, "s": 33881, "text": "1.<b>: HTML <b> tag acts as a presentation tag used to markup written text as a bold format. If we want to display plain text in bold format you can use text between <b>sentence</b> tag." }, { "code": null, "e": 34073, "s": 34068, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <b>amet consectetur</b> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 34426, "s": 34073, "text": null }, { "code": null, "e": 34434, "s": 34426, "text": "Output:" }, { "code": null, "e": 34492, "s": 34434, "text": "Lorem ipsum dolor sit amet consectetur\nadipisicing elit. " }, { "code": null, "e": 34677, "s": 34492, "text": "2.<i>: HTML <i> tag acts as a presentation tag used to markup written text as an italic format. If we want to display plain text in italics format you can use text between <i></i> tag." }, { "code": null, "e": 34682, "s": 34677, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <i>amet consectetur</i> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 35035, "s": 34682, "text": null }, { "code": null, "e": 35043, "s": 35035, "text": "Output:" }, { "code": null, "e": 35121, "s": 35043, "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit.\nVoluptates, tempora." }, { "code": null, "e": 35311, "s": 35121, "text": "3.<u>: HTML <u> tag acts as a presentation tag used to markup written text as an underline format. If we want to display plain text in underline format you can use text between <u></u> tag." }, { "code": null, "e": 35316, "s": 35311, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <u>amet consectetur</u> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 35668, "s": 35316, "text": null }, { "code": null, "e": 35676, "s": 35668, "text": "Output:" }, { "code": null, "e": 35754, "s": 35676, "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit.\nVoluptates, tempora." }, { "code": null, "e": 35968, "s": 35754, "text": "4.<big>: The <big> tag is used to make the text one size bigger i.e small to medium, medium to large, and large to x-large but the <big> tag will not make the font size larger than the browser’s maximum font-size." }, { "code": null, "e": 35973, "s": 35968, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <p> Lorem ipsum dolor sit <big>amet consectetur</big> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 36353, "s": 35973, "text": null }, { "code": null, "e": 36361, "s": 36353, "text": "Output:" }, { "code": null, "e": 36552, "s": 36361, "text": "5.<small>: The <small> tag is used to make the text one size smaller i.e x-large to large .... small but <small> tag will not make the font-size smaller than the browser’s minimum font-size." }, { "code": null, "e": 36557, "s": 36552, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <small>amet consectetur</small> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 36918, "s": 36557, "text": null }, { "code": null, "e": 36926, "s": 36918, "text": "Output:" }, { "code": null, "e": 37087, "s": 36926, "text": "6.<sub>: Sub tag defines subscript. Subscript appears half below a normal line with small font size. These tags are mostly used while writing chemical formulas." }, { "code": null, "e": 37092, "s": 37087, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor <sub>sit amet </sub> consectetur adipisicing elit. Voluptates, tempora. </p> <p> Acetylene C<sub>2</sub> H<sub>2</sub> </p> </body></html>", "e": 37510, "s": 37092, "text": null }, { "code": null, "e": 37518, "s": 37510, "text": "Output:" }, { "code": null, "e": 37611, "s": 37518, "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, tempora.\nAcetylene C2H2" }, { "code": null, "e": 37783, "s": 37611, "text": "7.<sup>: Sup tag defines superscript. Subscript appears half above the normal line with small font size. These tags are mostly used while writing mathematical derivations." }, { "code": null, "e": 37788, "s": 37783, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <sup>amet consectetur</sup> adipisicing elit. Voluptates, tempora. </p> <p> (a+b)<sup>2</sup> = a<sup>2</sup>+b<sup>2</sup>+2ab </p> </body></html>", "e": 38219, "s": 37788, "text": null }, { "code": null, "e": 38227, "s": 38219, "text": "Output:" }, { "code": null, "e": 38326, "s": 38227, "text": "Lorem ipsum dolor sit amet consectetur \nadipisicing elit. Voluptates, tempora.\n\n(a+b)2 = a2+b2+2ab" }, { "code": null, "e": 38506, "s": 38326, "text": "8.<strike>: Strike tag defines Strike through sentences. The strike tag makes the horizontal line over the text which represents that this given text is not for reading ignore it." }, { "code": null, "e": 38511, "s": 38506, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <strike>amet consectetur</strike> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 38874, "s": 38511, "text": null }, { "code": null, "e": 38882, "s": 38874, "text": "Output:" }, { "code": null, "e": 38961, "s": 38882, "text": "Lorem ipsum dolor sit amet consectetur \nadipisicing elit. Voluptates, tempora." }, { "code": null, "e": 39080, "s": 38961, "text": "9.<tt>: tt tag defines teletype text. This tag changes the given sentence into its default font-family i.e mono space." }, { "code": null, "e": 39085, "s": 39080, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head> <body> <p> Lorem ipsum dolor sit <tt>amet consectetur</tt> adipisicing elit. Voluptates, tempora. </p> </body></html>", "e": 39440, "s": 39085, "text": null }, { "code": null, "e": 39448, "s": 39440, "text": "Output:" }, { "code": null, "e": 39585, "s": 39448, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 39597, "s": 39585, "text": "HTML-Basics" }, { "code": null, "e": 39612, "s": 39597, "text": "HTML-Questions" }, { "code": null, "e": 39622, "s": 39612, "text": "HTML-Tags" }, { "code": null, "e": 39629, "s": 39622, "text": "Picked" }, { "code": null, "e": 39634, "s": 39629, "text": "HTML" }, { "code": null, "e": 39651, "s": 39634, "text": "Web Technologies" }, { "code": null, "e": 39656, "s": 39651, "text": "HTML" }, { "code": null, "e": 39754, "s": 39656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39804, "s": 39754, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39866, "s": 39804, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39914, "s": 39866, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39974, "s": 39914, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 40027, "s": 39974, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 40067, "s": 40027, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40100, "s": 40067, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40145, "s": 40100, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40188, "s": 40145, "text": "How to fetch data from an API in ReactJS ?" } ]
How to convert a 2D array to a comma-separated values (CSV) string in JavaScript ? - GeeksforGeeks
26 Apr, 2021 Given a 2D array, we have to convert it to a comma-separated values (CSV) string using JS. Input: [ [ "a" , "b"] , [ "c" ,"d" ] ] Output: "a,b c,d" Input: [ [ "1", "2"] ["3", "4"] ["5", "6"] ] Output: "1,2 3,4 5,6" To achieve this, we must know some array prototype functions which will be helpful in this regard: Join function: The Array.prototype.join( ) function is used to join all the strings in an array with a character/string. Example: [ "a","b"].join( ",") will result in : "a,b" Map function: The Array.prototype.map() returns a new array with the results of calling a function which we provide, on each element. Example: arr= ["a","b"] // Adding "c" to each element newArray = arr.map( item => item + "c") value of newArray = ["ac", "bc"] Approach: We will use the map function and join function to combine each 1D row into a string with the separation of a comma. and then join all the individual strings with “\n”, using the join function. Example: Javascript <script>// Create CSV file data in an array var array2D = [ [ "a" , "2"] , [ "c" ,"d" ] ]; // Use map function to traverse on each rowvar csv = array2D .map((item) => { // Here item refers to a row in that 2D array var row = item; // Now join the elements of row with "," using join function return row.join(","); }) // At this point we have an array of strings .join("\n"); // Join the array of strings with "\n"console.log(csv);</script> Output: a,2 c,d Explanation: We first used the map function on the 2D array to traverse on each row, then we used the join function to join the array of elements in that row using a comma. Next, that map function returns an array of strings, which we join by using “\n”. Thus resulting in a CSV string. Alternative Approach: We can even use for loops to traverse in the array, instead of a map. Example: Javascript <script>var csv="";create CSV file data in an array var array2D = [ [ "a" , "2"] , [ "c" ,"d" ] ]; for (var index1 in array2D) { var row = array2D[index1]; // Row is the row of array at index "index1" var string = ""; // Empty string which will be added later for (var index in row) { // Traversing each element in the row var w = row[index]; // Adding the element at index "index" to the string string += w; if (index != row.length - 1) { string += ","; // If the element is not the last element , then add a comma } } string += "\n"; // Adding next line at the end csv += string; // adding the string to the final string "csv"}console.log(csv);</script> Output: a,2 c,d javascript-array JavaScript-Methods JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 39215, "s": 39187, "text": "\n26 Apr, 2021" }, { "code": null, "e": 39306, "s": 39215, "text": "Given a 2D array, we have to convert it to a comma-separated values (CSV) string using JS." }, { "code": null, "e": 39432, "s": 39306, "text": "Input:\n[ [ \"a\" , \"b\"] , [ \"c\" ,\"d\" ] ]\nOutput:\n\"a,b \n c,d\"\nInput:\n[ [ \"1\", \"2\"]\n[\"3\", \"4\"]\n[\"5\", \"6\"] ]\nOutput:\n\"1,2\n3,4\n5,6\"" }, { "code": null, "e": 39531, "s": 39432, "text": "To achieve this, we must know some array prototype functions which will be helpful in this regard:" }, { "code": null, "e": 39652, "s": 39531, "text": "Join function: The Array.prototype.join( ) function is used to join all the strings in an array with a character/string." }, { "code": null, "e": 39661, "s": 39652, "text": "Example:" }, { "code": null, "e": 39706, "s": 39661, "text": "[ \"a\",\"b\"].join( \",\") will result in : \"a,b\"" }, { "code": null, "e": 39840, "s": 39706, "text": "Map function: The Array.prototype.map() returns a new array with the results of calling a function which we provide, on each element." }, { "code": null, "e": 39849, "s": 39840, "text": "Example:" }, { "code": null, "e": 39969, "s": 39849, "text": "arr= [\"a\",\"b\"]\n\n// Adding \"c\" to each element\nnewArray = arr.map( item => item + \"c\") \nvalue of newArray = [\"ac\", \"bc\"]" }, { "code": null, "e": 40172, "s": 39969, "text": "Approach: We will use the map function and join function to combine each 1D row into a string with the separation of a comma. and then join all the individual strings with “\\n”, using the join function." }, { "code": null, "e": 40181, "s": 40172, "text": "Example:" }, { "code": null, "e": 40192, "s": 40181, "text": "Javascript" }, { "code": "<script>// Create CSV file data in an array var array2D = [ [ \"a\" , \"2\"] , [ \"c\" ,\"d\" ] ]; // Use map function to traverse on each rowvar csv = array2D .map((item) => { // Here item refers to a row in that 2D array var row = item; // Now join the elements of row with \",\" using join function return row.join(\",\"); }) // At this point we have an array of strings .join(\"\\n\"); // Join the array of strings with \"\\n\"console.log(csv);</script>", "e": 40709, "s": 40192, "text": null }, { "code": null, "e": 40717, "s": 40709, "text": "Output:" }, { "code": null, "e": 40725, "s": 40717, "text": "a,2\nc,d" }, { "code": null, "e": 41013, "s": 40725, "text": "Explanation: We first used the map function on the 2D array to traverse on each row, then we used the join function to join the array of elements in that row using a comma. Next, that map function returns an array of strings, which we join by using “\\n”. Thus resulting in a CSV string." }, { "code": null, "e": 41105, "s": 41013, "text": "Alternative Approach: We can even use for loops to traverse in the array, instead of a map." }, { "code": null, "e": 41114, "s": 41105, "text": "Example:" }, { "code": null, "e": 41125, "s": 41114, "text": "Javascript" }, { "code": "<script>var csv=\"\";create CSV file data in an array var array2D = [ [ \"a\" , \"2\"] , [ \"c\" ,\"d\" ] ]; for (var index1 in array2D) { var row = array2D[index1]; // Row is the row of array at index \"index1\" var string = \"\"; // Empty string which will be added later for (var index in row) { // Traversing each element in the row var w = row[index]; // Adding the element at index \"index\" to the string string += w; if (index != row.length - 1) { string += \",\"; // If the element is not the last element , then add a comma } } string += \"\\n\"; // Adding next line at the end csv += string; // adding the string to the final string \"csv\"}console.log(csv);</script>", "e": 41884, "s": 41125, "text": null }, { "code": null, "e": 41900, "s": 41884, "text": "Output:\na,2\nc,d" }, { "code": null, "e": 41917, "s": 41900, "text": "javascript-array" }, { "code": null, "e": 41936, "s": 41917, "text": "JavaScript-Methods" }, { "code": null, "e": 41957, "s": 41936, "text": "JavaScript-Questions" }, { "code": null, "e": 41964, "s": 41957, "text": "Picked" }, { "code": null, "e": 41975, "s": 41964, "text": "JavaScript" }, { "code": null, "e": 41992, "s": 41975, "text": "Web Technologies" }, { "code": null, "e": 42090, "s": 41992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42130, "s": 42090, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42175, "s": 42130, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42236, "s": 42175, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42308, "s": 42236, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42377, "s": 42308, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42417, "s": 42377, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42450, "s": 42417, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42495, "s": 42450, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42538, "s": 42495, "text": "How to fetch data from an API in ReactJS ?" } ]
PHP | Sessions - GeeksforGeeks
12 Feb, 2019 What is a session? In general, session refers to a frame of communication between two medium. A PHP session is used to store data on a server rather than the computer of the user. Session identifiers or SID is a unique number which is used to identify every user in a session based environment. The SID is used to link the user with his information on the server like posts, emails etc. How are sessions better than cookies? Although cookies are also used for storing user related data, they have serious security issues because cookies are stored on the user’s computer and thus they are open to attackers to easily modify the content of the cookie.Addition of harmful data by the attackers in the cookie may result in the breakdown of the application.Apart from that cookies affect the performance of a site since cookies send the user data each time the user views a page.Every time the browser requests a URL to the server, all the cookie data for that website is automatically sent to the server within the request. Below are different steps involved in PHP sessions: Starting a PHP Session: The first step is to start up a session. After a session is started, session variables can be created to store information. The PHP session_start() function is used to begin a new session.It als creates a new session ID for the user.Below is the PHP code to start a new session:<?php session_start(); ?> Below is the PHP code to start a new session: <?php session_start(); ?> Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal array.The stored data can be accessed during lifetime of a session.Below is the PHP code to store a session with two session variables Rollnumber and Name:<?php session_start(); $_SESSION["Rollnumber"] = "11";$_SESSION["Name"] = "Ajay"; ?> Below is the PHP code to store a session with two session variables Rollnumber and Name: <?php session_start(); $_SESSION["Rollnumber"] = "11";$_SESSION["Name"] = "Ajay"; ?> Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key to the $_SESSION associative array.The PHP code to access a session data with two session variables Rollnumber and Name is shown below:<?php session_start(); echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>'; echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>'; ?>Output:The Name of the student is :Ajay The Roll number of the student is :11 The PHP code to access a session data with two session variables Rollnumber and Name is shown below: <?php session_start(); echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>'; echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>'; ?> Output: The Name of the student is :Ajay The Roll number of the student is :11 Destroying Certain Session Data: To delete only a certain session data,the unset feature can be used with the corresponding session variable in the $_SESSION associative array.The PHP code to unset only the “Rollnumber” session variable from the associative session array:<?php session_start(); if(isset($_SESSION["Name"])){ unset($_SESSION["Rollnumber"]);} ?> The PHP code to unset only the “Rollnumber” session variable from the associative session array: <?php session_start(); if(isset($_SESSION["Name"])){ unset($_SESSION["Rollnumber"]);} ?> Destroying Complete Session: The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.<?php session_start();session_destroy(); ?> Destroying Complete Session: The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument. <?php session_start();session_destroy(); ?> Important Points The session IDs are randomly generated by the PHP engine .The session data is stored on the server therefore it doesn’t have to be sent with every browser request.The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser. The session IDs are randomly generated by the PHP engine . The session data is stored on the server therefore it doesn’t have to be sent with every browser request. The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser. jqturn PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 42165, "s": 42137, "text": "\n12 Feb, 2019" }, { "code": null, "e": 42184, "s": 42165, "text": "What is a session?" }, { "code": null, "e": 42552, "s": 42184, "text": "In general, session refers to a frame of communication between two medium. A PHP session is used to store data on a server rather than the computer of the user. Session identifiers or SID is a unique number which is used to identify every user in a session based environment. The SID is used to link the user with his information on the server like posts, emails etc." }, { "code": null, "e": 42590, "s": 42552, "text": "How are sessions better than cookies?" }, { "code": null, "e": 43186, "s": 42590, "text": "Although cookies are also used for storing user related data, they have serious security issues because cookies are stored on the user’s computer and thus they are open to attackers to easily modify the content of the cookie.Addition of harmful data by the attackers in the cookie may result in the breakdown of the application.Apart from that cookies affect the performance of a site since cookies send the user data each time the user views a page.Every time the browser requests a URL to the server, all the cookie data for that website is automatically sent to the server within the request." }, { "code": null, "e": 43238, "s": 43186, "text": "Below are different steps involved in PHP sessions:" }, { "code": null, "e": 43568, "s": 43238, "text": "Starting a PHP Session: The first step is to start up a session. After a session is started, session variables can be created to store information. The PHP session_start() function is used to begin a new session.It als creates a new session ID for the user.Below is the PHP code to start a new session:<?php session_start(); ?>" }, { "code": null, "e": 43614, "s": 43568, "text": "Below is the PHP code to start a new session:" }, { "code": "<?php session_start(); ?>", "e": 43642, "s": 43614, "text": null }, { "code": null, "e": 43973, "s": 43642, "text": "Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal array.The stored data can be accessed during lifetime of a session.Below is the PHP code to store a session with two session variables Rollnumber and Name:<?php session_start(); $_SESSION[\"Rollnumber\"] = \"11\";$_SESSION[\"Name\"] = \"Ajay\"; ?>" }, { "code": null, "e": 44062, "s": 43973, "text": "Below is the PHP code to store a session with two session variables Rollnumber and Name:" }, { "code": "<?php session_start(); $_SESSION[\"Rollnumber\"] = \"11\";$_SESSION[\"Name\"] = \"Ajay\"; ?>", "e": 44150, "s": 44062, "text": null }, { "code": null, "e": 44685, "s": 44150, "text": "Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key to the $_SESSION associative array.The PHP code to access a session data with two session variables Rollnumber and Name is shown below:<?php session_start(); echo 'The Name of the student is :' . $_SESSION[\"Name\"] . '<br>'; echo 'The Roll number of the student is :' . $_SESSION[\"Rollnumber\"] . '<br>'; ?>Output:The Name of the student is :Ajay \nThe Roll number of the student is :11" }, { "code": null, "e": 44786, "s": 44685, "text": "The PHP code to access a session data with two session variables Rollnumber and Name is shown below:" }, { "code": "<?php session_start(); echo 'The Name of the student is :' . $_SESSION[\"Name\"] . '<br>'; echo 'The Roll number of the student is :' . $_SESSION[\"Rollnumber\"] . '<br>'; ?>", "e": 44960, "s": 44786, "text": null }, { "code": null, "e": 44968, "s": 44960, "text": "Output:" }, { "code": null, "e": 45040, "s": 44968, "text": "The Name of the student is :Ajay \nThe Roll number of the student is :11" }, { "code": null, "e": 45408, "s": 45040, "text": "Destroying Certain Session Data: To delete only a certain session data,the unset feature can be used with the corresponding session variable in the $_SESSION associative array.The PHP code to unset only the “Rollnumber” session variable from the associative session array:<?php session_start(); if(isset($_SESSION[\"Name\"])){ unset($_SESSION[\"Rollnumber\"]);} ?>" }, { "code": null, "e": 45505, "s": 45408, "text": "The PHP code to unset only the “Rollnumber” session variable from the associative session array:" }, { "code": "<?php session_start(); if(isset($_SESSION[\"Name\"])){ unset($_SESSION[\"Rollnumber\"]);} ?>", "e": 45601, "s": 45505, "text": null }, { "code": null, "e": 45809, "s": 45601, "text": "Destroying Complete Session: The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.<?php session_start();session_destroy(); ?>" }, { "code": null, "e": 45972, "s": 45809, "text": "Destroying Complete Session: The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument." }, { "code": "<?php session_start();session_destroy(); ?>", "e": 46018, "s": 45972, "text": null }, { "code": null, "e": 46035, "s": 46018, "text": "Important Points" }, { "code": null, "e": 46337, "s": 46035, "text": "The session IDs are randomly generated by the PHP engine .The session data is stored on the server therefore it doesn’t have to be sent with every browser request.The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser." }, { "code": null, "e": 46396, "s": 46337, "text": "The session IDs are randomly generated by the PHP engine ." }, { "code": null, "e": 46502, "s": 46396, "text": "The session data is stored on the server therefore it doesn’t have to be sent with every browser request." }, { "code": null, "e": 46641, "s": 46502, "text": "The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser." }, { "code": null, "e": 46648, "s": 46641, "text": "jqturn" }, { "code": null, "e": 46652, "s": 46648, "text": "PHP" }, { "code": null, "e": 46669, "s": 46652, "text": "Web Technologies" }, { "code": null, "e": 46673, "s": 46669, "text": "PHP" }, { "code": null, "e": 46771, "s": 46673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46816, "s": 46771, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 46866, "s": 46816, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 46906, "s": 46866, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 46930, "s": 46906, "text": "PHP in_array() Function" }, { "code": null, "e": 46974, "s": 46930, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 47014, "s": 46974, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47047, "s": 47014, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47092, "s": 47047, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47135, "s": 47092, "text": "How to fetch data from an API in ReactJS ?" } ]
Sum of all integers in given N ranges - GeeksforGeeks
17 Dec, 2021 Given N ranges of the form [L, R], the task is to find the sum of all integers that lie in any of the given ranges. Examples: Input: arr[] = {{1, 5}, {3, 7}}, N = 2Output: 28Explanation: The set of integers that exist in one or more ranges is {1, 2, 3, 4, 5 , 6, 7}. Hence there sum is 28. Input: ranges[] = {{-12, 15}, {3, 9}, {-5, -2}, {20, 25}, {16, 20}}Output: 247 Approach: The given problem can be solved by an approach similar to the Merge Overlapping Intervals problem. Below are the steps to follow: Sort the intervals based on increasing order of L. Push the first interval onto a stack and for each interval do the following:If the current interval does not overlap with the stack top, push it.If the current interval overlaps with stack top and right end of the current interval is more than that of stack top, update stack top with the value of right end of current interval. If the current interval does not overlap with the stack top, push it. If the current interval overlaps with stack top and right end of the current interval is more than that of stack top, update stack top with the value of right end of current interval. After traversing through all intervals, the remaining stack contains the merged intervals. The sum of the merged intervals can be calculated using formula for the sum of an Arithmetic Progression as the range [L, R] forms an AP with a common difference as 1 and the number of elements as R – L + 1. The sum is ((L + R)*(R-L+1))/2. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach#include <bits/stdc++.h>#define ll long longusing namespace std; // Function to find the sum of all// integers numbers in range [L, R]ll sumInRange(long L, long R){ ll Sum = ((R - L + 1) / 2) * (2 * L + (R - L)); return Sum;} // Function to find sum of all integers// that lie in any of the given rangesll calcSum(vector<pair<long, long> > data, int n){ // Sort intervals in increasing order // according to their first element sort(data.begin(), data.end()); // Merging the overlaping intervals int i, idx = 0; // Loop to iterate through the array for (i = 1; i < n; i++) { // If current interval overlaps // with the previous intervals if ((data[idx].second >= data[i].first) || (data[i].first == data[idx].second + 1)) { // Merge the previou and the // current interval data[idx].second = max(data[idx].second, data[i].second); } else { idx++; data[idx].second = data[i].second; data[idx].first = data[i].first; } } // Stores the required sum ll Sum = 0; // Loop to calculate the sum of all // the remaining merged intervals for (i = 0; i <= idx; i++) { // Add sum of integers // in current range Sum += sumInRange(data[i].first, data[i].second); } // Return the total Sum return Sum;} // Driver Codeint main(){ vector<pair<long, long> > vec = { { -12, 15 }, { 3, 9 }, { -5, -2 }, { 20, 25 }, { 16, 20 } }; cout << calcSum(vec, vec.size()); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the sum of all// integers numbers in range [L, R]static int sumInRange(int L, int R){ int Sum = ((R - L + 1) / 2) * (2 * L + (R - L)); return Sum;} // Function to find sum of all integers// that lie in any of the given rangesstatic int calcSum(int [][]data, int n){ // Sort intervals in increasing order // according to their first element Arrays.sort(data,(a,b)->{ return a[0]-b[0]; }); // Merging the overlaping intervals int i, idx = 0; // Loop to iterate through the array for (i = 1; i < n; i++) { // If current interval overlaps // with the previous intervals if ((data[idx][1] >= data[i][0]) || (data[i][0] == data[idx][1] + 1)) { // Merge the previou and the // current interval data[idx][1] = Math.max(data[idx][1], data[i][1]); } else { idx++; data[idx][1] = data[i][1]; data[idx][0] = data[i][0]; } } // Stores the required sum int Sum = 0; // Loop to calculate the sum of all // the remaining merged intervals for (i = 0; i <= idx; i++) { // Add sum of integers // in current range Sum += sumInRange(data[i][0], data[i][1]); } // Return the total Sum return Sum;} // Driver Codepublic static void main(String[] args){ int [][]vec = { { -12, 15 }, { 3, 9 }, { -5, -2 }, { 20, 25 }, { 16, 20 } }; System.out.print(calcSum(vec, vec.length)); }} // This code is contributed by shikhasingrajput # Python 3 program for the above approach # Function to find the sum of all# integers numbers in range [L, R]def sumInRange(L, R): Sum = ((R - L + 1) // 2) * (2 * L + (R - L)) return Sum # Function to find sum of all integers# that lie in any of the given rangesdef calcSum(data, n): # Sort intervals in increasing order # according to their first element data.sort() # Merging the overlaping intervals idx = 0 # Loop to iterate through the array for i in range(1, n): # If current interval overlaps # with the previous intervals if ((data[idx][1] >= data[i][0]) or (data[i][0] == data[idx][1] + 1)): # Merge the previou and the # current interval data[idx][1] = max(data[idx][1], data[i][1]) else: idx += 1 data[idx][1] = data[i][1] data[idx][0] = data[i][0] # Stores the required sum Sum = 0 # Loop to calculate the sum of all # the remaining merged intervals for i in range(idx+1): # Add sum of integers # in current range Sum += sumInRange(data[i][0], data[i][1]) # Return the total Sum return Sum # Driver Codeif __name__ == "__main__": vec = [[-12, 15], [3, 9], [-5, -2], [20, 25], [16, 20]] print(calcSum(vec, len(vec))) # This code is contributed by ukasp. <script> // JavaScript code for the above approach // Function to find the sum of all // integers numbers in range [L, R] function sumInRange(L, R) { let Sum = ((R - L + 1) / 2) * (2 * L + (R - L)); return Sum; } // Function to find sum of all integers // that lie in any of the given ranges function calcSum(data, n) { // Sort intervals in increasing order // according to their first element data.sort(function (a, b) { return a.first - b.first }) // Merging the overlaping intervals let i, idx = 0; // Loop to iterate through the array for (i = 1; i < n; i++) { // If current interval overlaps // with the previous intervals if ((data[idx].second >= data[i].first) || (data[i].first == data[idx].second + 1)) { // Merge the previou and the // current interval data[idx].second = Math.max(data[idx].second, data[i].second); } else { idx++; data[idx].second = data[i].second; data[idx].first = data[i].first; } } // Stores the required sum let Sum = 0; // Loop to calculate the sum of all // the remaining merged intervals for (i = 0; i <= idx; i++) { // Add sum of integers // in current range Sum += sumInRange(data[i].first, data[i].second); } // Return the total Sum return Sum; } // Driver Code let vec = [{ first: -12, second: 15 }, { first: 3, second: 9 }, { first: -5, second: -2 }, { first: 20, second: 25 }, { first: 16, second: 20 }]; document.write(calcSum(vec, vec.length)); // This code is contributed by Potta Lokesh </script> 247 Time Complexity: O(N*log N)Auxiliary Space: O(1) lokeshpotta20 shikhasingrajput ukasp array-range-queries Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Max Flow Problem Introduction Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26537, "s": 26509, "text": "\n17 Dec, 2021" }, { "code": null, "e": 26653, "s": 26537, "text": "Given N ranges of the form [L, R], the task is to find the sum of all integers that lie in any of the given ranges." }, { "code": null, "e": 26663, "s": 26653, "text": "Examples:" }, { "code": null, "e": 26827, "s": 26663, "text": "Input: arr[] = {{1, 5}, {3, 7}}, N = 2Output: 28Explanation: The set of integers that exist in one or more ranges is {1, 2, 3, 4, 5 , 6, 7}. Hence there sum is 28." }, { "code": null, "e": 26906, "s": 26827, "text": "Input: ranges[] = {{-12, 15}, {3, 9}, {-5, -2}, {20, 25}, {16, 20}}Output: 247" }, { "code": null, "e": 27046, "s": 26906, "text": "Approach: The given problem can be solved by an approach similar to the Merge Overlapping Intervals problem. Below are the steps to follow:" }, { "code": null, "e": 27097, "s": 27046, "text": "Sort the intervals based on increasing order of L." }, { "code": null, "e": 27426, "s": 27097, "text": "Push the first interval onto a stack and for each interval do the following:If the current interval does not overlap with the stack top, push it.If the current interval overlaps with stack top and right end of the current interval is more than that of stack top, update stack top with the value of right end of current interval." }, { "code": null, "e": 27496, "s": 27426, "text": "If the current interval does not overlap with the stack top, push it." }, { "code": null, "e": 27680, "s": 27496, "text": "If the current interval overlaps with stack top and right end of the current interval is more than that of stack top, update stack top with the value of right end of current interval." }, { "code": null, "e": 28011, "s": 27680, "text": "After traversing through all intervals, the remaining stack contains the merged intervals. The sum of the merged intervals can be calculated using formula for the sum of an Arithmetic Progression as the range [L, R] forms an AP with a common difference as 1 and the number of elements as R – L + 1. The sum is ((L + R)*(R-L+1))/2." }, { "code": null, "e": 28062, "s": 28011, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28066, "s": 28062, "text": "C++" }, { "code": null, "e": 28071, "s": 28066, "text": "Java" }, { "code": null, "e": 28079, "s": 28071, "text": "Python3" }, { "code": null, "e": 28090, "s": 28079, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>#define ll long longusing namespace std; // Function to find the sum of all// integers numbers in range [L, R]ll sumInRange(long L, long R){ ll Sum = ((R - L + 1) / 2) * (2 * L + (R - L)); return Sum;} // Function to find sum of all integers// that lie in any of the given rangesll calcSum(vector<pair<long, long> > data, int n){ // Sort intervals in increasing order // according to their first element sort(data.begin(), data.end()); // Merging the overlaping intervals int i, idx = 0; // Loop to iterate through the array for (i = 1; i < n; i++) { // If current interval overlaps // with the previous intervals if ((data[idx].second >= data[i].first) || (data[i].first == data[idx].second + 1)) { // Merge the previou and the // current interval data[idx].second = max(data[idx].second, data[i].second); } else { idx++; data[idx].second = data[i].second; data[idx].first = data[i].first; } } // Stores the required sum ll Sum = 0; // Loop to calculate the sum of all // the remaining merged intervals for (i = 0; i <= idx; i++) { // Add sum of integers // in current range Sum += sumInRange(data[i].first, data[i].second); } // Return the total Sum return Sum;} // Driver Codeint main(){ vector<pair<long, long> > vec = { { -12, 15 }, { 3, 9 }, { -5, -2 }, { 20, 25 }, { 16, 20 } }; cout << calcSum(vec, vec.size()); return 0;}", "e": 29836, "s": 28090, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the sum of all// integers numbers in range [L, R]static int sumInRange(int L, int R){ int Sum = ((R - L + 1) / 2) * (2 * L + (R - L)); return Sum;} // Function to find sum of all integers// that lie in any of the given rangesstatic int calcSum(int [][]data, int n){ // Sort intervals in increasing order // according to their first element Arrays.sort(data,(a,b)->{ return a[0]-b[0]; }); // Merging the overlaping intervals int i, idx = 0; // Loop to iterate through the array for (i = 1; i < n; i++) { // If current interval overlaps // with the previous intervals if ((data[idx][1] >= data[i][0]) || (data[i][0] == data[idx][1] + 1)) { // Merge the previou and the // current interval data[idx][1] = Math.max(data[idx][1], data[i][1]); } else { idx++; data[idx][1] = data[i][1]; data[idx][0] = data[i][0]; } } // Stores the required sum int Sum = 0; // Loop to calculate the sum of all // the remaining merged intervals for (i = 0; i <= idx; i++) { // Add sum of integers // in current range Sum += sumInRange(data[i][0], data[i][1]); } // Return the total Sum return Sum;} // Driver Codepublic static void main(String[] args){ int [][]vec = { { -12, 15 }, { 3, 9 }, { -5, -2 }, { 20, 25 }, { 16, 20 } }; System.out.print(calcSum(vec, vec.length)); }} // This code is contributed by shikhasingrajput", "e": 31586, "s": 29836, "text": null }, { "code": "# Python 3 program for the above approach # Function to find the sum of all# integers numbers in range [L, R]def sumInRange(L, R): Sum = ((R - L + 1) // 2) * (2 * L + (R - L)) return Sum # Function to find sum of all integers# that lie in any of the given rangesdef calcSum(data, n): # Sort intervals in increasing order # according to their first element data.sort() # Merging the overlaping intervals idx = 0 # Loop to iterate through the array for i in range(1, n): # If current interval overlaps # with the previous intervals if ((data[idx][1] >= data[i][0]) or (data[i][0] == data[idx][1] + 1)): # Merge the previou and the # current interval data[idx][1] = max(data[idx][1], data[i][1]) else: idx += 1 data[idx][1] = data[i][1] data[idx][0] = data[i][0] # Stores the required sum Sum = 0 # Loop to calculate the sum of all # the remaining merged intervals for i in range(idx+1): # Add sum of integers # in current range Sum += sumInRange(data[i][0], data[i][1]) # Return the total Sum return Sum # Driver Codeif __name__ == \"__main__\": vec = [[-12, 15], [3, 9], [-5, -2], [20, 25], [16, 20]] print(calcSum(vec, len(vec))) # This code is contributed by ukasp.", "e": 33080, "s": 31586, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the sum of all // integers numbers in range [L, R] function sumInRange(L, R) { let Sum = ((R - L + 1) / 2) * (2 * L + (R - L)); return Sum; } // Function to find sum of all integers // that lie in any of the given ranges function calcSum(data, n) { // Sort intervals in increasing order // according to their first element data.sort(function (a, b) { return a.first - b.first }) // Merging the overlaping intervals let i, idx = 0; // Loop to iterate through the array for (i = 1; i < n; i++) { // If current interval overlaps // with the previous intervals if ((data[idx].second >= data[i].first) || (data[i].first == data[idx].second + 1)) { // Merge the previou and the // current interval data[idx].second = Math.max(data[idx].second, data[i].second); } else { idx++; data[idx].second = data[i].second; data[idx].first = data[i].first; } } // Stores the required sum let Sum = 0; // Loop to calculate the sum of all // the remaining merged intervals for (i = 0; i <= idx; i++) { // Add sum of integers // in current range Sum += sumInRange(data[i].first, data[i].second); } // Return the total Sum return Sum; } // Driver Code let vec = [{ first: -12, second: 15 }, { first: 3, second: 9 }, { first: -5, second: -2 }, { first: 20, second: 25 }, { first: 16, second: 20 }]; document.write(calcSum(vec, vec.length)); // This code is contributed by Potta Lokesh </script>", "e": 35221, "s": 33080, "text": null }, { "code": null, "e": 35228, "s": 35224, "text": "247" }, { "code": null, "e": 35279, "s": 35230, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(1)" }, { "code": null, "e": 35295, "s": 35281, "text": "lokeshpotta20" }, { "code": null, "e": 35312, "s": 35295, "text": "shikhasingrajput" }, { "code": null, "e": 35318, "s": 35312, "text": "ukasp" }, { "code": null, "e": 35338, "s": 35318, "text": "array-range-queries" }, { "code": null, "e": 35345, "s": 35338, "text": "Greedy" }, { "code": null, "e": 35358, "s": 35345, "text": "Mathematical" }, { "code": null, "e": 35365, "s": 35358, "text": "Greedy" }, { "code": null, "e": 35378, "s": 35365, "text": "Mathematical" }, { "code": null, "e": 35476, "s": 35378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35511, "s": 35476, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 35563, "s": 35511, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 35616, "s": 35563, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 35667, "s": 35616, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 35697, "s": 35667, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 35727, "s": 35697, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35742, "s": 35727, "text": "C++ Data Types" }, { "code": null, "e": 35785, "s": 35742, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 35809, "s": 35785, "text": "Merge two sorted arrays" } ]
Python - Custom Split Comma Separated Words - GeeksforGeeks
20 Aug, 2020 While working with Python, we can have problem in which we need to perform the task of splitting the words of string on spaces. But sometimes, we can have comma separated words, which have comma’s joined to words and require to split them separately. Lets discuss certain ways in which this task can be performed.Method #1 : Using replace() Using replace() is one way to solve this problem. In this, we just separate the joined comma from string to spaced so that they can be splitted along with other words correctly. Python3 # Python3 code to demonstrate working of# Custom Split Comma Separated Words# Using replace() # initializing stringtest_str = 'geeksforgeeks, is, best, for, geeks' # printing original stringprint("The original string is : " + str(test_str)) # Distance between occurrences# Using replace()res = test_str.replace(", ", " , ").split() # printing resultprint("The strings after performing splits : " + str(res)) The original string is : geeksforgeeks, is, best, for, geeks The strings after performing splits : [‘geeksforgeeks’, ‘, ‘, ‘is’, ‘, ‘, ‘best’, ‘, ‘, ‘for’, ‘, ‘, ‘geeks’] Method #2 : Using re.findall() This problem can also be used using regex. In this, we find the occurrences of non space word and perform a split on that basis. Python3 # Python3 code to demonstrate working of# Custom Split Comma Separated Words# Using re.findall()import re # initializing stringtest_str = 'geeksforgeeks, is, best, for, geeks' # printing original stringprint("The original string is : " + str(test_str)) # Distance between occurrences# Using re.findall()res = re.findall(r'\w+|\S', test_str) # printing resultprint("The strings after performing splits : " + str(res)) The original string is : geeksforgeeks, is, best, for, geeks The strings after performing splits : [‘geeksforgeeks’, ‘, ‘, ‘is’, ‘, ‘, ‘best’, ‘, ‘, ‘for’, ‘, ‘, ‘geeks’] nidhi_biet tarangagarwal Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n20 Aug, 2020" }, { "code": null, "e": 24812, "s": 24292, "text": "While working with Python, we can have problem in which we need to perform the task of splitting the words of string on spaces. But sometimes, we can have comma separated words, which have comma’s joined to words and require to split them separately. Lets discuss certain ways in which this task can be performed.Method #1 : Using replace() Using replace() is one way to solve this problem. In this, we just separate the joined comma from string to spaced so that they can be splitted along with other words correctly. " }, { "code": null, "e": 24820, "s": 24812, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Custom Split Comma Separated Words# Using replace() # initializing stringtest_str = 'geeksforgeeks, is, best, for, geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Distance between occurrences# Using replace()res = test_str.replace(\", \", \" , \").split() # printing resultprint(\"The strings after performing splits : \" + str(res))", "e": 25228, "s": 24820, "text": null }, { "code": null, "e": 25400, "s": 25228, "text": "The original string is : geeksforgeeks, is, best, for, geeks The strings after performing splits : [‘geeksforgeeks’, ‘, ‘, ‘is’, ‘, ‘, ‘best’, ‘, ‘, ‘for’, ‘, ‘, ‘geeks’] " }, { "code": null, "e": 25564, "s": 25402, "text": " Method #2 : Using re.findall() This problem can also be used using regex. In this, we find the occurrences of non space word and perform a split on that basis. " }, { "code": null, "e": 25572, "s": 25564, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Custom Split Comma Separated Words# Using re.findall()import re # initializing stringtest_str = 'geeksforgeeks, is, best, for, geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Distance between occurrences# Using re.findall()res = re.findall(r'\\w+|\\S', test_str) # printing resultprint(\"The strings after performing splits : \" + str(res))", "e": 25989, "s": 25572, "text": null }, { "code": null, "e": 26161, "s": 25989, "text": "The original string is : geeksforgeeks, is, best, for, geeks The strings after performing splits : [‘geeksforgeeks’, ‘, ‘, ‘is’, ‘, ‘, ‘best’, ‘, ‘, ‘for’, ‘, ‘, ‘geeks’] " }, { "code": null, "e": 26174, "s": 26163, "text": "nidhi_biet" }, { "code": null, "e": 26188, "s": 26174, "text": "tarangagarwal" }, { "code": null, "e": 26211, "s": 26188, "text": "Python string-programs" }, { "code": null, "e": 26218, "s": 26211, "text": "Python" }, { "code": null, "e": 26234, "s": 26218, "text": "Python Programs" }, { "code": null, "e": 26332, "s": 26234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26364, "s": 26332, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26406, "s": 26364, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26462, "s": 26406, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26504, "s": 26462, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26535, "s": 26504, "text": "Python | os.path.join() method" }, { "code": null, "e": 26557, "s": 26535, "text": "Defaultdict in Python" }, { "code": null, "e": 26603, "s": 26557, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26642, "s": 26603, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26680, "s": 26642, "text": "Python | Convert a list to dictionary" } ]
Apache Kafka: Docker Container and examples in Python | Towards Data Science
Apache Kafka is a stream-processing software platform originally developed by LinkedIn, open sourced in early 2011 and currently developed by the Apache Software Foundation. It is written in Scala and Java. Kafka is a distributed system that consists of servers and clients. Some servers are called brokers and they form the storage layer. Other servers run Kafka Connect to import and export data as event streams to integrate Kafka with your existing system continuously. On the other hand, clients allow you to create applications that read, write and process streams of events. A client could be a producer or a consumer. A producer writes (produces) events to Kafka while a consumer read and process (consumes) events from Kafka. Servers and clients communicate via a high-performance TCP network protocol and are fully decoupled and agnostic of each other. But what is an event? In Kafka, an event is an object that has a key, a value and a timestamp. Optionally, it could have other metadata headers. You can think an event as a record or a message. One or more events are organized in topics: producers can write messages/events on different topics and consumers can choose to read and process events of one or more topics. In Kafka, you can configure how long events of a topic should be retained, therefore, they can be read whenever needed and are not deleted after consumption. A consumer cosumes the stream of events of a topic at its own pace and can commit its position (called offset). When we commit the offset we set a pointer to the last record that the consumer has consumed. From the servers side, topics are partitioned and replicated. A topic is partitioned for scalability reason. Its events are spread over different Kafka brokers. This allows clients to read/write from/to many brokers at the same time. For availability and fault-tolerance every topic can also be replicated. It means that multiple brokers in different datacenters could have a copy of the same data. For a detailed explanation on how Kafka works, check its official website. Enough introduction! Let’s see how to install Kafka in order to test our sample Python scripts! As data scientists, we usually find Kafka already installed, configured and ready to be used. For the sake of completeness, in this tutorial, let’s see how to install an instance of Kafka for testing purpose. To this purpose, we are going to use Docker Compose and Git. Please, install them on your system if they are not installed. In your working directory, open a terminal and clone the GitHub repository of the docker image for Apache Kafka. Then change the current directory in the repository folder. git clone https://github.com/wurstmeister/kafka-docker.git cd kafka-docker/ Inside kafka-docker, create a text file named docker-compose-expose.yml with the following content (you can use your favourite text editor): version: '2'services: zookeeper: image: wurstmeister/zookeeper:3.4.6 ports: - "2181:2181" kafka: image: wurstmeister/kafka ports: - "9092:9092" expose: - "9093" environment: KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_CREATE_TOPICS: "topic_test:1:1" volumes: - /var/run/docker.sock:/var/run/docker.sock Now, you are ready to start the Kafka cluster with: docker-compose -f docker-compose-expose.yml up If everything is ok, you should see logs from zookeeper and kafka. In case you want to stop it, just run docker-compose stop in a separate terminal session inside kafka-docker folder. For a complete guide on Kafka docker’s connectivity, check it’s wiki. In order to create our first producer/consumer for Kafka in Python, we need to install the Python client. pip install kafka-python Then, create a Python file called producer.py with the code below. from time import sleepfrom json import dumpsfrom kafka import KafkaProducerproducer = KafkaProducer( bootstrap_servers=['localhost:9092'], value_serializer=lambda x: dumps(x).encode('utf-8'))for j in range(9999): print("Iteration", j) data = {'counter': j} producer.send('topic_test', value=data) sleep(0.5) In the code block above: we have created a KafkaProducer object that connects of our local instance of Kafka; we have defined a way to serialize the data we want to send by trasforming it into a json string and then encoding it to UTF-8; we send an event every 0.5 seconds with topic named “topic_test” and the counter of the iteration as data. Instead of the couter, you can send anything. Now we are ready to start the producer: python producer.py The script should print the number of iteration every half second. [...]Iteration 2219Iteration 2220Iteration 2221Iteration 2222[...] Let’s leave the producer terminal session running and define our consumer in a separate Python file named consumer.py with the following lines of code. from kafka import KafkaConsumerfrom json import loadsfrom time import sleepconsumer = KafkaConsumer( 'topic_test', bootstrap_servers=['localhost:9092'], auto_offset_reset='earliest', enable_auto_commit=True, group_id='my-group-id', value_deserializer=lambda x: loads(x.decode('utf-8')))for event in consumer: event_data = event.value # Do whatever you want print(event_data) sleep(2) In the script above we are defining a KafkaConsumer that contacts the server “localhost:9092 ” and is subscribed to the topic “topic_test”. Since in the producer script the message is jsonfied and encoded, here we decode it by using a lambda function in value_deserializer. In addition, auto_offset_reset is a parameter that sets the policy for resetting offsets on OffsetOutOfRange errors; if we set “earliest” then it will move to the oldest available message, if “latest” is set then it will move to the most recent; enable_auto_commit is a boolean parameter that states whether the offset will be periodically committed in the background; group_id is the name of the consumer group to join. In the loop we print the content of the event consumed every 2 seconds. Instead of printing, we can perfom any task like writing it to a database or performing some real time analysis. At this point, if we run python consumer.py we should receive as output something like: {'counter': 0}{'counter': 1}{'counter': 2}{'counter': 3}{'counter': 4}{'counter': 5}{'counter': 6}[...] The complete documentation of parameters of Python producer/consumer classes can be found here. Now you are ready to use Kafka in Python! https://kafka.apache.org/ https://github.com/wurstmeister/kafka-docker https://kafka-python.readthedocs.io/en/master/index.html https://medium.com/big-data-engineering/hello-kafka-world-the-complete-guide-to-kafka-with-docker-and-python-f788e2588cfc https://towardsdatascience.com/kafka-python-explained-in-10-lines-of-code-800e3e07dad1 Contacts: LinkedIn | Twitter
[ { "code": null, "e": 254, "s": 47, "text": "Apache Kafka is a stream-processing software platform originally developed by LinkedIn, open sourced in early 2011 and currently developed by the Apache Software Foundation. It is written in Scala and Java." }, { "code": null, "e": 322, "s": 254, "text": "Kafka is a distributed system that consists of servers and clients." }, { "code": null, "e": 521, "s": 322, "text": "Some servers are called brokers and they form the storage layer. Other servers run Kafka Connect to import and export data as event streams to integrate Kafka with your existing system continuously." }, { "code": null, "e": 782, "s": 521, "text": "On the other hand, clients allow you to create applications that read, write and process streams of events. A client could be a producer or a consumer. A producer writes (produces) events to Kafka while a consumer read and process (consumes) events from Kafka." }, { "code": null, "e": 910, "s": 782, "text": "Servers and clients communicate via a high-performance TCP network protocol and are fully decoupled and agnostic of each other." }, { "code": null, "e": 1104, "s": 910, "text": "But what is an event? In Kafka, an event is an object that has a key, a value and a timestamp. Optionally, it could have other metadata headers. You can think an event as a record or a message." }, { "code": null, "e": 1437, "s": 1104, "text": "One or more events are organized in topics: producers can write messages/events on different topics and consumers can choose to read and process events of one or more topics. In Kafka, you can configure how long events of a topic should be retained, therefore, they can be read whenever needed and are not deleted after consumption." }, { "code": null, "e": 1643, "s": 1437, "text": "A consumer cosumes the stream of events of a topic at its own pace and can commit its position (called offset). When we commit the offset we set a pointer to the last record that the consumer has consumed." }, { "code": null, "e": 1705, "s": 1643, "text": "From the servers side, topics are partitioned and replicated." }, { "code": null, "e": 1877, "s": 1705, "text": "A topic is partitioned for scalability reason. Its events are spread over different Kafka brokers. This allows clients to read/write from/to many brokers at the same time." }, { "code": null, "e": 2042, "s": 1877, "text": "For availability and fault-tolerance every topic can also be replicated. It means that multiple brokers in different datacenters could have a copy of the same data." }, { "code": null, "e": 2117, "s": 2042, "text": "For a detailed explanation on how Kafka works, check its official website." }, { "code": null, "e": 2213, "s": 2117, "text": "Enough introduction! Let’s see how to install Kafka in order to test our sample Python scripts!" }, { "code": null, "e": 2546, "s": 2213, "text": "As data scientists, we usually find Kafka already installed, configured and ready to be used. For the sake of completeness, in this tutorial, let’s see how to install an instance of Kafka for testing purpose. To this purpose, we are going to use Docker Compose and Git. Please, install them on your system if they are not installed." }, { "code": null, "e": 2719, "s": 2546, "text": "In your working directory, open a terminal and clone the GitHub repository of the docker image for Apache Kafka. Then change the current directory in the repository folder." }, { "code": null, "e": 2795, "s": 2719, "text": "git clone https://github.com/wurstmeister/kafka-docker.git cd kafka-docker/" }, { "code": null, "e": 2936, "s": 2795, "text": "Inside kafka-docker, create a text file named docker-compose-expose.yml with the following content (you can use your favourite text editor):" }, { "code": null, "e": 3559, "s": 2936, "text": "version: '2'services: zookeeper: image: wurstmeister/zookeeper:3.4.6 ports: - \"2181:2181\" kafka: image: wurstmeister/kafka ports: - \"9092:9092\" expose: - \"9093\" environment: KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_CREATE_TOPICS: \"topic_test:1:1\" volumes: - /var/run/docker.sock:/var/run/docker.sock" }, { "code": null, "e": 3611, "s": 3559, "text": "Now, you are ready to start the Kafka cluster with:" }, { "code": null, "e": 3658, "s": 3611, "text": "docker-compose -f docker-compose-expose.yml up" }, { "code": null, "e": 3725, "s": 3658, "text": "If everything is ok, you should see logs from zookeeper and kafka." }, { "code": null, "e": 3763, "s": 3725, "text": "In case you want to stop it, just run" }, { "code": null, "e": 3783, "s": 3763, "text": "docker-compose stop" }, { "code": null, "e": 3842, "s": 3783, "text": "in a separate terminal session inside kafka-docker folder." }, { "code": null, "e": 3912, "s": 3842, "text": "For a complete guide on Kafka docker’s connectivity, check it’s wiki." }, { "code": null, "e": 4018, "s": 3912, "text": "In order to create our first producer/consumer for Kafka in Python, we need to install the Python client." }, { "code": null, "e": 4043, "s": 4018, "text": "pip install kafka-python" }, { "code": null, "e": 4110, "s": 4043, "text": "Then, create a Python file called producer.py with the code below." }, { "code": null, "e": 4436, "s": 4110, "text": "from time import sleepfrom json import dumpsfrom kafka import KafkaProducerproducer = KafkaProducer( bootstrap_servers=['localhost:9092'], value_serializer=lambda x: dumps(x).encode('utf-8'))for j in range(9999): print(\"Iteration\", j) data = {'counter': j} producer.send('topic_test', value=data) sleep(0.5)" }, { "code": null, "e": 4461, "s": 4436, "text": "In the code block above:" }, { "code": null, "e": 4546, "s": 4461, "text": "we have created a KafkaProducer object that connects of our local instance of Kafka;" }, { "code": null, "e": 4674, "s": 4546, "text": "we have defined a way to serialize the data we want to send by trasforming it into a json string and then encoding it to UTF-8;" }, { "code": null, "e": 4827, "s": 4674, "text": "we send an event every 0.5 seconds with topic named “topic_test” and the counter of the iteration as data. Instead of the couter, you can send anything." }, { "code": null, "e": 4867, "s": 4827, "text": "Now we are ready to start the producer:" }, { "code": null, "e": 4886, "s": 4867, "text": "python producer.py" }, { "code": null, "e": 4953, "s": 4886, "text": "The script should print the number of iteration every half second." }, { "code": null, "e": 5020, "s": 4953, "text": "[...]Iteration 2219Iteration 2220Iteration 2221Iteration 2222[...]" }, { "code": null, "e": 5172, "s": 5020, "text": "Let’s leave the producer terminal session running and define our consumer in a separate Python file named consumer.py with the following lines of code." }, { "code": null, "e": 5586, "s": 5172, "text": "from kafka import KafkaConsumerfrom json import loadsfrom time import sleepconsumer = KafkaConsumer( 'topic_test', bootstrap_servers=['localhost:9092'], auto_offset_reset='earliest', enable_auto_commit=True, group_id='my-group-id', value_deserializer=lambda x: loads(x.decode('utf-8')))for event in consumer: event_data = event.value # Do whatever you want print(event_data) sleep(2)" }, { "code": null, "e": 5873, "s": 5586, "text": "In the script above we are defining a KafkaConsumer that contacts the server “localhost:9092 ” and is subscribed to the topic “topic_test”. Since in the producer script the message is jsonfied and encoded, here we decode it by using a lambda function in value_deserializer. In addition," }, { "code": null, "e": 6106, "s": 5873, "text": "auto_offset_reset is a parameter that sets the policy for resetting offsets on OffsetOutOfRange errors; if we set “earliest” then it will move to the oldest available message, if “latest” is set then it will move to the most recent;" }, { "code": null, "e": 6229, "s": 6106, "text": "enable_auto_commit is a boolean parameter that states whether the offset will be periodically committed in the background;" }, { "code": null, "e": 6281, "s": 6229, "text": "group_id is the name of the consumer group to join." }, { "code": null, "e": 6466, "s": 6281, "text": "In the loop we print the content of the event consumed every 2 seconds. Instead of printing, we can perfom any task like writing it to a database or performing some real time analysis." }, { "code": null, "e": 6491, "s": 6466, "text": "At this point, if we run" }, { "code": null, "e": 6510, "s": 6491, "text": "python consumer.py" }, { "code": null, "e": 6554, "s": 6510, "text": "we should receive as output something like:" }, { "code": null, "e": 6658, "s": 6554, "text": "{'counter': 0}{'counter': 1}{'counter': 2}{'counter': 3}{'counter': 4}{'counter': 5}{'counter': 6}[...]" }, { "code": null, "e": 6754, "s": 6658, "text": "The complete documentation of parameters of Python producer/consumer classes can be found here." }, { "code": null, "e": 6796, "s": 6754, "text": "Now you are ready to use Kafka in Python!" }, { "code": null, "e": 6822, "s": 6796, "text": "https://kafka.apache.org/" }, { "code": null, "e": 6867, "s": 6822, "text": "https://github.com/wurstmeister/kafka-docker" }, { "code": null, "e": 6924, "s": 6867, "text": "https://kafka-python.readthedocs.io/en/master/index.html" }, { "code": null, "e": 7046, "s": 6924, "text": "https://medium.com/big-data-engineering/hello-kafka-world-the-complete-guide-to-kafka-with-docker-and-python-f788e2588cfc" }, { "code": null, "e": 7133, "s": 7046, "text": "https://towardsdatascience.com/kafka-python-explained-in-10-lines-of-code-800e3e07dad1" } ]
Get the first occurrence of a substring within a string in Arduino
The indexOf() function within Arduino scans a string from the beginning, and returns the first index of the specified substring within the string. The syntax is − Syntax myString.indexOf(substr) where substr is the substring to search for. It can be of type character or string. Optionally, you can provide a different starting point to begin the search from, in which case, the syntax is − Syntax myString.indexOf(substr, from) where from is the index from where the search should start. This function returns the index of the first occurrence of the substring within the string, or -1, if no match is found. void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); String s1 = "Mississippi"; String substr1 = "is"; String substr2 = "os"; Serial.println(s1.indexOf(substr1)); Serial.println(s1.indexOf(substr2)); Serial.println(s1.indexOf(substr1, 3)); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is shown below − As you can see, in the first case, the index 1 was printed (counting starts from 0). In the second case, since no match was found, -1 was printed. In the third case, we told Arduino to start searching from index 3. Therefore, the next match was found at index 4, and that was printed.
[ { "code": null, "e": 1225, "s": 1062, "text": "The indexOf() function within Arduino scans a string from the beginning, and returns the first index of the specified substring within the string. The syntax is −" }, { "code": null, "e": 1232, "s": 1225, "text": "Syntax" }, { "code": null, "e": 1257, "s": 1232, "text": "myString.indexOf(substr)" }, { "code": null, "e": 1341, "s": 1257, "text": "where substr is the substring to search for. It can be of type character or string." }, { "code": null, "e": 1453, "s": 1341, "text": "Optionally, you can provide a different starting point to begin the search from, in which case, the syntax is −" }, { "code": null, "e": 1460, "s": 1453, "text": "Syntax" }, { "code": null, "e": 1491, "s": 1460, "text": "myString.indexOf(substr, from)" }, { "code": null, "e": 1672, "s": 1491, "text": "where from is the index from where the search should start. This function returns the index of the first occurrence of the substring within the string, or -1, if no match is found." }, { "code": null, "e": 2049, "s": 1672, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n String s1 = \"Mississippi\";\n String substr1 = \"is\";\n String substr2 = \"os\";\n Serial.println(s1.indexOf(substr1));\n Serial.println(s1.indexOf(substr2));\n Serial.println(s1.indexOf(substr1, 3));\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2092, "s": 2049, "text": "The Serial Monitor output is shown below −" }, { "code": null, "e": 2377, "s": 2092, "text": "As you can see, in the first case, the index 1 was printed (counting starts from 0). In the second case, since no match was found, -1 was printed. In the third case, we told Arduino to start searching from index 3. Therefore, the next match was found at index 4, and that was printed." } ]
A/B Testing Design & Execution. How to conduct A/B tests... | by Barış Karaman | Towards Data Science
This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning. I will cover all the topics in the following nine articles: 1- Know Your Metrics 2- Customer Segmentation 3- Customer Lifetime Value Prediction 4- Churn Prediction 5- Predicting Next Purchase Day 6- Predicting Sales 7- Market Response Models 8- Uplift Modeling 9- A/B Testing Design and Execution Articles have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it: Sometimes you gotta run before you can walk — Tony Stark As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only. Alright, let’s start. As a (Data-Driven) Growth Hacker, one of the main responsibilities is to experiment new ideas and sustain continuous learning. Experimentation is a great way to test your machine learning models, new actions & improve existing ones. Let’s give an example: You have a churn model that works with 95% accuracy. By calling the customers who are likely to churn and giving an attractive offer, you are assuming 10% of them will retain and bring monthly $20 per each. That’s a lot of assumptions. Breaking it down: The model’s accuracy is 95%. Is it really? You have trained your model based on last month’s data. The next month, there will be new users, new product features, marketing & brand activities, seasonality and so on. Historical accuracy and real accuracy rarely match in this kind of cases. You can’t come up with a conclusion without a test. By looking at the previous campaigns’ results, you are assuming a 10% conversion. It doesn’t guarantee that your new action will have 10% conversion due to the factors above. Moreover, since it is a new group, their reaction is partly unpredictable. Finally, if those customers bring $20 monthly today, that doesn’t mean they will bring the same after your new action. To see what’s going to happen, we need to conduct an A/B test. In this article, we are going to focus on how we can execute our test programmatically and report the statistics behind it. Just before jumping into coding, there are two important points you need to think while designing and A/B test. 1- What is your hypothesis? Going forward with the example above, our hypothesis is, test group will have more retention: Group A → Offer → Higher Retention Group B → No offer → Lower Retention This also helps us to test model accuracy as well. If group B’s retention rate is 50%, it clearly shows that our model is not working. The same applies to measure revenue coming from those users too. 2- What is your success metric? In this case, we are going to check the retention rate of both groups. For this coding example, we are going to create our own dataset by using numpy library and evaluate the result of an A/B test. Let’s start with importing the necessary libraries: Now we are going to create our own dataset. The dataset will contain the columns below: customer_id: the unique identifier of the customer segment: customer’s segment; high-value or low-value group: indicates whether the customer is in the test or control group purchase_count: # of purchases completed by the customer The first three will be quite easy: df_hv = pd.DataFrame()df_hv['customer_id'] = np.array([count for count in range(20000)])df_hv['segment'] = np.array(['high-value' for _ in range(20000)])df_hv['group'] = 'control'df_hv.loc[df_hv.index<10000,'group'] = 'test' Ideally, purchase count should be a Poisson distribution. There will be customers with no purchase and we will have less customers with high purchase counts. Let’s use numpy.random.poisson() for doing that and assign different distributions to test and control group: df_hv.loc[df_hv.group == 'test', 'purchase_count'] = np.random.poisson(0.6, 10000)df_hv.loc[df_hv.group == 'control', 'purchase_count'] = np.random.poisson(0.5, 10000) Let’s have a look at our dataset: Awesome. We have everything to evaluate our A/B test. Assume we applied an offer to 50% of high-value users and observed their purchases in a given period. Best way to visualize it to check the densities: Output: The results are looking really good. The density of the test group’s purchase is better starting from 1. But how we can certainly say this experiment is successful and the difference didn’t happen due to other factors? To answer this question, we need to check if the uptick in the test group is statistically significant. scipy library allows us to programmatically check this: from scipy import stats test_result = stats.ttest_ind(test_results, control_results)print(test_result) Output: ttest_ind() method returns two output: t-statistic: represents the difference between averages of test and control group in units of standard error. Higher t-statistic value means bigger difference and supports our hypothesis. p-value: measures the probability of the null hypothesis to be true. Ops, what is null hypothesis? If null hypothesis is true, it means there is no significant difference between your test and control group. So the lower p-value means the better. As the industry standard, we accept that p-value<5% makes the result statistically significant (but it depends on your business logic, there are cases that people use 10% or even 1%). To understand if our test is statistically significant or not, let’s build a function and apply to our dataset: def eval_test(test_results,control_results): test_result = stats.ttest_ind(test_results, control_results) if test_result[1] < 0.05: print('result is significant') else: print('result is not significant') If we apply this to our dataset: Looks great but unfortunately, it is not that simple. If you select a biased test group, your results will be statistically significant by default. As an example, if we allocate more high-value customer to test group and more low-value customers to control group, then our experiment becomes a failure from the beginning. That’s why selecting the group is the key to a healthy A/B test. The most common approach to select test & control groups is random sampling. Let’s see how we can do it programmatically. We are going to start with creating the dataset first. In this version, it will have 20k high-value and 80k low-value customers: #create hv segmentdf_hv = pd.DataFrame()df_hv['customer_id'] = np.array([count for count in range(20000)])df_hv['segment'] = np.array(['high-value' for _ in range(20000)])df_hv['prev_purchase_count'] = np.random.poisson(0.9, 20000)df_lv = pd.DataFrame()df_lv['customer_id'] = np.array([count for count in range(20000,100000)])df_lv['segment'] = np.array(['low-value' for _ in range(80000)])df_lv['prev_purchase_count'] = np.random.poisson(0.3, 80000)df_customers = pd.concat([df_hv,df_lv],axis=0) By using pandas’ sample() function, we can select our test groups. Assuming we will have 90% test and 10% control group: df_test = df_customers.sample(frac=0.9)df_control = df_customers[~df_customers.customer_id.isin(df_test.customer_id)] In this example, we extracted 90% of the whole group and labeled it as test. But there is a small problem that can ruin our experiment. If you have significantly different multiple groups in your dataset (in this case, high-value & low-value), better to do random sampling separately. Otherwise, we can’t guarantee that the ratio of high-value to low-value is the same for test and control group. To ensure creating test and control groups correctly, we need to apply the following code: df_test_hv = df_customers[df_customers.segment == 'high-value'].sample(frac=0.9)df_test_lv = df_customers[df_customers.segment == 'low-value'].sample(frac=0.9)df_test = pd.concat([df_test_hv,df_test_lv],axis=0)df_control = df_customers[~df_customers.customer_id.isin(df_test.customer_id)] This makes the allocation correct for both: We have explored how to do the t-test and selecting test and control groups. But what if we are doing A/B/C test or A/B test on multiple groups like above. It’s time to introduce ANOVA tests. Let’s assume we are testing 2+ variants on same groups (i.e 2 different offers and no-offer to low-value high-value customers). Then we need to apply one-way ANOVA for evaluating our experiment. Let’s start from creating our dataset: Output: To evaluate the result, we will apply the function below: def one_anova_test(a_stats,b_stats,c_stats): test_result = stats.f_oneway(a_stats, b_stats, c_stats) if test_result[1] < 0.05: print('result is significant') else: print('result is not significant') The logic is similar to t_test. If p-value is lower than 5%, our test become significant: Let’s check out who it will look like if there was no difference between the groups: df_hv.loc[df_hv.group == 'A', 'purchase_count'] = np.random.poisson(0.5, 10000)df_hv.loc[df_hv.group == 'B', 'purchase_count'] = np.random.poisson(0.5, 10000)df_hv.loc[df_hv.group == 'C', 'purchase_count'] = np.random.poisson(0.5, 10000)a_stats = df_hv[df_hv.group=='A'].purchase_countb_stats = df_hv[df_hv.group=='B'].purchase_countc_stats = df_hv[df_hv.group=='C'].purchase_counthist_data = [a_stats, b_stats, c_stats]group_labels = ['A', 'B','C']# Create distplot with curve_type set to 'normal'fig = ff.create_distplot(hist_data, group_labels, bin_size=.5, curve_type='normal',show_rug=False)fig.layout = go.Layout( title='Test vs Control Stats', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )# Plot!pyoff.iplot(fig) Output & the test result: If we want to see if there is difference between A and B or C, we can apply the t_test that I explained above. Let’s say we are doing the same test on both high-value and low-value customers. In this case, we need to apply two-way ANOVA. We are going to create our dataset again and build our evaluation method: Two-way ANOVA requires building a model like below: import statsmodels.formula.api as smf from statsmodels.stats.anova import anova_lmmodel = smf.ols(formula='purchase_count ~ segment + group ', data=df_customers).fit()aov_table = anova_lm(model, typ=2) By using segment & group, the model trying to reach purchase_count. aov_table above helps us to see if our experiment is successful: The last column represents the result and showing us the difference is significant. If it wasn’t, it would look like below: This shows, segment (being high-value or low-value) significantly affects the purchase count but group doesn’t since it is almost 66%, way higher than 5%. Now we know how to select our groups and evaluate the results. But there is one more missing part. To reach statistical significance, our sample size should be enough. Let’s see how we can calculate it. To calculate the required sample size, first we need to understand two concepts: Effect size: this represents the magnitude of difference between averages of test and control group. It is the variance in averages between test and control groups divided by the standard deviation of the control. Power: this refers to the probability of finding a statistical significance in your test. To calculate the sample size, 0.8 is the common value that is being used. Let’s build our dataset and see the sample size calculation in an example: from statsmodels.stats import powerss_analysis = power.TTestIndPower()#create hv segmentdf_hv = pd.DataFrame()df_hv['customer_id'] = np.array([count for count in range(20000)])df_hv['segment'] = np.array(['high-value' for _ in range(20000)])df_hv['prev_purchase_count'] = np.random.poisson(0.7, 20000)purchase_mean = df_hv.prev_purchase_count.mean()purchase_std = df_hv.prev_purchase_count.std() In this example, the average of purchases (purchase_mean) is 0.7 and the standard deviation (purchase_std) is 0.84. Let’s say we want to increase the purchase_mean to 0.75 in this experiment. We can calculate the effect size like below: effect_size = (0.75 - purchase_mean)/purchase_std After that, the sample size calculation is quite simple: alpha = 0.05power = 0.8ratio = 1ss_result = ss_analysis.solve_power(effect_size=effect_size, power=power,alpha=alpha, ratio=ratio , nobs1=None) print(ss_result) Alpha is the threshold for statistical significance (5%) and our ratio of test and control sample sizes are 1 (equal). As a result, our required sample size is (output of ss_result) 4868. Let’s build a function to use this everywhere we want: def calculate_sample_size(c_data, column_name, target,ratio): value_mean = c_data[column_name].mean() value_std = c_data[column_name].std() value_target = value_mean * target effect_size = (value_target - value_mean)/value_std power = 0.8 alpha = 0.05 ss_result = ss_analysis.solve_power(effect_size=effect_size, power=power,alpha=alpha, ratio=ratio , nobs1=None) print(int(ss_result)) To this function, we need to provide our dataset, the column_name that represents the value (purchase_count in our case), our target mean (0.75 was our target in the previous example) and the ratio. In the dataset above, let’s assume we want to increase purchase count mean by 5% and we will keep the sizes of both groups the same: calculate_sample_size(df_hv, 'prev_purchase_count', 1.05,1) Then the result becomes 8961. You can find the Jupyter Notebook for this article here. This is the end of the Data Driven Growth series. Hope you enjoyed the articles and started to apply the practices here. Those will be converted to an e-book and supported by a comprehensive video series. Stay tuned! Happy hacking! To discuss growth marketing & data science, go ahead and book a free session with me here.
[ { "code": null, "e": 423, "s": 172, "text": "This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning." }, { "code": null, "e": 483, "s": 423, "text": "I will cover all the topics in the following nine articles:" }, { "code": null, "e": 504, "s": 483, "text": "1- Know Your Metrics" }, { "code": null, "e": 529, "s": 504, "text": "2- Customer Segmentation" }, { "code": null, "e": 567, "s": 529, "text": "3- Customer Lifetime Value Prediction" }, { "code": null, "e": 587, "s": 567, "text": "4- Churn Prediction" }, { "code": null, "e": 619, "s": 587, "text": "5- Predicting Next Purchase Day" }, { "code": null, "e": 639, "s": 619, "text": "6- Predicting Sales" }, { "code": null, "e": 665, "s": 639, "text": "7- Market Response Models" }, { "code": null, "e": 684, "s": 665, "text": "8- Uplift Modeling" }, { "code": null, "e": 720, "s": 684, "text": "9- A/B Testing Design and Execution" }, { "code": null, "e": 1065, "s": 720, "text": "Articles have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:" }, { "code": null, "e": 1122, "s": 1065, "text": "Sometimes you gotta run before you can walk — Tony Stark" }, { "code": null, "e": 1263, "s": 1122, "text": "As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only." }, { "code": null, "e": 1285, "s": 1263, "text": "Alright, let’s start." }, { "code": null, "e": 1541, "s": 1285, "text": "As a (Data-Driven) Growth Hacker, one of the main responsibilities is to experiment new ideas and sustain continuous learning. Experimentation is a great way to test your machine learning models, new actions & improve existing ones. Let’s give an example:" }, { "code": null, "e": 1748, "s": 1541, "text": "You have a churn model that works with 95% accuracy. By calling the customers who are likely to churn and giving an attractive offer, you are assuming 10% of them will retain and bring monthly $20 per each." }, { "code": null, "e": 1795, "s": 1748, "text": "That’s a lot of assumptions. Breaking it down:" }, { "code": null, "e": 2136, "s": 1795, "text": "The model’s accuracy is 95%. Is it really? You have trained your model based on last month’s data. The next month, there will be new users, new product features, marketing & brand activities, seasonality and so on. Historical accuracy and real accuracy rarely match in this kind of cases. You can’t come up with a conclusion without a test." }, { "code": null, "e": 2386, "s": 2136, "text": "By looking at the previous campaigns’ results, you are assuming a 10% conversion. It doesn’t guarantee that your new action will have 10% conversion due to the factors above. Moreover, since it is a new group, their reaction is partly unpredictable." }, { "code": null, "e": 2505, "s": 2386, "text": "Finally, if those customers bring $20 monthly today, that doesn’t mean they will bring the same after your new action." }, { "code": null, "e": 2804, "s": 2505, "text": "To see what’s going to happen, we need to conduct an A/B test. In this article, we are going to focus on how we can execute our test programmatically and report the statistics behind it. Just before jumping into coding, there are two important points you need to think while designing and A/B test." }, { "code": null, "e": 2832, "s": 2804, "text": "1- What is your hypothesis?" }, { "code": null, "e": 2926, "s": 2832, "text": "Going forward with the example above, our hypothesis is, test group will have more retention:" }, { "code": null, "e": 2961, "s": 2926, "text": "Group A → Offer → Higher Retention" }, { "code": null, "e": 2998, "s": 2961, "text": "Group B → No offer → Lower Retention" }, { "code": null, "e": 3198, "s": 2998, "text": "This also helps us to test model accuracy as well. If group B’s retention rate is 50%, it clearly shows that our model is not working. The same applies to measure revenue coming from those users too." }, { "code": null, "e": 3230, "s": 3198, "text": "2- What is your success metric?" }, { "code": null, "e": 3301, "s": 3230, "text": "In this case, we are going to check the retention rate of both groups." }, { "code": null, "e": 3428, "s": 3301, "text": "For this coding example, we are going to create our own dataset by using numpy library and evaluate the result of an A/B test." }, { "code": null, "e": 3480, "s": 3428, "text": "Let’s start with importing the necessary libraries:" }, { "code": null, "e": 3568, "s": 3480, "text": "Now we are going to create our own dataset. The dataset will contain the columns below:" }, { "code": null, "e": 3619, "s": 3568, "text": "customer_id: the unique identifier of the customer" }, { "code": null, "e": 3672, "s": 3619, "text": "segment: customer’s segment; high-value or low-value" }, { "code": null, "e": 3742, "s": 3672, "text": "group: indicates whether the customer is in the test or control group" }, { "code": null, "e": 3799, "s": 3742, "text": "purchase_count: # of purchases completed by the customer" }, { "code": null, "e": 3835, "s": 3799, "text": "The first three will be quite easy:" }, { "code": null, "e": 4060, "s": 3835, "text": "df_hv = pd.DataFrame()df_hv['customer_id'] = np.array([count for count in range(20000)])df_hv['segment'] = np.array(['high-value' for _ in range(20000)])df_hv['group'] = 'control'df_hv.loc[df_hv.index<10000,'group'] = 'test'" }, { "code": null, "e": 4328, "s": 4060, "text": "Ideally, purchase count should be a Poisson distribution. There will be customers with no purchase and we will have less customers with high purchase counts. Let’s use numpy.random.poisson() for doing that and assign different distributions to test and control group:" }, { "code": null, "e": 4496, "s": 4328, "text": "df_hv.loc[df_hv.group == 'test', 'purchase_count'] = np.random.poisson(0.6, 10000)df_hv.loc[df_hv.group == 'control', 'purchase_count'] = np.random.poisson(0.5, 10000)" }, { "code": null, "e": 4530, "s": 4496, "text": "Let’s have a look at our dataset:" }, { "code": null, "e": 4735, "s": 4530, "text": "Awesome. We have everything to evaluate our A/B test. Assume we applied an offer to 50% of high-value users and observed their purchases in a given period. Best way to visualize it to check the densities:" }, { "code": null, "e": 4743, "s": 4735, "text": "Output:" }, { "code": null, "e": 4962, "s": 4743, "text": "The results are looking really good. The density of the test group’s purchase is better starting from 1. But how we can certainly say this experiment is successful and the difference didn’t happen due to other factors?" }, { "code": null, "e": 5122, "s": 4962, "text": "To answer this question, we need to check if the uptick in the test group is statistically significant. scipy library allows us to programmatically check this:" }, { "code": null, "e": 5225, "s": 5122, "text": "from scipy import stats test_result = stats.ttest_ind(test_results, control_results)print(test_result)" }, { "code": null, "e": 5233, "s": 5225, "text": "Output:" }, { "code": null, "e": 5272, "s": 5233, "text": "ttest_ind() method returns two output:" }, { "code": null, "e": 5460, "s": 5272, "text": "t-statistic: represents the difference between averages of test and control group in units of standard error. Higher t-statistic value means bigger difference and supports our hypothesis." }, { "code": null, "e": 5529, "s": 5460, "text": "p-value: measures the probability of the null hypothesis to be true." }, { "code": null, "e": 5559, "s": 5529, "text": "Ops, what is null hypothesis?" }, { "code": null, "e": 5891, "s": 5559, "text": "If null hypothesis is true, it means there is no significant difference between your test and control group. So the lower p-value means the better. As the industry standard, we accept that p-value<5% makes the result statistically significant (but it depends on your business logic, there are cases that people use 10% or even 1%)." }, { "code": null, "e": 6003, "s": 5891, "text": "To understand if our test is statistically significant or not, let’s build a function and apply to our dataset:" }, { "code": null, "e": 6230, "s": 6003, "text": "def eval_test(test_results,control_results): test_result = stats.ttest_ind(test_results, control_results) if test_result[1] < 0.05: print('result is significant') else: print('result is not significant')" }, { "code": null, "e": 6263, "s": 6230, "text": "If we apply this to our dataset:" }, { "code": null, "e": 6650, "s": 6263, "text": "Looks great but unfortunately, it is not that simple. If you select a biased test group, your results will be statistically significant by default. As an example, if we allocate more high-value customer to test group and more low-value customers to control group, then our experiment becomes a failure from the beginning. That’s why selecting the group is the key to a healthy A/B test." }, { "code": null, "e": 6901, "s": 6650, "text": "The most common approach to select test & control groups is random sampling. Let’s see how we can do it programmatically. We are going to start with creating the dataset first. In this version, it will have 20k high-value and 80k low-value customers:" }, { "code": null, "e": 7398, "s": 6901, "text": "#create hv segmentdf_hv = pd.DataFrame()df_hv['customer_id'] = np.array([count for count in range(20000)])df_hv['segment'] = np.array(['high-value' for _ in range(20000)])df_hv['prev_purchase_count'] = np.random.poisson(0.9, 20000)df_lv = pd.DataFrame()df_lv['customer_id'] = np.array([count for count in range(20000,100000)])df_lv['segment'] = np.array(['low-value' for _ in range(80000)])df_lv['prev_purchase_count'] = np.random.poisson(0.3, 80000)df_customers = pd.concat([df_hv,df_lv],axis=0)" }, { "code": null, "e": 7519, "s": 7398, "text": "By using pandas’ sample() function, we can select our test groups. Assuming we will have 90% test and 10% control group:" }, { "code": null, "e": 7637, "s": 7519, "text": "df_test = df_customers.sample(frac=0.9)df_control = df_customers[~df_customers.customer_id.isin(df_test.customer_id)]" }, { "code": null, "e": 8034, "s": 7637, "text": "In this example, we extracted 90% of the whole group and labeled it as test. But there is a small problem that can ruin our experiment. If you have significantly different multiple groups in your dataset (in this case, high-value & low-value), better to do random sampling separately. Otherwise, we can’t guarantee that the ratio of high-value to low-value is the same for test and control group." }, { "code": null, "e": 8125, "s": 8034, "text": "To ensure creating test and control groups correctly, we need to apply the following code:" }, { "code": null, "e": 8414, "s": 8125, "text": "df_test_hv = df_customers[df_customers.segment == 'high-value'].sample(frac=0.9)df_test_lv = df_customers[df_customers.segment == 'low-value'].sample(frac=0.9)df_test = pd.concat([df_test_hv,df_test_lv],axis=0)df_control = df_customers[~df_customers.customer_id.isin(df_test.customer_id)]" }, { "code": null, "e": 8458, "s": 8414, "text": "This makes the allocation correct for both:" }, { "code": null, "e": 8650, "s": 8458, "text": "We have explored how to do the t-test and selecting test and control groups. But what if we are doing A/B/C test or A/B test on multiple groups like above. It’s time to introduce ANOVA tests." }, { "code": null, "e": 8884, "s": 8650, "text": "Let’s assume we are testing 2+ variants on same groups (i.e 2 different offers and no-offer to low-value high-value customers). Then we need to apply one-way ANOVA for evaluating our experiment. Let’s start from creating our dataset:" }, { "code": null, "e": 8892, "s": 8884, "text": "Output:" }, { "code": null, "e": 8950, "s": 8892, "text": "To evaluate the result, we will apply the function below:" }, { "code": null, "e": 9172, "s": 8950, "text": "def one_anova_test(a_stats,b_stats,c_stats): test_result = stats.f_oneway(a_stats, b_stats, c_stats) if test_result[1] < 0.05: print('result is significant') else: print('result is not significant')" }, { "code": null, "e": 9262, "s": 9172, "text": "The logic is similar to t_test. If p-value is lower than 5%, our test become significant:" }, { "code": null, "e": 9347, "s": 9262, "text": "Let’s check out who it will look like if there was no difference between the groups:" }, { "code": null, "e": 10144, "s": 9347, "text": "df_hv.loc[df_hv.group == 'A', 'purchase_count'] = np.random.poisson(0.5, 10000)df_hv.loc[df_hv.group == 'B', 'purchase_count'] = np.random.poisson(0.5, 10000)df_hv.loc[df_hv.group == 'C', 'purchase_count'] = np.random.poisson(0.5, 10000)a_stats = df_hv[df_hv.group=='A'].purchase_countb_stats = df_hv[df_hv.group=='B'].purchase_countc_stats = df_hv[df_hv.group=='C'].purchase_counthist_data = [a_stats, b_stats, c_stats]group_labels = ['A', 'B','C']# Create distplot with curve_type set to 'normal'fig = ff.create_distplot(hist_data, group_labels, bin_size=.5, curve_type='normal',show_rug=False)fig.layout = go.Layout( title='Test vs Control Stats', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )# Plot!pyoff.iplot(fig)" }, { "code": null, "e": 10170, "s": 10144, "text": "Output & the test result:" }, { "code": null, "e": 10281, "s": 10170, "text": "If we want to see if there is difference between A and B or C, we can apply the t_test that I explained above." }, { "code": null, "e": 10482, "s": 10281, "text": "Let’s say we are doing the same test on both high-value and low-value customers. In this case, we need to apply two-way ANOVA. We are going to create our dataset again and build our evaluation method:" }, { "code": null, "e": 10534, "s": 10482, "text": "Two-way ANOVA requires building a model like below:" }, { "code": null, "e": 10736, "s": 10534, "text": "import statsmodels.formula.api as smf from statsmodels.stats.anova import anova_lmmodel = smf.ols(formula='purchase_count ~ segment + group ', data=df_customers).fit()aov_table = anova_lm(model, typ=2)" }, { "code": null, "e": 10869, "s": 10736, "text": "By using segment & group, the model trying to reach purchase_count. aov_table above helps us to see if our experiment is successful:" }, { "code": null, "e": 10993, "s": 10869, "text": "The last column represents the result and showing us the difference is significant. If it wasn’t, it would look like below:" }, { "code": null, "e": 11148, "s": 10993, "text": "This shows, segment (being high-value or low-value) significantly affects the purchase count but group doesn’t since it is almost 66%, way higher than 5%." }, { "code": null, "e": 11351, "s": 11148, "text": "Now we know how to select our groups and evaluate the results. But there is one more missing part. To reach statistical significance, our sample size should be enough. Let’s see how we can calculate it." }, { "code": null, "e": 11432, "s": 11351, "text": "To calculate the required sample size, first we need to understand two concepts:" }, { "code": null, "e": 11646, "s": 11432, "text": "Effect size: this represents the magnitude of difference between averages of test and control group. It is the variance in averages between test and control groups divided by the standard deviation of the control." }, { "code": null, "e": 11810, "s": 11646, "text": "Power: this refers to the probability of finding a statistical significance in your test. To calculate the sample size, 0.8 is the common value that is being used." }, { "code": null, "e": 11885, "s": 11810, "text": "Let’s build our dataset and see the sample size calculation in an example:" }, { "code": null, "e": 12281, "s": 11885, "text": "from statsmodels.stats import powerss_analysis = power.TTestIndPower()#create hv segmentdf_hv = pd.DataFrame()df_hv['customer_id'] = np.array([count for count in range(20000)])df_hv['segment'] = np.array(['high-value' for _ in range(20000)])df_hv['prev_purchase_count'] = np.random.poisson(0.7, 20000)purchase_mean = df_hv.prev_purchase_count.mean()purchase_std = df_hv.prev_purchase_count.std()" }, { "code": null, "e": 12397, "s": 12281, "text": "In this example, the average of purchases (purchase_mean) is 0.7 and the standard deviation (purchase_std) is 0.84." }, { "code": null, "e": 12518, "s": 12397, "text": "Let’s say we want to increase the purchase_mean to 0.75 in this experiment. We can calculate the effect size like below:" }, { "code": null, "e": 12568, "s": 12518, "text": "effect_size = (0.75 - purchase_mean)/purchase_std" }, { "code": null, "e": 12625, "s": 12568, "text": "After that, the sample size calculation is quite simple:" }, { "code": null, "e": 12786, "s": 12625, "text": "alpha = 0.05power = 0.8ratio = 1ss_result = ss_analysis.solve_power(effect_size=effect_size, power=power,alpha=alpha, ratio=ratio , nobs1=None) print(ss_result)" }, { "code": null, "e": 12974, "s": 12786, "text": "Alpha is the threshold for statistical significance (5%) and our ratio of test and control sample sizes are 1 (equal). As a result, our required sample size is (output of ss_result) 4868." }, { "code": null, "e": 13029, "s": 12974, "text": "Let’s build a function to use this everywhere we want:" }, { "code": null, "e": 13452, "s": 13029, "text": "def calculate_sample_size(c_data, column_name, target,ratio): value_mean = c_data[column_name].mean() value_std = c_data[column_name].std() value_target = value_mean * target effect_size = (value_target - value_mean)/value_std power = 0.8 alpha = 0.05 ss_result = ss_analysis.solve_power(effect_size=effect_size, power=power,alpha=alpha, ratio=ratio , nobs1=None) print(int(ss_result))" }, { "code": null, "e": 13651, "s": 13452, "text": "To this function, we need to provide our dataset, the column_name that represents the value (purchase_count in our case), our target mean (0.75 was our target in the previous example) and the ratio." }, { "code": null, "e": 13784, "s": 13651, "text": "In the dataset above, let’s assume we want to increase purchase count mean by 5% and we will keep the sizes of both groups the same:" }, { "code": null, "e": 13844, "s": 13784, "text": "calculate_sample_size(df_hv, 'prev_purchase_count', 1.05,1)" }, { "code": null, "e": 13874, "s": 13844, "text": "Then the result becomes 8961." }, { "code": null, "e": 13931, "s": 13874, "text": "You can find the Jupyter Notebook for this article here." }, { "code": null, "e": 14148, "s": 13931, "text": "This is the end of the Data Driven Growth series. Hope you enjoyed the articles and started to apply the practices here. Those will be converted to an e-book and supported by a comprehensive video series. Stay tuned!" }, { "code": null, "e": 14163, "s": 14148, "text": "Happy hacking!" } ]
Bokeh - Filtering Data
Often, you may want to obtain a plot pertaining to a part of data that satisfies certain conditions instead of the entire dataset. Object of the CDSView class defined in bokeh.models module returns a subset of ColumnDatasource under consideration by applying one or more filters over it. IndexFilter is the simplest type of filter. You have to specify indices of only those rows from the dataset that you want to use while plotting the figure. Following example demonstrates use of IndexFilter to set up a CDSView. The resultant figure shows a line glyph between x and y data series of the ColumnDataSource. A view object is obtained by applying index filter over it. The view is used to plot circle glyph as a result of IndexFilter. from bokeh.models import ColumnDataSource, CDSView, IndexFilter from bokeh.plotting import figure, output_file, show source = ColumnDataSource(data = dict(x = list(range(1,11)), y = list(range(2,22,2)))) view = CDSView(source=source, filters = [IndexFilter([0, 2, 4,6])]) fig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y') fig.circle(x = "x", y = "y", size = 10, source = source, view = view, legend = 'filtered') fig.line(source.data['x'],source.data['y'], legend = 'unfiltered') show(fig) To choose only those rows from the data source, that satisfy a certain Boolean condition, apply a BooleanFilter. A typical Bokeh installation consists of a number of sample data sets in sampledata directory. For following example, we use unemployment1948 dataset provided in the form of unemployment1948.csv. It stores year wise percentage of unemployment in USA since 1948. We want to generate a plot only for year 1980 onwards. For that purpose, a CDSView object is obtained by applying BooleanFilter over the given data source. from bokeh.models import ColumnDataSource, CDSView, BooleanFilter from bokeh.plotting import figure, show from bokeh.sampledata.unemployment1948 import data source = ColumnDataSource(data) booleans = [True if int(year) >= 1980 else False for year in source.data['Year']] print (booleans) view1 = CDSView(source = source, filters=[BooleanFilter(booleans)]) p = figure(title = "Unemployment data", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label='Percentage') p.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2) show(p) To add more flexibility in applying filter, Bokeh provides a CustomJSFilter class with the help of which the data source can be filtered with a user defined JavaScript function. The example given below uses the same USA unemployment data. Defining a CustomJSFilter to plot unemployment figures of year 1980 and after. from bokeh.models import ColumnDataSource, CDSView, CustomJSFilter from bokeh.plotting import figure, show from bokeh.sampledata.unemployment1948 import data source = ColumnDataSource(data) custom_filter = CustomJSFilter(code = ''' var indices = []; for (var i = 0; i < source.get_length(); i++){ if (parseInt(source.data['Year'][i]) > = 1980){ indices.push(true); } else { indices.push(false); } } return indices; ''') view1 = CDSView(source = source, filters = [custom_filter]) p = figure(title = "Unemployment data", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label = 'Percentage') p.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2) show(p) Print Add Notes Bookmark this page
[ { "code": null, "e": 2558, "s": 2270, "text": "Often, you may want to obtain a plot pertaining to a part of data that satisfies certain conditions instead of the entire dataset. Object of the CDSView class defined in bokeh.models module returns a subset of ColumnDatasource under consideration by applying one or more filters over it." }, { "code": null, "e": 2714, "s": 2558, "text": "IndexFilter is the simplest type of filter. You have to specify indices of only those rows from the dataset that you want to use while plotting the figure." }, { "code": null, "e": 3004, "s": 2714, "text": "Following example demonstrates use of IndexFilter to set up a CDSView. The resultant figure shows a line glyph between x and y data series of the ColumnDataSource. A view object is obtained by applying index filter over it. The view is used to plot circle glyph as a result of IndexFilter." }, { "code": null, "e": 3526, "s": 3004, "text": "from bokeh.models import ColumnDataSource, CDSView, IndexFilter\nfrom bokeh.plotting import figure, output_file, show\nsource = ColumnDataSource(data = dict(x = list(range(1,11)), y = list(range(2,22,2))))\nview = CDSView(source=source, filters = [IndexFilter([0, 2, 4,6])])\nfig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')\nfig.circle(x = \"x\", y = \"y\", size = 10, source = source, view = view, legend = 'filtered')\nfig.line(source.data['x'],source.data['y'], legend = 'unfiltered')\nshow(fig)" }, { "code": null, "e": 3639, "s": 3526, "text": "To choose only those rows from the data source, that satisfy a certain Boolean condition, apply a BooleanFilter." }, { "code": null, "e": 4057, "s": 3639, "text": "A typical Bokeh installation consists of a number of sample data sets in sampledata directory. For following example, we use unemployment1948 dataset provided in the form of unemployment1948.csv. It stores year wise percentage of unemployment in USA since 1948. We want to generate a plot only for year 1980 onwards. For that purpose, a CDSView object is obtained by applying BooleanFilter over the given data source." }, { "code": null, "e": 4629, "s": 4057, "text": "from bokeh.models import ColumnDataSource, CDSView, BooleanFilter\nfrom bokeh.plotting import figure, show\nfrom bokeh.sampledata.unemployment1948 import data\nsource = ColumnDataSource(data)\nbooleans = [True if int(year) >= 1980 else False for year in\nsource.data['Year']]\nprint (booleans)\nview1 = CDSView(source = source, filters=[BooleanFilter(booleans)])\np = figure(title = \"Unemployment data\", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label='Percentage')\np.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)\nshow(p)" }, { "code": null, "e": 4807, "s": 4629, "text": "To add more flexibility in applying filter, Bokeh provides a CustomJSFilter class with the help of which the data source can be filtered with a user defined JavaScript function." }, { "code": null, "e": 4947, "s": 4807, "text": "The example given below uses the same USA unemployment data. Defining a CustomJSFilter to plot unemployment figures of year 1980 and after." }, { "code": null, "e": 5694, "s": 4947, "text": "from bokeh.models import ColumnDataSource, CDSView, CustomJSFilter\nfrom bokeh.plotting import figure, show\nfrom bokeh.sampledata.unemployment1948 import data\nsource = ColumnDataSource(data)\ncustom_filter = CustomJSFilter(code = '''\n var indices = [];\n\n for (var i = 0; i < source.get_length(); i++){\n if (parseInt(source.data['Year'][i]) > = 1980){\n indices.push(true);\n } else {\n indices.push(false);\n }\n }\n return indices;\n''')\nview1 = CDSView(source = source, filters = [custom_filter])\np = figure(title = \"Unemployment data\", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label = 'Percentage')\np.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)\nshow(p)" }, { "code": null, "e": 5701, "s": 5694, "text": " Print" }, { "code": null, "e": 5712, "s": 5701, "text": " Add Notes" } ]
Cassini’s Identity - GeeksforGeeks
24 Mar, 2021 Given a number N, the task is to evaluate below expression. Expected time complexity is O(1). f(n-1)*f(n+1) - f(n)*f(n) Where f(n) is the n-th Fibonacci number with n >= 1. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ...........i.e. (considering 0 as 0th Fibonacci number) Examples : Input : n = 5 Output : -1 f(5-1=4) = 3 f(5+1=6) = 8 f(5)*f(5)= 5*5 = 25 f(4)*f(6)- f(5)*f(5)= 24-25= -1 Although the task is simple i.e. find n-1th, nth and (n+1)-th Fibonacci numbers. Evaluate the expression and display the result. But this can be done in O(1) time using Cassini’s Identity which states that: f(n-1)*f(n+1) - f(n*n) = (-1)^n So, we don’t need to calculate any Fibonacci term,the only thing is to check whether n is even or odd. How does above formula work?The formula is based on matrix representation of Fibonacci numbers. C/C++ Java Python3 C# PHP JavaScript // C++ implementation to demonstrate working// of Cassini’s Identity #include<bits/stdc++.h>using namespace std; // Returns (-1)^nint cassini(int n){ return (n & 1) ? -1 : 1;} // Driver programint main(){ int n = 5; cout << cassini(n); return 0;} // Java implementation to demonstrate working// of Cassini’s Identity class Gfg{ // Returns (-1)^n static int cassini(int n) { return (n & 1) != 0 ? -1 : 1; } // Driver method public static void main(String args[]) { int n = 5; System.out.println(cassini(n)); }} # Python implementation# to demonstrate working# of Cassini’s Identity # Returns (-1)^ndef cassini(n): return -1 if (n & 1) else 1 # Driver program n = 5print(cassini(n)) # This code is contributed# by Anant Agarwal. // C# implementation to demonstrate // working of Cassini’s Identityusing System; class GFG { // Returns (-1) ^ n static int cassini(int n) { return (n & 1) != 0 ? -1 : 1; } // Driver Code public static void Main() { int n = 5; Console.Write(cassini(n)); }} // This code is contributed by Nitin Mittal. <?php// PHP implementation to // demonstrate working of // Cassini’s Identity // Returns (-1)^nfunction cassini($n){ return ($n & 1) ? -1 : 1;} // Driver Code$n = 5;echo(cassini($n)); // This code is contributed by Ajit.?> <script>// Javascript implementation to // demonstrate working of // Cassini’s Identity // Returns (-1)^n function cassini(n) { return (n & 1) ? -1 : 1; } // Driver Code let n = 5; document.write(cassini(n)); // This code is contributed by _saurabh_jaiswal. </script> -1 Reference :https://en.wikipedia.org/wiki/Cassini_and_Catalan_identities This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t _saurabh_jaiswal Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Find first and last digits of a number Count ways to reach the n'th stair Program to convert a given number to words Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 24718, "s": 24690, "text": "\n24 Mar, 2021" }, { "code": null, "e": 24812, "s": 24718, "text": "Given a number N, the task is to evaluate below expression. Expected time complexity is O(1)." }, { "code": null, "e": 24839, "s": 24812, "text": " f(n-1)*f(n+1) - f(n)*f(n)" }, { "code": null, "e": 25005, "s": 24839, "text": "Where f(n) is the n-th Fibonacci number with n >= 1. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ...........i.e. (considering 0 as 0th Fibonacci number)" }, { "code": null, "e": 25016, "s": 25005, "text": "Examples :" }, { "code": null, "e": 25121, "s": 25016, "text": "Input : n = 5\nOutput : -1\nf(5-1=4) = 3\nf(5+1=6) = 8\nf(5)*f(5)= 5*5 = 25\nf(4)*f(6)- f(5)*f(5)= 24-25= -1\n" }, { "code": null, "e": 25328, "s": 25121, "text": "Although the task is simple i.e. find n-1th, nth and (n+1)-th Fibonacci numbers. Evaluate the expression and display the result. But this can be done in O(1) time using Cassini’s Identity which states that:" }, { "code": null, "e": 25372, "s": 25328, "text": " f(n-1)*f(n+1) - f(n*n) = (-1)^n " }, { "code": null, "e": 25475, "s": 25372, "text": "So, we don’t need to calculate any Fibonacci term,the only thing is to check whether n is even or odd." }, { "code": null, "e": 25571, "s": 25475, "text": "How does above formula work?The formula is based on matrix representation of Fibonacci numbers." }, { "code": null, "e": 25577, "s": 25571, "text": "C/C++" }, { "code": null, "e": 25582, "s": 25577, "text": "Java" }, { "code": null, "e": 25590, "s": 25582, "text": "Python3" }, { "code": null, "e": 25593, "s": 25590, "text": "C#" }, { "code": null, "e": 25597, "s": 25593, "text": "PHP" }, { "code": null, "e": 25608, "s": 25597, "text": "JavaScript" }, { "code": "// C++ implementation to demonstrate working// of Cassini’s Identity #include<bits/stdc++.h>using namespace std; // Returns (-1)^nint cassini(int n){ return (n & 1) ? -1 : 1;} // Driver programint main(){ int n = 5; cout << cassini(n); return 0;} ", "e": 25869, "s": 25608, "text": null }, { "code": "// Java implementation to demonstrate working// of Cassini’s Identity class Gfg{ // Returns (-1)^n static int cassini(int n) { return (n & 1) != 0 ? -1 : 1; } // Driver method public static void main(String args[]) { int n = 5; System.out.println(cassini(n)); }}", "e": 26183, "s": 25869, "text": null }, { "code": "# Python implementation# to demonstrate working# of Cassini’s Identity # Returns (-1)^ndef cassini(n): return -1 if (n & 1) else 1 # Driver program n = 5print(cassini(n)) # This code is contributed# by Anant Agarwal.", "e": 26414, "s": 26183, "text": null }, { "code": "// C# implementation to demonstrate // working of Cassini’s Identityusing System; class GFG { // Returns (-1) ^ n static int cassini(int n) { return (n & 1) != 0 ? -1 : 1; } // Driver Code public static void Main() { int n = 5; Console.Write(cassini(n)); }} // This code is contributed by Nitin Mittal.", "e": 26771, "s": 26414, "text": null }, { "code": "<?php// PHP implementation to // demonstrate working of // Cassini’s Identity // Returns (-1)^nfunction cassini($n){ return ($n & 1) ? -1 : 1;} // Driver Code$n = 5;echo(cassini($n)); // This code is contributed by Ajit.?>", "e": 27002, "s": 26771, "text": null }, { "code": "<script>// Javascript implementation to // demonstrate working of // Cassini’s Identity // Returns (-1)^n function cassini(n) { return (n & 1) ? -1 : 1; } // Driver Code let n = 5; document.write(cassini(n)); // This code is contributed by _saurabh_jaiswal. </script>", "e": 27281, "s": 27002, "text": null }, { "code": null, "e": 27285, "s": 27281, "text": "-1\n" }, { "code": null, "e": 27357, "s": 27285, "text": "Reference :https://en.wikipedia.org/wiki/Cassini_and_Catalan_identities" }, { "code": null, "e": 27658, "s": 27357, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27783, "s": 27658, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27796, "s": 27783, "text": "nitin mittal" }, { "code": null, "e": 27802, "s": 27796, "text": "jit_t" }, { "code": null, "e": 27819, "s": 27802, "text": "_saurabh_jaiswal" }, { "code": null, "e": 27829, "s": 27819, "text": "Fibonacci" }, { "code": null, "e": 27842, "s": 27829, "text": "Mathematical" }, { "code": null, "e": 27855, "s": 27842, "text": "Mathematical" }, { "code": null, "e": 27865, "s": 27855, "text": "Fibonacci" }, { "code": null, "e": 27963, "s": 27865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27995, "s": 27963, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28039, "s": 27995, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28064, "s": 28039, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28097, "s": 28064, "text": "Program to multiply two matrices" }, { "code": null, "e": 28128, "s": 28097, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28160, "s": 28128, "text": "Check if a number is Palindrome" }, { "code": null, "e": 28199, "s": 28160, "text": "Find first and last digits of a number" }, { "code": null, "e": 28234, "s": 28199, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 28277, "s": 28234, "text": "Program to convert a given number to words" } ]
How to make your Pandas operation 100x faster | by Yifei Huang | Towards Data Science
Pandas is a great tool for exploring and working with data. As such, it is deliberately optimized for versatility and ease of use, instead of performance. There are often many different ways to do the exact same operation, some of which are far more performant than others. This is not a problem if your data is relatively small or your transformation is relatively simple, but it can quickly becomes a bottleneck as the scale and complexity increase. In this article, I will walk through a few different approaches to optimizing the performance ranging from vectorization to parallelization. Let’s start by making this issue more concrete with an example. A common operation when using Pandas is to create a new derived value based on one or more existing columns. The examples below (inspired by [1]) illustrates the various different ways of doing this using Pandas, and measure the resulting performance using the%timeit magic command in Jupyter notebooks. The first approach [sum_square(row[0], row[1]) for _, row in df.iterrows()] uses list comprehension along with the method iterrows , and is the slowest by a long shot. This is because it is effectively using a simple for loop and incurring the heavy overhead of using the pandas series object in each iteration. It is rarely necessary to use series object in your transformation function, so you should almost never use the iterrows method. The second approach [sum_square(a, b) for a, b in df[[0, 1]].itertuples(index=False)] replaces the iterrows method of the first approach with itertuples method. The improvement in performance is a whopping 60x (575ms -> 9.53ms). This is because the itertuples method bypasses the overhead associated with the Pandas series object and uses the simple tuples instead. If you need to loop through a Pandas dataframe, you should almost always itertuples instead of the iterrows The third approach df.apply(lambda row: sum_square(row[0], row[1]), axis=1 ) uses the apply method instead of list comprehension to apply the function to each row of the dataframe. It still incurs the overhead of the Pandas series object when working with each row, but is 6x faster than the first approach because it is able to leverage some more efficient pre-compiled looping methods underneath the hood. It is, however, still effectively a for loop, just more efficient way to do so. The fourth approach df.apply(lambda row: sum_square(row[0], row[1]), raw=True, axis=1 ) is able to achieve a 4x speed up relative to the third approach, with a very simple parameter tweak in adding raw=True . This is telling the apply method to bypass the overhead associated with the Pandas series object and use simple map objects instead. It is interesting note that this is still slower than the second approach with itertuples The fifth approach np.vectorize(sum_square)(df[0], df[1]) uses np.vectorize to attempt to make the function provided more “vectorized”. This basically means it tries to leverage pre-compiled and native methods that are SIMD (Single Instruction Multiple Data) and significantly faster [2], as much as possible. Depending on the function, it may or may not actually yield a speed up, but it never hurts to try given the relative simplicity. In this particularly example, it worked quite well and yielded a 171x speed up relative to the first approach. It is even 3x faster than the itertuple method in the second approach. The last approach np.power(df[0] + df[1], 2) fully takes advantage of the vectorized native Numpy methods and is 1888x faster than the first approach we started with. Just like the np.vectorize method, it may not always be possible (or clear as to how) to vectorize the given function, but when you can you should definitely try. A good rule of thumb for assessing whether you can vectorize the function is if you can represent it as linear algebra operations on matrices and scalar values. If you can, you can likely find native Numpy methods to vectorize those operations. What if your function cannot be vectorized or you don’t know how to? There are transformations of the data that simply cannot be vectorized, and therefore cannot benefit from the dramatic improvements that vectorization provided above (but you should still never use iterrows). One example of this type of transformation is regex operations on strings like extracting the top level domain from URLs. In these cases, there are a few different approaches like compiling your function using Cython or run-time compilers like Numba, or using parallel processing. I prefer parallel processing because it requires the least amount of rewrite of your existing code. You simply have to add a few lines wrapper code to make it work. The example below illustrates how you can do this import concurrent.futures import numpy as np import pandas as pd from functools import partial import time df = pd.DataFrame(np.random.binomial(n=1000, p=0.2, size=(10000,2))) # a no op function that simulates a transformation that takes some time to complete def do_work(row, duration): time.sleep(duration) return True FUNCTION_RUN_TIME = 0.0001 # simple use of apply to execute the function against the pd dataframe def serial_calc(df, duration): apply_partial = partial(do_work, duration=duration) df['result'] = df.apply(apply_partial, axis=1) return df %timeit serial_calc(df, FUNCTION_RUN_TIME) # simple wrapper code around serial_calc to parallelize the work def parallel_calc(df, func, n_core, duration): futs = [] df_split = np.array_split(df, n_core) # pool = concurrent.futures.ThreadPoolExecutor(max_workers = n_core) pool = concurrent.futures.ProcessPoolExecutor(max_workers = n_core) apply_partial = partial(func, duration=duration) return pd.concat(pool.map(apply_partial, df_split)) %timeit parallel_calc(df, serial_calc, 32, FUNCTION_RUN_TIME) 1.42 s ± 9.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 184 ms ± 776 μs per loop (mean ± std. dev. of 7 runs, 10 loops each) function_time = [] non_parallel_time = [] parallel_time = [] for d in range(11): # print(d) d_ms = d/20000 function_time.append(d_ms) start = time.time() serial_calc(df, d_ms) end = time.time() non_parallel_time.append(end-start) start = time.time() parallel_calc(df, serial_calc, 32, d_ms) end = time.time() parallel_time.append(end-start) import matplotlib.pyplot as plt font = {'family' : 'Arial', 'weight': 'normal', 'size' : 20} plt.rc('font', **font) fig, ax = plt.subplots(figsize=(14,8)) plt.xlabel('Function run time (ms)') plt.ylabel('Overall processing time (s)') x = [t*1000 for t in function_time] ax.plot(x, non_parallel_time, '-', linewidth=1) ax.plot(x, parallel_time, '-', linewidth=1) ax.legend(['Serial Apply', 'Parallelized Apply']) plt.show() As you can see with relatively little effort and no modification to the existing code, we were able to achieve a 7x speed up to the code by leveraging parallel processing. It is worth noting that this improvement increases with data scale and function run time, as can be seen in the graph below, where I varied simulated function run time from 0 to 0.5ms. The serial implementation processing time scales at a much higher rate than parallel implementation. A few important consideration to keep in mind when using parallel processing Overhead — parallel processing incurs quite a bit of overhead, and as a result it is not guaranteed to be faster than serial processing if you function is relatively fast and your data is not super large. For the example above (10k rows), we can see that parallel processing overtakes serial processing, at around 0.01ms function run time.CPU bound vs I/O bound — If your function is CPU bound, meaning that the transformation logic just takes a long time and it is not waiting for data, then you should use multiprocess (or process pool). If your function is I/O bound, meaning that it is spending a lot of time waiting for data (e.g. making api requests over the internet), then multithreading (or thread pool) will be the better and faster option. This article [3] provides a really good discussion on differences between the two. Overhead — parallel processing incurs quite a bit of overhead, and as a result it is not guaranteed to be faster than serial processing if you function is relatively fast and your data is not super large. For the example above (10k rows), we can see that parallel processing overtakes serial processing, at around 0.01ms function run time. CPU bound vs I/O bound — If your function is CPU bound, meaning that the transformation logic just takes a long time and it is not waiting for data, then you should use multiprocess (or process pool). If your function is I/O bound, meaning that it is spending a lot of time waiting for data (e.g. making api requests over the internet), then multithreading (or thread pool) will be the better and faster option. This article [3] provides a really good discussion on differences between the two. Whenever possible write your transformation functions using native pre-compiled SIMD methods (most Numpy and many Pandas native methods are)If you are not sure how to vectorize yourself, try np.vectorize, but your mileage may varyUse df.apply or df.itertuples for looping, never use df.iterrows unless you know exactly why you must use itIf your data is large and transformation is slow and cannot be vectorized easily, parallel processing is an easy way to boost performance Whenever possible write your transformation functions using native pre-compiled SIMD methods (most Numpy and many Pandas native methods are) If you are not sure how to vectorize yourself, try np.vectorize, but your mileage may vary Use df.apply or df.itertuples for looping, never use df.iterrows unless you know exactly why you must use it If your data is large and transformation is slow and cannot be vectorized easily, parallel processing is an easy way to boost performance Hope this was a useful discussion. Feel free to reach out if you have comments or questions. Twitter | Linkedin | Medium
[ { "code": null, "e": 765, "s": 172, "text": "Pandas is a great tool for exploring and working with data. As such, it is deliberately optimized for versatility and ease of use, instead of performance. There are often many different ways to do the exact same operation, some of which are far more performant than others. This is not a problem if your data is relatively small or your transformation is relatively simple, but it can quickly becomes a bottleneck as the scale and complexity increase. In this article, I will walk through a few different approaches to optimizing the performance ranging from vectorization to parallelization." }, { "code": null, "e": 829, "s": 765, "text": "Let’s start by making this issue more concrete with an example." }, { "code": null, "e": 1133, "s": 829, "text": "A common operation when using Pandas is to create a new derived value based on one or more existing columns. The examples below (inspired by [1]) illustrates the various different ways of doing this using Pandas, and measure the resulting performance using the%timeit magic command in Jupyter notebooks." }, { "code": null, "e": 1152, "s": 1133, "text": "The first approach" }, { "code": null, "e": 1209, "s": 1152, "text": "[sum_square(row[0], row[1]) for _, row in df.iterrows()]" }, { "code": null, "e": 1574, "s": 1209, "text": "uses list comprehension along with the method iterrows , and is the slowest by a long shot. This is because it is effectively using a simple for loop and incurring the heavy overhead of using the pandas series object in each iteration. It is rarely necessary to use series object in your transformation function, so you should almost never use the iterrows method." }, { "code": null, "e": 1594, "s": 1574, "text": "The second approach" }, { "code": null, "e": 1660, "s": 1594, "text": "[sum_square(a, b) for a, b in df[[0, 1]].itertuples(index=False)]" }, { "code": null, "e": 2048, "s": 1660, "text": "replaces the iterrows method of the first approach with itertuples method. The improvement in performance is a whopping 60x (575ms -> 9.53ms). This is because the itertuples method bypasses the overhead associated with the Pandas series object and uses the simple tuples instead. If you need to loop through a Pandas dataframe, you should almost always itertuples instead of the iterrows" }, { "code": null, "e": 2067, "s": 2048, "text": "The third approach" }, { "code": null, "e": 2125, "s": 2067, "text": "df.apply(lambda row: sum_square(row[0], row[1]), axis=1 )" }, { "code": null, "e": 2536, "s": 2125, "text": "uses the apply method instead of list comprehension to apply the function to each row of the dataframe. It still incurs the overhead of the Pandas series object when working with each row, but is 6x faster than the first approach because it is able to leverage some more efficient pre-compiled looping methods underneath the hood. It is, however, still effectively a for loop, just more efficient way to do so." }, { "code": null, "e": 2556, "s": 2536, "text": "The fourth approach" }, { "code": null, "e": 2624, "s": 2556, "text": "df.apply(lambda row: sum_square(row[0], row[1]), raw=True, axis=1 )" }, { "code": null, "e": 2968, "s": 2624, "text": "is able to achieve a 4x speed up relative to the third approach, with a very simple parameter tweak in adding raw=True . This is telling the apply method to bypass the overhead associated with the Pandas series object and use simple map objects instead. It is interesting note that this is still slower than the second approach with itertuples" }, { "code": null, "e": 2987, "s": 2968, "text": "The fifth approach" }, { "code": null, "e": 3026, "s": 2987, "text": "np.vectorize(sum_square)(df[0], df[1])" }, { "code": null, "e": 3589, "s": 3026, "text": "uses np.vectorize to attempt to make the function provided more “vectorized”. This basically means it tries to leverage pre-compiled and native methods that are SIMD (Single Instruction Multiple Data) and significantly faster [2], as much as possible. Depending on the function, it may or may not actually yield a speed up, but it never hurts to try given the relative simplicity. In this particularly example, it worked quite well and yielded a 171x speed up relative to the first approach. It is even 3x faster than the itertuple method in the second approach." }, { "code": null, "e": 3607, "s": 3589, "text": "The last approach" }, { "code": null, "e": 3634, "s": 3607, "text": "np.power(df[0] + df[1], 2)" }, { "code": null, "e": 4164, "s": 3634, "text": "fully takes advantage of the vectorized native Numpy methods and is 1888x faster than the first approach we started with. Just like the np.vectorize method, it may not always be possible (or clear as to how) to vectorize the given function, but when you can you should definitely try. A good rule of thumb for assessing whether you can vectorize the function is if you can represent it as linear algebra operations on matrices and scalar values. If you can, you can likely find native Numpy methods to vectorize those operations." }, { "code": null, "e": 4233, "s": 4164, "text": "What if your function cannot be vectorized or you don’t know how to?" }, { "code": null, "e": 4938, "s": 4233, "text": "There are transformations of the data that simply cannot be vectorized, and therefore cannot benefit from the dramatic improvements that vectorization provided above (but you should still never use iterrows). One example of this type of transformation is regex operations on strings like extracting the top level domain from URLs. In these cases, there are a few different approaches like compiling your function using Cython or run-time compilers like Numba, or using parallel processing. I prefer parallel processing because it requires the least amount of rewrite of your existing code. You simply have to add a few lines wrapper code to make it work. The example below illustrates how you can do this" }, { "code": null, "e": 5046, "s": 4938, "text": "import concurrent.futures\nimport numpy as np\nimport pandas as pd\nfrom functools import partial\nimport time\n" }, { "code": null, "e": 6052, "s": 5046, "text": "df = pd.DataFrame(np.random.binomial(n=1000, p=0.2, size=(10000,2)))\n\n# a no op function that simulates a transformation that takes some time to complete\ndef do_work(row, duration):\n time.sleep(duration)\n return True\n\nFUNCTION_RUN_TIME = 0.0001\n\n# simple use of apply to execute the function against the pd dataframe\ndef serial_calc(df, duration):\n apply_partial = partial(do_work, duration=duration)\n df['result'] = df.apply(apply_partial, axis=1)\n return df\n\n%timeit serial_calc(df, FUNCTION_RUN_TIME)\n\n# simple wrapper code around serial_calc to parallelize the work\ndef parallel_calc(df, func, n_core, duration):\n futs = []\n df_split = np.array_split(df, n_core)\n# pool = concurrent.futures.ThreadPoolExecutor(max_workers = n_core)\n pool = concurrent.futures.ProcessPoolExecutor(max_workers = n_core)\n apply_partial = partial(func, duration=duration)\n return pd.concat(pool.map(apply_partial, df_split))\n\n%timeit parallel_calc(df, serial_calc, 32, FUNCTION_RUN_TIME)\n" }, { "code": null, "e": 6190, "s": 6052, "text": "1.42 s ± 9.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n184 ms ± 776 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" }, { "code": null, "e": 7034, "s": 6190, "text": "function_time = []\nnon_parallel_time = []\nparallel_time = []\n\nfor d in range(11):\n# print(d)\n d_ms = d/20000\n function_time.append(d_ms)\n start = time.time()\n serial_calc(df, d_ms)\n end = time.time()\n non_parallel_time.append(end-start)\n \n start = time.time()\n parallel_calc(df, serial_calc, 32, d_ms)\n end = time.time()\n parallel_time.append(end-start)\n \nimport matplotlib.pyplot as plt\n\nfont = {'family' : 'Arial',\n 'weight': 'normal',\n 'size' : 20}\n\nplt.rc('font', **font)\n\nfig, ax = plt.subplots(figsize=(14,8))\nplt.xlabel('Function run time (ms)')\nplt.ylabel('Overall processing time (s)')\n\nx = [t*1000 for t in function_time]\n\nax.plot(x, non_parallel_time, '-', linewidth=1)\nax.plot(x, parallel_time, '-', linewidth=1)\nax.legend(['Serial Apply', 'Parallelized Apply'])\n\nplt.show()\n" }, { "code": null, "e": 7492, "s": 7034, "text": "As you can see with relatively little effort and no modification to the existing code, we were able to achieve a 7x speed up to the code by leveraging parallel processing. It is worth noting that this improvement increases with data scale and function run time, as can be seen in the graph below, where I varied simulated function run time from 0 to 0.5ms. The serial implementation processing time scales at a much higher rate than parallel implementation." }, { "code": null, "e": 7569, "s": 7492, "text": "A few important consideration to keep in mind when using parallel processing" }, { "code": null, "e": 8403, "s": 7569, "text": "Overhead — parallel processing incurs quite a bit of overhead, and as a result it is not guaranteed to be faster than serial processing if you function is relatively fast and your data is not super large. For the example above (10k rows), we can see that parallel processing overtakes serial processing, at around 0.01ms function run time.CPU bound vs I/O bound — If your function is CPU bound, meaning that the transformation logic just takes a long time and it is not waiting for data, then you should use multiprocess (or process pool). If your function is I/O bound, meaning that it is spending a lot of time waiting for data (e.g. making api requests over the internet), then multithreading (or thread pool) will be the better and faster option. This article [3] provides a really good discussion on differences between the two." }, { "code": null, "e": 8743, "s": 8403, "text": "Overhead — parallel processing incurs quite a bit of overhead, and as a result it is not guaranteed to be faster than serial processing if you function is relatively fast and your data is not super large. For the example above (10k rows), we can see that parallel processing overtakes serial processing, at around 0.01ms function run time." }, { "code": null, "e": 9238, "s": 8743, "text": "CPU bound vs I/O bound — If your function is CPU bound, meaning that the transformation logic just takes a long time and it is not waiting for data, then you should use multiprocess (or process pool). If your function is I/O bound, meaning that it is spending a lot of time waiting for data (e.g. making api requests over the internet), then multithreading (or thread pool) will be the better and faster option. This article [3] provides a really good discussion on differences between the two." }, { "code": null, "e": 9714, "s": 9238, "text": "Whenever possible write your transformation functions using native pre-compiled SIMD methods (most Numpy and many Pandas native methods are)If you are not sure how to vectorize yourself, try np.vectorize, but your mileage may varyUse df.apply or df.itertuples for looping, never use df.iterrows unless you know exactly why you must use itIf your data is large and transformation is slow and cannot be vectorized easily, parallel processing is an easy way to boost performance" }, { "code": null, "e": 9855, "s": 9714, "text": "Whenever possible write your transformation functions using native pre-compiled SIMD methods (most Numpy and many Pandas native methods are)" }, { "code": null, "e": 9946, "s": 9855, "text": "If you are not sure how to vectorize yourself, try np.vectorize, but your mileage may vary" }, { "code": null, "e": 10055, "s": 9946, "text": "Use df.apply or df.itertuples for looping, never use df.iterrows unless you know exactly why you must use it" }, { "code": null, "e": 10193, "s": 10055, "text": "If your data is large and transformation is slow and cannot be vectorized easily, parallel processing is an easy way to boost performance" } ]
Latent Space of Convolutional Neural Nets | Towards Data Science
A fascinating thing about Neural networks, especially Convolutional Neural Networks is that in the final layers of the network where the layers are fully connected, each layer can be treated as a vector space. All the useful and required information that has been extracted from the image by the ConvNet has been stored in a compact version in the final layer in the form of a feature vector. When this final layer is treated as a vector space and is subjected to vector algebra, it starts to yield some very interesting and useful properties. I trained a Resnet50 classifier on the iMaterialist Challenge(Fashion) dataset from Kaggle. The challenge here is to classify every apparel image into appropriate attributes like pattern, neckline, sleeve length, style, etc. I used the pre-trained Resnet model and applied transfer learning on this dataset with added layers for each of the labels. Once the model got trained, I wish to look at the vector space of the last layer and search for patterns. The last FC layer of the Resnet50 is of length 1000. After transfer learning on the Fashion dataset, I apply PCA on this layer and reduce the dimension to 50 which retains more than 98% of the variance. The concept of Latent Space Directions is popular with GANs and Variational Auto Encoders where the input is a vector and the output is an image, it is observed that by translating the input vector in a certain direction, a certain attribute of the output image changes. The below example is from StyleGAN trained by NVIDIA, you can have a look at this website where a fake face gets generated from a random vector every time you refresh the page. This is exciting! A trivial linear operation on the input vector brings about such a complex transformation in the output image. These latent directions are like knobs which you can tune to get the desired effect on the output image. Incredible! In our image classifier, we are doing exactly the opposite of GAN. In the classifier, we take an image and get a vector of length 1000 in the FC layer, and with the PCA transformation, we reduce its dimension to 50. The idea we want to explore is whether the image attributes we have trained the model for, are they getting arranged in a linear fashion in the vector space of the FC layer and the layer after PCA. The answer is indeed a yes! One of the tasks in the iMaterialist challenge is to identify the sleeve length which is classified into five types: long-sleeved, short sleeves, puff sleeves, sleeveless, and strapless. Out of these five, three are in majority: long-sleeved, short sleeves, and sleeveless. Now we want to see if there exists a latent direction along which these three sleeve length classes get segregated. If it was a binary classification, we could have used logistic regression and the vector of coefficients would have given us the latent direction but in our case, we have multiple classes. One method to get the latent direction in a multi-class problem is to build a neural network where we force the input layer through a single-unit middle layer and the vector of weights of the input layer gives us the latent direction. The code snippet for this classifier is given below where my input is the PCA layer of length 50 which is passed through a single unit layer and after a few layers, I get my final 5 classes. The idea behind forcing it through a single unit layer is to constraint the network to learn a linear latent direction. The value of this single unit layer essentially gives me the projection of inputs onto the learned latent direction. class latent_model(nn.Module): def __init__(self): super(latent_model, self).__init__() self.layer1 = nn.Sequential(nn.Linear(50, 1), nn.Linear(1,10), nn.ReLU(),nn.Linear(10,10), nn.ReLU(), nn.Linear(10,5) , nn.Softmax()) def forward(self, ip): x = self.layer1(ip) return xlm=latent_model()#####Train the Classifier##############################The latent direction##latent_direction=lm.layer1[0].weight[0].cpu().detach().numpy() Let's see what we get after training this small classifier!The plot below shows the distribution of different sleeve types along the latent direction, and we can see that the three major classes: short, long, and sleeveless get segregated along this direction. Neural networks are complex non-linear models but there is linearity hidden in hidden layers! Now I take an image of a dress and starting from the point in the PCA vector space for this image, I draw a line along the latent direction for sleeve length and retrieve images from the training dataset that are closest to this line. Below are a few such examples. An interesting thing to note is that, while the sleeve length changes along the direction from long-sleeved to short sleeves to sleeveless, other features of the dress as the neckline, dress length, and the overall style tend to stay preserved. In the second example, all the retrieved images are long dresses and have two poses in an image whereas in the third example most of them don’t have a model. The only significant change along the direction is in the sleeve length. From the above results, it looks like the training dataset images have been arranged in a pristine order in the latent space of the PCA layer! Doing a similar analysis for pattern gives the following results From the above graph, we see that floral type dresses get segregated from more solid type patterns along the latent direction. Looking at a few examples confirms this observation. In the above examples, the pattern slowly shifts from solid to stripes to floral to plaid along the discovered direction and the retrieved images tend to be similar to the starting image in terms of the overall style. Looking at the latent space of feature vectors is a step forward in our understanding of the workings of Neural Networks. From our above analysis, one conclusion that we can draw is that Convolution Neural Networks take in complex data in form of images and the information extracted from those images gets more and more organized as the input passes through subsequent layers. We find that in the latent space of the last layers of the network our training dataset images get sorted and segregated in an orderly way so much so that we can discover linear directions along which a certain attribute of interest varies.Read more blogs here.
[ { "code": null, "e": 715, "s": 171, "text": "A fascinating thing about Neural networks, especially Convolutional Neural Networks is that in the final layers of the network where the layers are fully connected, each layer can be treated as a vector space. All the useful and required information that has been extracted from the image by the ConvNet has been stored in a compact version in the final layer in the form of a feature vector. When this final layer is treated as a vector space and is subjected to vector algebra, it starts to yield some very interesting and useful properties." }, { "code": null, "e": 1170, "s": 715, "text": "I trained a Resnet50 classifier on the iMaterialist Challenge(Fashion) dataset from Kaggle. The challenge here is to classify every apparel image into appropriate attributes like pattern, neckline, sleeve length, style, etc. I used the pre-trained Resnet model and applied transfer learning on this dataset with added layers for each of the labels. Once the model got trained, I wish to look at the vector space of the last layer and search for patterns." }, { "code": null, "e": 1373, "s": 1170, "text": "The last FC layer of the Resnet50 is of length 1000. After transfer learning on the Fashion dataset, I apply PCA on this layer and reduce the dimension to 50 which retains more than 98% of the variance." }, { "code": null, "e": 1821, "s": 1373, "text": "The concept of Latent Space Directions is popular with GANs and Variational Auto Encoders where the input is a vector and the output is an image, it is observed that by translating the input vector in a certain direction, a certain attribute of the output image changes. The below example is from StyleGAN trained by NVIDIA, you can have a look at this website where a fake face gets generated from a random vector every time you refresh the page." }, { "code": null, "e": 2067, "s": 1821, "text": "This is exciting! A trivial linear operation on the input vector brings about such a complex transformation in the output image. These latent directions are like knobs which you can tune to get the desired effect on the output image. Incredible!" }, { "code": null, "e": 2509, "s": 2067, "text": "In our image classifier, we are doing exactly the opposite of GAN. In the classifier, we take an image and get a vector of length 1000 in the FC layer, and with the PCA transformation, we reduce its dimension to 50. The idea we want to explore is whether the image attributes we have trained the model for, are they getting arranged in a linear fashion in the vector space of the FC layer and the layer after PCA. The answer is indeed a yes!" }, { "code": null, "e": 3088, "s": 2509, "text": "One of the tasks in the iMaterialist challenge is to identify the sleeve length which is classified into five types: long-sleeved, short sleeves, puff sleeves, sleeveless, and strapless. Out of these five, three are in majority: long-sleeved, short sleeves, and sleeveless. Now we want to see if there exists a latent direction along which these three sleeve length classes get segregated. If it was a binary classification, we could have used logistic regression and the vector of coefficients would have given us the latent direction but in our case, we have multiple classes." }, { "code": null, "e": 3751, "s": 3088, "text": "One method to get the latent direction in a multi-class problem is to build a neural network where we force the input layer through a single-unit middle layer and the vector of weights of the input layer gives us the latent direction. The code snippet for this classifier is given below where my input is the PCA layer of length 50 which is passed through a single unit layer and after a few layers, I get my final 5 classes. The idea behind forcing it through a single unit layer is to constraint the network to learn a linear latent direction. The value of this single unit layer essentially gives me the projection of inputs onto the learned latent direction." }, { "code": null, "e": 4195, "s": 3751, "text": "class latent_model(nn.Module): def __init__(self): super(latent_model, self).__init__() self.layer1 = nn.Sequential(nn.Linear(50, 1), nn.Linear(1,10), nn.ReLU(),nn.Linear(10,10), nn.ReLU(), nn.Linear(10,5) , nn.Softmax()) def forward(self, ip): x = self.layer1(ip) return xlm=latent_model()#####Train the Classifier##############################The latent direction##latent_direction=lm.layer1[0].weight[0].cpu().detach().numpy()" }, { "code": null, "e": 4456, "s": 4195, "text": "Let's see what we get after training this small classifier!The plot below shows the distribution of different sleeve types along the latent direction, and we can see that the three major classes: short, long, and sleeveless get segregated along this direction." }, { "code": null, "e": 4550, "s": 4456, "text": "Neural networks are complex non-linear models but there is linearity hidden in hidden layers!" }, { "code": null, "e": 5061, "s": 4550, "text": "Now I take an image of a dress and starting from the point in the PCA vector space for this image, I draw a line along the latent direction for sleeve length and retrieve images from the training dataset that are closest to this line. Below are a few such examples. An interesting thing to note is that, while the sleeve length changes along the direction from long-sleeved to short sleeves to sleeveless, other features of the dress as the neckline, dress length, and the overall style tend to stay preserved." }, { "code": null, "e": 5292, "s": 5061, "text": "In the second example, all the retrieved images are long dresses and have two poses in an image whereas in the third example most of them don’t have a model. The only significant change along the direction is in the sleeve length." }, { "code": null, "e": 5435, "s": 5292, "text": "From the above results, it looks like the training dataset images have been arranged in a pristine order in the latent space of the PCA layer!" }, { "code": null, "e": 5500, "s": 5435, "text": "Doing a similar analysis for pattern gives the following results" }, { "code": null, "e": 5680, "s": 5500, "text": "From the above graph, we see that floral type dresses get segregated from more solid type patterns along the latent direction. Looking at a few examples confirms this observation." }, { "code": null, "e": 5898, "s": 5680, "text": "In the above examples, the pattern slowly shifts from solid to stripes to floral to plaid along the discovered direction and the retrieved images tend to be similar to the starting image in terms of the overall style." } ]
Convert decimal to binary number in Python program
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given a decimal number, we need to convert it into its binary equivalent. There are two approaches to solve the given problem. Let’s see them one by one− Live Demo def DecimalToBinary(num): if num > 1: DecimalToBinary(num // 2) print(num % 2, end = '') # main if __name__ == '__main__': # decimal input dec_val = 56 # binary equivalent DecimalToBinary(dec_val) 111000 All the variables and functions are declared in the global scope shown in the figure above. Live Demo def decimalToBinary(n): return bin(n).replace("0b", "") # Driver code if __name__ == '__main__': print(decimalToBinary(56)) 111000 All the variables and functions are declared in the global scope shown in the figure above. In this article, we have learned about the python program to convert a list into a string.
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1251, "s": 1150, "text": "Problem statement − We are given a decimal number, we need to convert it into its binary equivalent." }, { "code": null, "e": 1331, "s": 1251, "text": "There are two approaches to solve the given problem. Let’s see them one by one−" }, { "code": null, "e": 1342, "s": 1331, "text": " Live Demo" }, { "code": null, "e": 1563, "s": 1342, "text": "def DecimalToBinary(num):\n if num > 1:\n DecimalToBinary(num // 2)\n print(num % 2, end = '')\n# main\nif __name__ == '__main__':\n # decimal input\n dec_val = 56\n # binary equivalent\n DecimalToBinary(dec_val)" }, { "code": null, "e": 1570, "s": 1563, "text": "111000" }, { "code": null, "e": 1662, "s": 1570, "text": "All the variables and functions are declared in the global scope shown in the figure above." }, { "code": null, "e": 1673, "s": 1662, "text": " Live Demo" }, { "code": null, "e": 1803, "s": 1673, "text": "def decimalToBinary(n):\n return bin(n).replace(\"0b\", \"\")\n# Driver code\nif __name__ == '__main__':\n print(decimalToBinary(56))" }, { "code": null, "e": 1810, "s": 1803, "text": "111000" }, { "code": null, "e": 1902, "s": 1810, "text": "All the variables and functions are declared in the global scope shown in the figure above." }, { "code": null, "e": 1993, "s": 1902, "text": "In this article, we have learned about the python program to convert a list into a string." } ]
Raspberry Pi and OpenVino. With the Intel Compute Stick | by David Moore | Towards Data Science
If you have been reading my column here on Towards Data Science, you will know that I am on a mission. I wanted to count the number of cars passing my house using Computer Vision and Motion Detection. This article provides a small update on Computer Vision using the Intel Neural Compute Stick and the OpenVino library. As a catch-up, I previously built a camera and then explained the need to tune the motion detection device(s). My earlier posts described the camera build and early scripts to review the data and make sense of passing traffic. We had even made a very early chart to plot motion events. Last time I sent 192 images forward through the Yolo model using the Raspberry Pi ARM CPU. There was a lot of heat, and things took a long time. In fact, it took 10 seconds per image. Worse still, I had to slow everything down to only do a shot in 15 seconds. The system over-heated getting to 85% degrees, and I closed, for XMAS, with wanting to run the Neural Compute Stick with that workload to see if things would be any better. My love for Raspberry Pi had started to wear off, and I was feeling a little sad. Let’s get on with updating my code to use the Intel co-processor and just see what happens! I mentioned I had the Neural Compute Stick in my last article, I therefore went ahead and refactored my class to exploit OpenVino. That would allow me to transfer the CPU workload to a specialist Inference Engine. Since I had committed myself to report back on the effort here is my summary of the exercise. There is an excellent tutorial on the whole topic over at pyimagesearch.com and plenty written about OpenCV and OpenVINO already such that I won’t need to get into the details here. www.pyimagesearch.com The value of using the Object Orientated approach is that the code gets nicely segregated out and is therefore much easier to maintain and update. I only really needed to add a single line of code to my __init__ function. After I load the ‘net’ from the disk files, I can update the Object to set my preferred device as the Intel stick. How cool is that! self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD) Naturally, there are all sorts of problems when we take this simple approach. What if the Neural Compute Stick isn’t plugged in? Rather than default to the Raspberry Pi CPU I prefer the script to abend! Obviously, for production workloads, you’d really want to write more robust code! The last run, 192 photos, took 15 seconds per image, and produced a very hot Raspberry Pi, so how did we do? I couldn’t be happier as it turns out. The co-processor cost me about 100.00 dollars, far less than an Nvidia Titan GPU and is much easier to set-up. I couldn’t be happier, really. www.amazon.com So I ran my code once again my = myYolo()my.run() This time I removed a 5-second delay to allow things to cool down. I can tell you that the compute stick is a Turbocharger (Supercharger) add-on to the Raspberry Pi for Deep Neural Network inference workloads. Let us examine the results. Image 0 — took 29 seconds, and that might seem like a lot. But remember that we have the overhead of transferring our model to the Neural Compute stick on the first forward pass. Image 1 took a mere .58, so just half a second to perform a forward pass on the neural network. If we exclude image 0, as an outlier, and get the average of the remaining 191 images, the average inference time is .57 or half a second. The Intel device performs object detection in .57 seconds whereas the Arm-based CPU for Raspberry Pi 4b took at least 9.5 seconds. Isn’t that incredible! But wait! there is more. Since we are offloading the compute-intensive workload to the Intel device, there is nothing much for the CPU to do. The CPU must mostly handle a bit of I/O between the SSD storage drive, cache memory, and the Neural stick. Therefore there is absolutely no heat produced. We went from >80degrees to a more or less constant 45degrees. That really is amazing. The Intel stick gets warm to the touch, but there is no hum or any noises at all. My love of the Raspberry Pi is now restored, and I am delighted. Now it makes no difference, to the accuracy, if you use the Intel Neural Compute stick or the Arm-based CPU. Things just move slower or faster, but the object detection is the system. I reported back on doing Computer Vision operations on the Intel Stick, but I still have my investigation into 100 pictures where Yolo didn’t find an object to complete! Is the data pointing to a need to train Yolo on an Irish data set? Exciting, please do come back! I can now run Yolo in a reasonable time and pass many more photos through the model.
[ { "code": null, "e": 492, "s": 172, "text": "If you have been reading my column here on Towards Data Science, you will know that I am on a mission. I wanted to count the number of cars passing my house using Computer Vision and Motion Detection. This article provides a small update on Computer Vision using the Intel Neural Compute Stick and the OpenVino library." }, { "code": null, "e": 1385, "s": 492, "text": "As a catch-up, I previously built a camera and then explained the need to tune the motion detection device(s). My earlier posts described the camera build and early scripts to review the data and make sense of passing traffic. We had even made a very early chart to plot motion events. Last time I sent 192 images forward through the Yolo model using the Raspberry Pi ARM CPU. There was a lot of heat, and things took a long time. In fact, it took 10 seconds per image. Worse still, I had to slow everything down to only do a shot in 15 seconds. The system over-heated getting to 85% degrees, and I closed, for XMAS, with wanting to run the Neural Compute Stick with that workload to see if things would be any better. My love for Raspberry Pi had started to wear off, and I was feeling a little sad. Let’s get on with updating my code to use the Intel co-processor and just see what happens!" }, { "code": null, "e": 1693, "s": 1385, "text": "I mentioned I had the Neural Compute Stick in my last article, I therefore went ahead and refactored my class to exploit OpenVino. That would allow me to transfer the CPU workload to a specialist Inference Engine. Since I had committed myself to report back on the effort here is my summary of the exercise." }, { "code": null, "e": 1875, "s": 1693, "text": "There is an excellent tutorial on the whole topic over at pyimagesearch.com and plenty written about OpenCV and OpenVINO already such that I won’t need to get into the details here." }, { "code": null, "e": 1897, "s": 1875, "text": "www.pyimagesearch.com" }, { "code": null, "e": 2252, "s": 1897, "text": "The value of using the Object Orientated approach is that the code gets nicely segregated out and is therefore much easier to maintain and update. I only really needed to add a single line of code to my __init__ function. After I load the ‘net’ from the disk files, I can update the Object to set my preferred device as the Intel stick. How cool is that!" }, { "code": null, "e": 2308, "s": 2252, "text": "self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD)" }, { "code": null, "e": 2702, "s": 2308, "text": "Naturally, there are all sorts of problems when we take this simple approach. What if the Neural Compute Stick isn’t plugged in? Rather than default to the Raspberry Pi CPU I prefer the script to abend! Obviously, for production workloads, you’d really want to write more robust code! The last run, 192 photos, took 15 seconds per image, and produced a very hot Raspberry Pi, so how did we do?" }, { "code": null, "e": 2883, "s": 2702, "text": "I couldn’t be happier as it turns out. The co-processor cost me about 100.00 dollars, far less than an Nvidia Titan GPU and is much easier to set-up. I couldn’t be happier, really." }, { "code": null, "e": 2898, "s": 2883, "text": "www.amazon.com" }, { "code": null, "e": 2926, "s": 2898, "text": "So I ran my code once again" }, { "code": null, "e": 2948, "s": 2926, "text": "my = myYolo()my.run()" }, { "code": null, "e": 3186, "s": 2948, "text": "This time I removed a 5-second delay to allow things to cool down. I can tell you that the compute stick is a Turbocharger (Supercharger) add-on to the Raspberry Pi for Deep Neural Network inference workloads. Let us examine the results." }, { "code": null, "e": 3600, "s": 3186, "text": "Image 0 — took 29 seconds, and that might seem like a lot. But remember that we have the overhead of transferring our model to the Neural Compute stick on the first forward pass. Image 1 took a mere .58, so just half a second to perform a forward pass on the neural network. If we exclude image 0, as an outlier, and get the average of the remaining 191 images, the average inference time is .57 or half a second." }, { "code": null, "e": 4219, "s": 3600, "text": "The Intel device performs object detection in .57 seconds whereas the Arm-based CPU for Raspberry Pi 4b took at least 9.5 seconds. Isn’t that incredible! But wait! there is more. Since we are offloading the compute-intensive workload to the Intel device, there is nothing much for the CPU to do. The CPU must mostly handle a bit of I/O between the SSD storage drive, cache memory, and the Neural stick. Therefore there is absolutely no heat produced. We went from >80degrees to a more or less constant 45degrees. That really is amazing. The Intel stick gets warm to the touch, but there is no hum or any noises at all." }, { "code": null, "e": 4284, "s": 4219, "text": "My love of the Raspberry Pi is now restored, and I am delighted." } ]
fmt.Sscanf() Function in Golang With Examples - GeeksforGeeks
05 May, 2020 In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sscanf() function in Go language scans the specified string and stores the successive space-separated values into successive arguments as determined by the format. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. Syntax: func Sscanf(str string, format string, a ...interface{}) (n int, err error) Parameters: This function accepts three parameters which are illustrated below: str string: This parameter contains the specified text which is going to be scanned. format string: This parameter is the different types of format for each elements of the specified string. a ...interface{}: This parameter receives each elements of the string. Returns: It returns the number of items successfully parsed. Example 1: // Golang program to illustrate the usage of// fmt.Sscanf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring two variables var name string var alphabet_count int // Calling the Sscanf() function which // returns the number of elements // successfully parsed and error if // it persists n, err := fmt.Sscanf("GFG is having 3 alphabets.", "%s is having %d alphabets.", &name, &alphabet_count) // Below statements get // executed if there is any error if err != nil { panic(err) } // Printing the number of // elements and each elements also fmt.Printf("%d: %s, %d\n", n, name, alphabet_count) } Output: 2: GFG, 3 Example 2: // Golang program to illustrate the usage of// fmt.Sscanf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var boolean_value bool // Calling the Sscanf() function which // returns the number of elements // successfully parsed and error if // it persists n, err := fmt.Sscanf("GeeksforGeeks 13 6.7 true", "%s %d %g %t", &name, &alphabet_count, &float_value, &boolean_value) // Below statements get executed // if there is any error if err != nil { panic(err) } // Printing the number of elements // and each elements also fmt.Printf("%d: %s, %d, %g, %t", n, name, alphabet_count, float_value, boolean_value) } Output: 4: GeeksforGeeks, 13, 6.7, true Golang-fmt Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go How to Split a String in Golang? fmt.Sprintf() Function in Golang With Examples Golang Maps Slices in Golang Interfaces in Golang Inheritance in GoLang Different Ways to Find the Type of Variable in Golang How to Trim a String in Golang?
[ { "code": null, "e": 25787, "s": 25759, "text": "\n05 May, 2020" }, { "code": null, "e": 26209, "s": 25787, "text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sscanf() function in Go language scans the specified string and stores the successive space-separated values into successive arguments as determined by the format. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions." }, { "code": null, "e": 26217, "s": 26209, "text": "Syntax:" }, { "code": null, "e": 26294, "s": 26217, "text": "func Sscanf(str string, format string, a ...interface{}) (n int, err error)\n" }, { "code": null, "e": 26374, "s": 26294, "text": "Parameters: This function accepts three parameters which are illustrated below:" }, { "code": null, "e": 26459, "s": 26374, "text": "str string: This parameter contains the specified text which is going to be scanned." }, { "code": null, "e": 26565, "s": 26459, "text": "format string: This parameter is the different types of format for each elements of the specified string." }, { "code": null, "e": 26636, "s": 26565, "text": "a ...interface{}: This parameter receives each elements of the string." }, { "code": null, "e": 26697, "s": 26636, "text": "Returns: It returns the number of items successfully parsed." }, { "code": null, "e": 26708, "s": 26697, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// fmt.Sscanf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring two variables var name string var alphabet_count int // Calling the Sscanf() function which // returns the number of elements // successfully parsed and error if // it persists n, err := fmt.Sscanf(\"GFG is having 3 alphabets.\", \"%s is having %d alphabets.\", &name, &alphabet_count) // Below statements get // executed if there is any error if err != nil { panic(err) } // Printing the number of // elements and each elements also fmt.Printf(\"%d: %s, %d\\n\", n, name, alphabet_count) }", "e": 27451, "s": 26708, "text": null }, { "code": null, "e": 27459, "s": 27451, "text": "Output:" }, { "code": null, "e": 27470, "s": 27459, "text": "2: GFG, 3\n" }, { "code": null, "e": 27481, "s": 27470, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// fmt.Sscanf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var boolean_value bool // Calling the Sscanf() function which // returns the number of elements // successfully parsed and error if // it persists n, err := fmt.Sscanf(\"GeeksforGeeks 13 6.7 true\", \"%s %d %g %t\", &name, &alphabet_count, &float_value, &boolean_value) // Below statements get executed // if there is any error if err != nil { panic(err) } // Printing the number of elements // and each elements also fmt.Printf(\"%d: %s, %d, %g, %t\", n, name, alphabet_count, float_value, boolean_value) }", "e": 28362, "s": 27481, "text": null }, { "code": null, "e": 28370, "s": 28362, "text": "Output:" }, { "code": null, "e": 28403, "s": 28370, "text": "4: GeeksforGeeks, 13, 6.7, true\n" }, { "code": null, "e": 28414, "s": 28403, "text": "Golang-fmt" }, { "code": null, "e": 28426, "s": 28414, "text": "Go Language" }, { "code": null, "e": 28524, "s": 28426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28575, "s": 28524, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28588, "s": 28575, "text": "Arrays in Go" }, { "code": null, "e": 28621, "s": 28588, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28668, "s": 28621, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 28680, "s": 28668, "text": "Golang Maps" }, { "code": null, "e": 28697, "s": 28680, "text": "Slices in Golang" }, { "code": null, "e": 28718, "s": 28697, "text": "Interfaces in Golang" }, { "code": null, "e": 28740, "s": 28718, "text": "Inheritance in GoLang" }, { "code": null, "e": 28794, "s": 28740, "text": "Different Ways to Find the Type of Variable in Golang" } ]
C# | Get or set the value associated with specified key in SortedList - GeeksforGeeks
01 Feb, 2019 SortedList.Item[Object] Property is used to get and set the value associated with a specific key in a SortedList object. Syntax: public virtual object this[object key] { get; set; } Here, the key is associated with the value to get or set. It is of the object type. Return Value: This property returns the value associated with the key parameter in the SortedList object if the key is found otherwise it returns null. Exceptions: ArgumentNullException: If the key is null. NotSupportedException: If the property is set and the SortedList object is read-only or if the property is set, the key doesn’t exist in the collection and the SortedList has a fixed size. OutOfMemoryException: If there is not enough available memory to add the element to the SortedList. InvalidOperationException: If the comparer throws an exception. Below programs illustrate the use of above-discussed property: Example 1: // C# code to Gets or sets the value // associated with the specified key using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a SortedList SortedList mylist = new SortedList(); // Adding elements in SortedList mylist.Add("g", "geeks"); mylist.Add("c", "c++"); mylist.Add("d", "data structures"); mylist.Add("q", "quiz"); // Get a collection of the keys. ICollection c = mylist.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + mylist[str]); // Setting the value associated with key "c" mylist["c"] = "C#"; Console.WriteLine("Updated Values:"); // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + mylist[str]); } } c: c++ d: data structures g: geeks q: quiz Updated Values: c: C# d: data structures g: geeks q: quiz Example 2: // C# code to Gets or sets the value // associated with the specified key using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a SortedList SortedList mylist = new SortedList(); // Adding elements in SortedList mylist.Add("4", "Even"); mylist.Add("9", "Odd"); mylist.Add("5", "Odd and Prime"); mylist.Add("2", "Even and Prime"); // Get a collection of the keys. ICollection c = mylist.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + mylist[str]); // Setting the value associated // with key "56" which is not present // will result in the creation of // new key and value will be set which // is given by the user mylist["56"] = "New Value"; Console.WriteLine("Updated Values:"); // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + mylist[str]); // Setting the value associated // with key "28" which is not present // will result in the creation of // new key and its value can be null mylist["28"] = null; Console.WriteLine("Updated Values:"); // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + mylist[str]); } } 2: Even and Prime 4: Even 5: Odd and Prime 9: Odd Updated Values: 2: Even and Prime 4: Even 5: Odd and Prime 56: New Value 9: Odd Updated Values: 2: Even and Prime 28: 4: Even 5: Odd and Prime 56: New Value 9: Odd Note: This property returns the value associated with the specific key. If that key is not found, and one is trying to get that, then this property will return null and if trying to set, it will result into the creation of a new element with the specified key. A key cannot be null, but a value can be. To distinguish between null that is returned because the specified key is not found and null that is returned because the value of the specified key is null, use the Contains method or the ContainsKey method to determine if the key exists in the list. Retrieving the value of this property is an O(log n) operation, where n is Count. Setting the property is an O(log n) operation if the key is already in the SortedList. If the key is not in the list, setting the property is an O(n) operation for unsorted data, or O(log n) if the new element is added at the end of the list. If insertion causes a resize, the operation is O(n). Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.item?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-SortedList C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# C# | Replace() Method Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object C# | Constructors Introduction to .NET Framework
[ { "code": null, "e": 26173, "s": 26145, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26294, "s": 26173, "text": "SortedList.Item[Object] Property is used to get and set the value associated with a specific key in a SortedList object." }, { "code": null, "e": 26302, "s": 26294, "text": "Syntax:" }, { "code": null, "e": 26355, "s": 26302, "text": "public virtual object this[object key] { get; set; }" }, { "code": null, "e": 26439, "s": 26355, "text": "Here, the key is associated with the value to get or set. It is of the object type." }, { "code": null, "e": 26591, "s": 26439, "text": "Return Value: This property returns the value associated with the key parameter in the SortedList object if the key is found otherwise it returns null." }, { "code": null, "e": 26603, "s": 26591, "text": "Exceptions:" }, { "code": null, "e": 26646, "s": 26603, "text": "ArgumentNullException: If the key is null." }, { "code": null, "e": 26835, "s": 26646, "text": "NotSupportedException: If the property is set and the SortedList object is read-only or if the property is set, the key doesn’t exist in the collection and the SortedList has a fixed size." }, { "code": null, "e": 26935, "s": 26835, "text": "OutOfMemoryException: If there is not enough available memory to add the element to the SortedList." }, { "code": null, "e": 26999, "s": 26935, "text": "InvalidOperationException: If the comparer throws an exception." }, { "code": null, "e": 27062, "s": 26999, "text": "Below programs illustrate the use of above-discussed property:" }, { "code": null, "e": 27073, "s": 27062, "text": "Example 1:" }, { "code": "// C# code to Gets or sets the value // associated with the specified key using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a SortedList SortedList mylist = new SortedList(); // Adding elements in SortedList mylist.Add(\"g\", \"geeks\"); mylist.Add(\"c\", \"c++\"); mylist.Add(\"d\", \"data structures\"); mylist.Add(\"q\", \"quiz\"); // Get a collection of the keys. ICollection c = mylist.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + mylist[str]); // Setting the value associated with key \"c\" mylist[\"c\"] = \"C#\"; Console.WriteLine(\"Updated Values:\"); // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + mylist[str]); } } ", "e": 27998, "s": 27073, "text": null }, { "code": null, "e": 28100, "s": 27998, "text": "c: c++\nd: data structures\ng: geeks\nq: quiz\nUpdated Values:\nc: C#\nd: data structures\ng: geeks\nq: quiz\n" }, { "code": null, "e": 28111, "s": 28100, "text": "Example 2:" }, { "code": "// C# code to Gets or sets the value // associated with the specified key using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a SortedList SortedList mylist = new SortedList(); // Adding elements in SortedList mylist.Add(\"4\", \"Even\"); mylist.Add(\"9\", \"Odd\"); mylist.Add(\"5\", \"Odd and Prime\"); mylist.Add(\"2\", \"Even and Prime\"); // Get a collection of the keys. ICollection c = mylist.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + mylist[str]); // Setting the value associated // with key \"56\" which is not present // will result in the creation of // new key and value will be set which // is given by the user mylist[\"56\"] = \"New Value\"; Console.WriteLine(\"Updated Values:\"); // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + mylist[str]); // Setting the value associated // with key \"28\" which is not present // will result in the creation of // new key and its value can be null mylist[\"28\"] = null; Console.WriteLine(\"Updated Values:\"); // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + mylist[str]); } } ", "e": 29636, "s": 28111, "text": null }, { "code": null, "e": 29852, "s": 29636, "text": "2: Even and Prime\n4: Even\n5: Odd and Prime\n9: Odd\nUpdated Values:\n2: Even and Prime\n4: Even\n5: Odd and Prime\n56: New Value\n9: Odd\nUpdated Values:\n2: Even and Prime\n28: \n4: Even\n5: Odd and Prime\n56: New Value\n9: Odd\n" }, { "code": null, "e": 29858, "s": 29852, "text": "Note:" }, { "code": null, "e": 30113, "s": 29858, "text": "This property returns the value associated with the specific key. If that key is not found, and one is trying to get that, then this property will return null and if trying to set, it will result into the creation of a new element with the specified key." }, { "code": null, "e": 30407, "s": 30113, "text": "A key cannot be null, but a value can be. To distinguish between null that is returned because the specified key is not found and null that is returned because the value of the specified key is null, use the Contains method or the ContainsKey method to determine if the key exists in the list." }, { "code": null, "e": 30785, "s": 30407, "text": "Retrieving the value of this property is an O(log n) operation, where n is Count. Setting the property is an O(log n) operation if the key is already in the SortedList. If the key is not in the list, setting the property is an O(n) operation for unsorted data, or O(log n) if the new element is added at the end of the list. If insertion causes a resize, the operation is O(n)." }, { "code": null, "e": 30796, "s": 30785, "text": "Reference:" }, { "code": null, "e": 30899, "s": 30796, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.item?view=netframework-4.7.2" }, { "code": null, "e": 30928, "s": 30899, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 30958, "s": 30928, "text": "CSharp-Collections-SortedList" }, { "code": null, "e": 30961, "s": 30958, "text": "C#" }, { "code": null, "e": 31059, "s": 30961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31074, "s": 31059, "text": "C# | Delegates" }, { "code": null, "e": 31097, "s": 31074, "text": "C# | Method Overriding" }, { "code": null, "e": 31119, "s": 31097, "text": "C# | Abstract Classes" }, { "code": null, "e": 31165, "s": 31119, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 31187, "s": 31165, "text": "C# | Replace() Method" }, { "code": null, "e": 31210, "s": 31187, "text": "Extension Method in C#" }, { "code": null, "e": 31250, "s": 31210, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 31272, "s": 31250, "text": "C# | Class and Object" }, { "code": null, "e": 31290, "s": 31272, "text": "C# | Constructors" } ]
What is the return type of a “count” query against MySQL using Java JDBC?
The return type of count is long. The Java statement is as follows rs.next(); long result= rs.getLong("anyAliasName"); First, create a table with some records in our sample database test3. The query to create a table is as follows mysql> create table CountDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.60 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into CountDemo(Name) values('John'); Query OK, 1 row affected (0.21 sec) mysql> insert into CountDemo(Name) values('Carol'); Query OK, 1 row affected (0.16 sec) mysql> insert into CountDemo(Name) values('Bob'); Query OK, 1 row affected (0.19 sec) mysql> insert into CountDemo(Name) values('David'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement. The query is as follows mysql> select *from CountDemo; The following is the output +----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | David | +----+-------+ 4 rows in set (0.00 sec) Here is the Java code return type of a “count” query against MySQL using Java JDBC import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ReturnTypeOfCount { public static void main(String[] args) { Connection con=null; Statement st=null; ResultSet rs=null; try { con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test3?useSSL=false", "root","123456"); String yourQuery = "SELECT COUNT(*) AS totalCount FROM CountDemo"; st = con.createStatement(); rs = st.executeQuery(yourQuery); rs.next(); long result= rs.getLong("totalCount"); System.out.println("Total Count="+result); } catch(Exception e) { e.printStackTrace(); } } } The following is the output Total Count=4 Here is the snapshot of the output:
[ { "code": null, "e": 1129, "s": 1062, "text": "The return type of count is long. The Java statement is as follows" }, { "code": null, "e": 1181, "s": 1129, "text": "rs.next();\nlong result= rs.getLong(\"anyAliasName\");" }, { "code": null, "e": 1293, "s": 1181, "text": "First, create a table with some records in our sample database test3. The query to create a table is as follows" }, { "code": null, "e": 1450, "s": 1293, "text": "mysql> create table CountDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1505, "s": 1450, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1529, "s": 1505, "text": "The query is as follows" }, { "code": null, "e": 1878, "s": 1529, "text": "mysql> insert into CountDemo(Name) values('John');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into CountDemo(Name) values('Carol');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into CountDemo(Name) values('Bob');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into CountDemo(Name) values('David');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1937, "s": 1878, "text": "Display all records from the table using select statement." }, { "code": null, "e": 1961, "s": 1937, "text": "The query is as follows" }, { "code": null, "e": 1992, "s": 1961, "text": "mysql> select *from CountDemo;" }, { "code": null, "e": 2020, "s": 1992, "text": "The following is the output" }, { "code": null, "e": 2165, "s": 2020, "text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n| 4 | David |\n+----+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2248, "s": 2165, "text": "Here is the Java code return type of a “count” query against MySQL using Java JDBC" }, { "code": null, "e": 2994, "s": 2248, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class ReturnTypeOfCount {\n public static void main(String[] args) {\n Connection con=null;\n Statement st=null;\n ResultSet rs=null;\n try {\n con=DriverManager.getConnection(\"jdbc:mysql://localhost:3306/test3?useSSL=false\",\n \"root\",\"123456\");\n String yourQuery = \"SELECT COUNT(*) AS totalCount FROM CountDemo\";\n st = con.createStatement();\n rs = st.executeQuery(yourQuery);\n rs.next();\n long result= rs.getLong(\"totalCount\");\n System.out.println(\"Total Count=\"+result);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 3022, "s": 2994, "text": "The following is the output" }, { "code": null, "e": 3072, "s": 3022, "text": "Total Count=4\nHere is the snapshot of the output:" } ]