title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Shell Script to Demonstrate Special Parameters With Example - GeeksforGeeks
20 Apr, 2021 Here, we are going to see what are the special Parameters of the shell script. Before that first, let’s understand what is parameters in the shell. The parameter is the entity that stores the value. The variables are the parameters that are defined by the user to use in that specific shell script. And the Special parameters are the read-only variables that are predefined and maintained by the shell. Now let’s see what are the Special parameters in the bash shell. This parameter represents the current flags set in your shell .himBH are the flags in bash shell. Where: H – histexpand m – monitor h – hashall B – braceexpand i – interactive Now let’s see the script which demonstrates all Special Parameters. #!/bin/bash echo "Number of argument passed: $#" echo "Script name is $0" echo "The 2nd argument passed is: $2" echo "Arguments passed to script are: $*" echo "Exit status of last command that executed:$?" #This is the previous command for $_ echo "Last argument provide to previous command:$_" echo "PID of current shell is: $$" echo "Flags are set in the shell: $-" Now let’s see the output of the above script: Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n20 Apr, 2021" }, { "code": null, "e": 26119, "s": 25651, "text": "Here, we are going to see what are the special Parameters of the shell script. Before that first, let’s understand what is parameters in the shell. The parameter is the entity that stores the value. The variables are the parameters that are defined by the user to use in that specific shell script. And the Special parameters are the read-only variables that are predefined and maintained by the shell. Now let’s see what are the Special parameters in the bash shell." }, { "code": null, "e": 26217, "s": 26119, "text": "This parameter represents the current flags set in your shell .himBH are the flags in bash shell." }, { "code": null, "e": 26224, "s": 26217, "text": "Where:" }, { "code": null, "e": 26239, "s": 26224, "text": "H – histexpand" }, { "code": null, "e": 26251, "s": 26239, "text": "m – monitor" }, { "code": null, "e": 26263, "s": 26251, "text": "h – hashall" }, { "code": null, "e": 26279, "s": 26263, "text": "B – braceexpand" }, { "code": null, "e": 26295, "s": 26279, "text": "i – interactive" }, { "code": null, "e": 26363, "s": 26295, "text": "Now let’s see the script which demonstrates all Special Parameters." }, { "code": null, "e": 26732, "s": 26363, "text": "#!/bin/bash\n\necho \"Number of argument passed: $#\"\necho \"Script name is $0\"\necho \"The 2nd argument passed is: $2\"\necho \"Arguments passed to script are: $*\"\necho \"Exit status of last command that executed:$?\" #This is the previous command for $_\necho \"Last argument provide to previous command:$_\"\necho \"PID of current shell is: $$\"\necho \"Flags are set in the shell: $-\"" }, { "code": null, "e": 26778, "s": 26732, "text": "Now let’s see the output of the above script:" }, { "code": null, "e": 26785, "s": 26778, "text": "Picked" }, { "code": null, "e": 26798, "s": 26785, "text": "Shell Script" }, { "code": null, "e": 26809, "s": 26798, "text": "Linux-Unix" }, { "code": null, "e": 26907, "s": 26809, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26942, "s": 26907, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26976, "s": 26942, "text": "mv command in Linux with examples" }, { "code": null, "e": 27002, "s": 26976, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27031, "s": 27002, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27068, "s": 27031, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27105, "s": 27068, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27147, "s": 27105, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27173, "s": 27147, "text": "Thread functions in C/C++" }, { "code": null, "e": 27209, "s": 27173, "text": "uniq Command in LINUX with examples" } ]
ConcurrentSkipListMap in Java with Examples - GeeksforGeeks
24 Nov, 2020 The ConcurrentSkipListMap class is a member of the Java Collections Framework. It was introduced in JDK 1.6, it belongs to java.util.concurrent package. The ConcurrentSkipListMap is a scalable implementation of ConcurrentNavigableMap. All the elements are sorted based on natural ordering or by the Comparator passed during it’s construction time. This class uses a concurrent variation of SkipList data structure providing log(n) time cost for insertion, removal, update, and access operations. These operations are safe for executing concurrently by multiple threads. Declaration public class ConcurrentSkipListMap<K,​V> extends AbstractMap<K,​V> implements ConcurrentNavigableMap<K,​V>, Cloneable, Serializable Here, K is the key Object type and V is the value Object type. The Hierarchy of ConcurrentSkipListMap It implements Serializable, Cloneable, ConcurrentMap<K,​V>, ConcurrentNavigableMap<K,​V>, Map<K,​V>, NavigableMap<K,​V>, SortedMap<K,​V> interfaces and extends AbstractMap<K, V> class. 1. ConcurrentSkipListMap(): Constructs a new, empty map, sorted according to the natural ordering of the keys. ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap<K, V>(); 2. ConcurrentSkipListMap​(Comparator<? super K> comparator): Constructs a new, empty map, sorted according to the specified comparator. ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap​<K, V>(Comparator<? super K> comparator); 3. ConcurrentSkipListMap​(Map<? extends K,​? extends V> m): Constructs a new map containing the same mappings as the given map, sorted according to the natural ordering of the keys.​ ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap<K, V>​(Map<? extends K,​? extends V> m); 4. ConcurrentSkipListMap​(SortedMap<K,​? extends V> m): Constructs a new map containing the same mappings and using the same ordering as the specified sorted map. ConcurrentSkipListMap​<K, V> cslm = new ConcurrentSkipListMap​<K, V>(SortedMap<K,​? extends V> m); Example Java // Java Program to Demonstrate// ConcurrentSkipListMap import java.io.*;import java.util.*;import java.util.concurrent.*; class ConcurrentSkipListMapExample { public static void main(String[] args) { // create an instance of ConcurrentSkipListMap ConcurrentSkipListMap<String, String> cslm = new ConcurrentSkipListMap<String, String>(); // Add mappings using put method cslm.put("3", "Geeks"); cslm.put("2", "from"); cslm.put("1", "Hi!"); cslm.put("5", "Geeks"); cslm.put("4", "for"); // print to the console System.out.println("Initial Map : " + cslm); // print key-value pair whose key is greater than 2 System.out.println("ceilingEntry-2: " + cslm.ceilingEntry("2")); // get the descending key set NavigableSet navigableSet = cslm.descendingKeySet(); System.out.println("descendingKeySet: "); // Iterate through the keySet Iterator itr = navigableSet.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); } // print the first mapping System.out.println("firstEntry: " + cslm.firstEntry()); // print the last mapping System.out.println("lastEntry: " + cslm.lastEntry()); // remove the first mapping and print it System.out.println("pollFirstEntry: " + cslm.pollFirstEntry()); // print the first mapping System.out.println("now firstEntry: " + cslm.firstEntry()); // remove the last mapping and print it System.out.println("pollLastEntry: " + cslm.pollLastEntry()); // print the last mapping System.out.println("now lastEntry: " + cslm.lastEntry()); }} Initial Map : {1=Hi!, 2=from, 3=Geeks, 4=for, 5=Geeks} ceilingEntry-2: 2=from descendingKeySet: 5 4 3 2 1 firstEntry: 1=Hi! lastEntry: 5=Geeks pollFirstEntry: 1=Hi! now firstEntry: 2=from pollLastEntry: 5=Geeks now lastEntry: 4=for 1. Add Mappings The put() method of ConcurrentSkipListMap associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. Java // Java Program to demonstrate adding// mappings to a ConcurrentSkipListMap import java.util.concurrent.*; class AddingMappingsExample { public static void main(String[] args) { // Initializing the map ConcurrentSkipListMap<Integer, Integer> cslm = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map for (int i = 1; i <= 9; i++) cslm.put(i, i); // put() operation on the map System.out.println("After put(): " + cslm); }} After put(): {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9} 2. Remove Mappings The remove() method of ConcurrentSkipListMap removes the mapping for the specified key from this map. The method returns null if there is no mapping for of that particular key. After this method is performed the size of the map is reduced. To remove the first entry and last entry of the map, we can use pollFirstEntry() and pollLastEntry() respectively. Java // Java Program Demonstrate removing// mappings from ConcurrentSkipListMap import java.util.concurrent.*; class RemovingMappingsExample { public static void main(String[] args) { // Initializing the map ConcurrentSkipListMap<Integer, Integer> cslm = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map for (int i = 1; i <= 6; i++) cslm.put(i, i); // remove() operation on the map cslm.remove(5); // print the modified map System.out.println("After remove(): " + cslm); // remove the first mapping and print it System.out.println("pollFirstEntry: " + cslm.pollFirstEntry()); // remove the last mapping and print it System.out.println("pollLastEntry: " + cslm.pollLastEntry()); // Print final map System.out.println("map contents: " + cslm); }} After remove(): {1=1, 2=2, 3=3, 4=4, 6=6} pollFirstEntry: 1=1 pollLastEntry: 6=6 map contents: {2=2, 3=3, 4=4} 3. Iterating We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentSkipListMap. Java // Java Program to demonstrate iterating// over ConcurrentSkipListMap import java.util.concurrent.*;import java.util.*; class IteratingExample { public static void main(String[] args) { // create an instance of ConcurrentSkipListMap ConcurrentSkipListMap<Integer, Integer> cslm = new ConcurrentSkipListMap<>(); // Add mappings using put method for (int i = 0; i < 6; i++) { cslm.put(i, i); } // Create an Iterator over the // ConcurrentSkipListMap Iterator<ConcurrentSkipListMap .Entry<Integer, Integer> > itr = cslm.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentSkipListMap .Entry<Integer, Integer> entry = itr.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }} Key = 0, Value = 0 Key = 1, Value = 1 Key = 2, Value = 2 Key = 3, Value = 3 Key = 4, Value = 4 Key = 5, Value = 5 METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html Java-Collections Java-ConcurrentSkipListMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25251, "s": 25223, "text": "\n24 Nov, 2020" }, { "code": null, "e": 25822, "s": 25251, "text": "The ConcurrentSkipListMap class is a member of the Java Collections Framework. It was introduced in JDK 1.6, it belongs to java.util.concurrent package. The ConcurrentSkipListMap is a scalable implementation of ConcurrentNavigableMap. All the elements are sorted based on natural ordering or by the Comparator passed during it’s construction time. This class uses a concurrent variation of SkipList data structure providing log(n) time cost for insertion, removal, update, and access operations. These operations are safe for executing concurrently by multiple threads. " }, { "code": null, "e": 25834, "s": 25822, "text": "Declaration" }, { "code": null, "e": 25966, "s": 25834, "text": "public class ConcurrentSkipListMap<K,​V> extends AbstractMap<K,​V> implements ConcurrentNavigableMap<K,​V>, Cloneable, Serializable" }, { "code": null, "e": 26029, "s": 25966, "text": "Here, K is the key Object type and V is the value Object type." }, { "code": null, "e": 26068, "s": 26029, "text": "The Hierarchy of ConcurrentSkipListMap" }, { "code": null, "e": 26253, "s": 26068, "text": "It implements Serializable, Cloneable, ConcurrentMap<K,​V>, ConcurrentNavigableMap<K,​V>, Map<K,​V>, NavigableMap<K,​V>, SortedMap<K,​V> interfaces and extends AbstractMap<K, V> class." }, { "code": null, "e": 26364, "s": 26253, "text": "1. ConcurrentSkipListMap(): Constructs a new, empty map, sorted according to the natural ordering of the keys." }, { "code": null, "e": 26434, "s": 26364, "text": "ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap<K, V>();" }, { "code": null, "e": 26570, "s": 26434, "text": "2. ConcurrentSkipListMap​(Comparator<? super K> comparator): Constructs a new, empty map, sorted according to the specified comparator." }, { "code": null, "e": 26673, "s": 26570, "text": "ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap​<K, V>(Comparator<? super K> comparator);" }, { "code": null, "e": 26856, "s": 26673, "text": "3. ConcurrentSkipListMap​(Map<? extends K,​? extends V> m): Constructs a new map containing the same mappings as the given map, sorted according to the natural ordering of the keys.​" }, { "code": null, "e": 26958, "s": 26856, "text": "ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap<K, V>​(Map<? extends K,​? extends V> m);" }, { "code": null, "e": 27121, "s": 26958, "text": "4. ConcurrentSkipListMap​(SortedMap<K,​? extends V> m): Constructs a new map containing the same mappings and using the same ordering as the specified sorted map." }, { "code": null, "e": 27220, "s": 27121, "text": "ConcurrentSkipListMap​<K, V> cslm = new ConcurrentSkipListMap​<K, V>(SortedMap<K,​? extends V> m);" }, { "code": null, "e": 27228, "s": 27220, "text": "Example" }, { "code": null, "e": 27233, "s": 27228, "text": "Java" }, { "code": "// Java Program to Demonstrate// ConcurrentSkipListMap import java.io.*;import java.util.*;import java.util.concurrent.*; class ConcurrentSkipListMapExample { public static void main(String[] args) { // create an instance of ConcurrentSkipListMap ConcurrentSkipListMap<String, String> cslm = new ConcurrentSkipListMap<String, String>(); // Add mappings using put method cslm.put(\"3\", \"Geeks\"); cslm.put(\"2\", \"from\"); cslm.put(\"1\", \"Hi!\"); cslm.put(\"5\", \"Geeks\"); cslm.put(\"4\", \"for\"); // print to the console System.out.println(\"Initial Map : \" + cslm); // print key-value pair whose key is greater than 2 System.out.println(\"ceilingEntry-2: \" + cslm.ceilingEntry(\"2\")); // get the descending key set NavigableSet navigableSet = cslm.descendingKeySet(); System.out.println(\"descendingKeySet: \"); // Iterate through the keySet Iterator itr = navigableSet.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); } // print the first mapping System.out.println(\"firstEntry: \" + cslm.firstEntry()); // print the last mapping System.out.println(\"lastEntry: \" + cslm.lastEntry()); // remove the first mapping and print it System.out.println(\"pollFirstEntry: \" + cslm.pollFirstEntry()); // print the first mapping System.out.println(\"now firstEntry: \" + cslm.firstEntry()); // remove the last mapping and print it System.out.println(\"pollLastEntry: \" + cslm.pollLastEntry()); // print the last mapping System.out.println(\"now lastEntry: \" + cslm.lastEntry()); }}", "e": 29190, "s": 27233, "text": null }, { "code": null, "e": 29423, "s": 29190, "text": "Initial Map : {1=Hi!, 2=from, 3=Geeks, 4=for, 5=Geeks}\nceilingEntry-2: 2=from\ndescendingKeySet: \n5\n4\n3\n2\n1\nfirstEntry: 1=Hi!\nlastEntry: 5=Geeks\npollFirstEntry: 1=Hi!\nnow firstEntry: 2=from\npollLastEntry: 5=Geeks\nnow lastEntry: 4=for" }, { "code": null, "e": 29439, "s": 29423, "text": "1. Add Mappings" }, { "code": null, "e": 29630, "s": 29439, "text": "The put() method of ConcurrentSkipListMap associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced." }, { "code": null, "e": 29635, "s": 29630, "text": "Java" }, { "code": "// Java Program to demonstrate adding// mappings to a ConcurrentSkipListMap import java.util.concurrent.*; class AddingMappingsExample { public static void main(String[] args) { // Initializing the map ConcurrentSkipListMap<Integer, Integer> cslm = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map for (int i = 1; i <= 9; i++) cslm.put(i, i); // put() operation on the map System.out.println(\"After put(): \" + cslm); }}", "e": 30165, "s": 29635, "text": null }, { "code": null, "e": 30224, "s": 30165, "text": "After put(): {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}" }, { "code": null, "e": 30243, "s": 30224, "text": "2. Remove Mappings" }, { "code": null, "e": 30598, "s": 30243, "text": "The remove() method of ConcurrentSkipListMap removes the mapping for the specified key from this map. The method returns null if there is no mapping for of that particular key. After this method is performed the size of the map is reduced. To remove the first entry and last entry of the map, we can use pollFirstEntry() and pollLastEntry() respectively." }, { "code": null, "e": 30603, "s": 30598, "text": "Java" }, { "code": "// Java Program Demonstrate removing// mappings from ConcurrentSkipListMap import java.util.concurrent.*; class RemovingMappingsExample { public static void main(String[] args) { // Initializing the map ConcurrentSkipListMap<Integer, Integer> cslm = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map for (int i = 1; i <= 6; i++) cslm.put(i, i); // remove() operation on the map cslm.remove(5); // print the modified map System.out.println(\"After remove(): \" + cslm); // remove the first mapping and print it System.out.println(\"pollFirstEntry: \" + cslm.pollFirstEntry()); // remove the last mapping and print it System.out.println(\"pollLastEntry: \" + cslm.pollLastEntry()); // Print final map System.out.println(\"map contents: \" + cslm); }}", "e": 31583, "s": 30603, "text": null }, { "code": null, "e": 31694, "s": 31583, "text": "After remove(): {1=1, 2=2, 3=3, 4=4, 6=6}\npollFirstEntry: 1=1\npollLastEntry: 6=6\nmap contents: {2=2, 3=3, 4=4}" }, { "code": null, "e": 31708, "s": 31694, "text": " 3. Iterating" }, { "code": null, "e": 32008, "s": 31708, "text": "We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentSkipListMap." }, { "code": null, "e": 32013, "s": 32008, "text": "Java" }, { "code": "// Java Program to demonstrate iterating// over ConcurrentSkipListMap import java.util.concurrent.*;import java.util.*; class IteratingExample { public static void main(String[] args) { // create an instance of ConcurrentSkipListMap ConcurrentSkipListMap<Integer, Integer> cslm = new ConcurrentSkipListMap<>(); // Add mappings using put method for (int i = 0; i < 6; i++) { cslm.put(i, i); } // Create an Iterator over the // ConcurrentSkipListMap Iterator<ConcurrentSkipListMap .Entry<Integer, Integer> > itr = cslm.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentSkipListMap .Entry<Integer, Integer> entry = itr.next(); System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } }}", "e": 33132, "s": 32013, "text": null }, { "code": null, "e": 33246, "s": 33132, "text": "Key = 0, Value = 0\nKey = 1, Value = 1\nKey = 2, Value = 2\nKey = 3, Value = 3\nKey = 4, Value = 4\nKey = 5, Value = 5" }, { "code": null, "e": 33253, "s": 33246, "text": "METHOD" }, { "code": null, "e": 33265, "s": 33253, "text": "DESCRIPTION" }, { "code": null, "e": 33272, "s": 33265, "text": "METHOD" }, { "code": null, "e": 33284, "s": 33272, "text": "DESCRIPTION" }, { "code": null, "e": 33291, "s": 33284, "text": "METHOD" }, { "code": null, "e": 33303, "s": 33291, "text": "DESCRIPTION" }, { "code": null, "e": 33310, "s": 33303, "text": "METHOD" }, { "code": null, "e": 33322, "s": 33310, "text": "DESCRIPTION" }, { "code": null, "e": 33329, "s": 33322, "text": "METHOD" }, { "code": null, "e": 33341, "s": 33329, "text": "DESCRIPTION" }, { "code": null, "e": 33348, "s": 33341, "text": "METHOD" }, { "code": null, "e": 33360, "s": 33348, "text": "DESCRIPTION" }, { "code": null, "e": 33480, "s": 33360, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html" }, { "code": null, "e": 33497, "s": 33480, "text": "Java-Collections" }, { "code": null, "e": 33524, "s": 33497, "text": "Java-ConcurrentSkipListMap" }, { "code": null, "e": 33529, "s": 33524, "text": "Java" }, { "code": null, "e": 33534, "s": 33529, "text": "Java" }, { "code": null, "e": 33551, "s": 33534, "text": "Java-Collections" }, { "code": null, "e": 33649, "s": 33551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33664, "s": 33649, "text": "Stream In Java" }, { "code": null, "e": 33685, "s": 33664, "text": "Constructors in Java" }, { "code": null, "e": 33704, "s": 33685, "text": "Exceptions in Java" }, { "code": null, "e": 33734, "s": 33704, "text": "Functional Interfaces in Java" }, { "code": null, "e": 33780, "s": 33734, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 33797, "s": 33780, "text": "Generics in Java" }, { "code": null, "e": 33818, "s": 33797, "text": "Introduction to Java" }, { "code": null, "e": 33861, "s": 33818, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 33897, "s": 33861, "text": "Internal Working of HashMap in Java" } ]
How to Install Scala on MacOS? - GeeksforGeeks
30 Nov, 2021 In this article, we are going to show you how you can download and install Scala on your Mac operating system. First of all, you need to download the Java JDK which you can download here Follow the below steps to install Scala on MacOS: Step 1: After installing JDK, run the following commands and make sure they don’t return an error : javac -version java -version Step 2: Now, we need to download and install scala download the binary file from the official-website Step 3: After downloading it you’ll have to extract it from the command line. And make sure to extract it in the root directory tar -zxvf scala-2.12.8.tgz Step 4: After extracting run the following command sudo cp -R scala-X.XX /usr/local/scala When you run this command the output like where you’ll find folders like bin, doc, lib, man. Step 5: Open your .bash_profile file and run the following command : sudo nano ~/.bash_profile Step 6: The following step is to change or add environment variables. Replace USERNAME with your actual username, but make sure your file location is right. export SCALA_HOME="/Users/USERNAME/scala-2.12.6" export PATH=$PATH:$SCALA_HOME/bin Step 7: Save and Restart the terminal. Step 8: Now run the commands to check the Scala is installed properly. scalac -version scala -version how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26221, "s": 26193, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26408, "s": 26221, "text": "In this article, we are going to show you how you can download and install Scala on your Mac operating system. First of all, you need to download the Java JDK which you can download here" }, { "code": null, "e": 26458, "s": 26408, "text": "Follow the below steps to install Scala on MacOS:" }, { "code": null, "e": 26558, "s": 26458, "text": "Step 1: After installing JDK, run the following commands and make sure they don’t return an error :" }, { "code": null, "e": 26587, "s": 26558, "text": "javac -version\njava -version" }, { "code": null, "e": 26639, "s": 26587, "text": "Step 2: Now, we need to download and install scala " }, { "code": null, "e": 26690, "s": 26639, "text": "download the binary file from the official-website" }, { "code": null, "e": 26818, "s": 26690, "text": "Step 3: After downloading it you’ll have to extract it from the command line. And make sure to extract it in the root directory" }, { "code": null, "e": 26845, "s": 26818, "text": "tar -zxvf scala-2.12.8.tgz" }, { "code": null, "e": 26896, "s": 26845, "text": "Step 4: After extracting run the following command" }, { "code": null, "e": 26935, "s": 26896, "text": "sudo cp -R scala-X.XX /usr/local/scala" }, { "code": null, "e": 27028, "s": 26935, "text": "When you run this command the output like where you’ll find folders like bin, doc, lib, man." }, { "code": null, "e": 27097, "s": 27028, "text": "Step 5: Open your .bash_profile file and run the following command :" }, { "code": null, "e": 27123, "s": 27097, "text": "sudo nano ~/.bash_profile" }, { "code": null, "e": 27280, "s": 27123, "text": "Step 6: The following step is to change or add environment variables. Replace USERNAME with your actual username, but make sure your file location is right." }, { "code": null, "e": 27363, "s": 27280, "text": "export SCALA_HOME=\"/Users/USERNAME/scala-2.12.6\"\nexport PATH=$PATH:$SCALA_HOME/bin" }, { "code": null, "e": 27402, "s": 27363, "text": "Step 7: Save and Restart the terminal." }, { "code": null, "e": 27473, "s": 27402, "text": "Step 8: Now run the commands to check the Scala is installed properly." }, { "code": null, "e": 27504, "s": 27473, "text": "scalac -version\nscala -version" }, { "code": null, "e": 27519, "s": 27504, "text": "how-to-install" }, { "code": null, "e": 27526, "s": 27519, "text": "Picked" }, { "code": null, "e": 27533, "s": 27526, "text": "How To" }, { "code": null, "e": 27552, "s": 27533, "text": "Installation Guide" }, { "code": null, "e": 27650, "s": 27552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27684, "s": 27650, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27742, "s": 27684, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27791, "s": 27742, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 27838, "s": 27791, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 27880, "s": 27838, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27913, "s": 27880, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27947, "s": 27913, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27982, "s": 27947, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 28040, "s": 27982, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Why can't static methods be abstract in Java? - GeeksforGeeks
23 Aug, 2021 In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java // Java program to demonstrate// abstract static method import java.io.*; // super-class Aabstract class A { // abstract static method func // it has no body abstract static void func();} // subclass class Bclass B extends A { // class B must override func() method static void func() { System.out.println( "Static abstract" + " method implemented."); }} // Driver classpublic class Demo { public static void main(String args[]) { // Calling the abstract // static method func() B.func(); }} The above code is incorrect as static methods cannot be abstract. When run, the Compilation Error that occurs is:Compilation Error: prog.java:12: error: illegal combination of modifiers: abstract and static abstract static void func(); ^ 1 error What will happen if a static method is made abstract?Assuming we make a static method abstract. Then that method will be written as: public abstract static void func(); Scenario 1: When a method is described as abstract by using the abstract type modifier, it becomes responsibility of the subclass to implement it because they have no specified implementation in the super-class. Thus, a subclass must override them to provide method definition. Scenario 2: Now when a method is described as static, it makes it clear that this static method cannot be overridden by any subclass (It makes the static method hidden) as static members are compile-time elements and overriding them will make it runtime elements (Runtime Polymorphism). Now considering Scenario 1, if the func method is described as abstract, it must have a definition in the subclass. But according to Scenario 2, the static func method cannot be overridden in any subclass and hence it cannot have a definition then. So the scenarios seem to contradict each other. Hence our assumption for static func method to be abstract fails. Therefore, a static method cannot be abstract.Then that method will be coded as: public static void func(); Example: Java // Java program to demonstrate// abstract static method import java.io.*; // super-class Aabstract class A { // static method func static void func() { System.out.println( "Static method implemented."); } // abstract method func1 // it has no body abstract void func1();} // subclass class Bclass B extends A { // class B must override func1() method void func1() { System.out.println( "Abstract method implemented."); }} // Driver classpublic class Demo { public static void main(String args[]) { // Calling the abstract // static method func() B.func(); B b = new B(); b.func1(); }} Static method implemented. Abstract method implemented. pigenio adnanirshad158 abstract keyword Static Keyword Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25250, "s": 25222, "text": "\n23 Aug, 2021" }, { "code": null, "e": 25345, "s": 25250, "text": "In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: " }, { "code": null, "e": 25350, "s": 25345, "text": "Java" }, { "code": "// Java program to demonstrate// abstract static method import java.io.*; // super-class Aabstract class A { // abstract static method func // it has no body abstract static void func();} // subclass class Bclass B extends A { // class B must override func() method static void func() { System.out.println( \"Static abstract\" + \" method implemented.\"); }} // Driver classpublic class Demo { public static void main(String args[]) { // Calling the abstract // static method func() B.func(); }}", "e": 25925, "s": 25350, "text": null }, { "code": null, "e": 26059, "s": 25925, "text": "The above code is incorrect as static methods cannot be abstract. When run, the Compilation Error that occurs is:Compilation Error: " }, { "code": null, "e": 26202, "s": 26059, "text": "prog.java:12: error: illegal combination of modifiers: abstract and static\n abstract static void func();\n ^\n1 error" }, { "code": null, "e": 26337, "s": 26202, "text": "What will happen if a static method is made abstract?Assuming we make a static method abstract. Then that method will be written as: " }, { "code": null, "e": 26373, "s": 26337, "text": "public abstract static void func();" }, { "code": null, "e": 26655, "s": 26375, "text": "Scenario 1: When a method is described as abstract by using the abstract type modifier, it becomes responsibility of the subclass to implement it because they have no specified implementation in the super-class. Thus, a subclass must override them to provide method definition. " }, { "code": null, "e": 26946, "s": 26657, "text": "Scenario 2: Now when a method is described as static, it makes it clear that this static method cannot be overridden by any subclass (It makes the static method hidden) as static members are compile-time elements and overriding them will make it runtime elements (Runtime Polymorphism). " }, { "code": null, "e": 27392, "s": 26946, "text": "Now considering Scenario 1, if the func method is described as abstract, it must have a definition in the subclass. But according to Scenario 2, the static func method cannot be overridden in any subclass and hence it cannot have a definition then. So the scenarios seem to contradict each other. Hence our assumption for static func method to be abstract fails. Therefore, a static method cannot be abstract.Then that method will be coded as: " }, { "code": null, "e": 27419, "s": 27392, "text": "public static void func();" }, { "code": null, "e": 27430, "s": 27419, "text": "Example: " }, { "code": null, "e": 27435, "s": 27430, "text": "Java" }, { "code": "// Java program to demonstrate// abstract static method import java.io.*; // super-class Aabstract class A { // static method func static void func() { System.out.println( \"Static method implemented.\"); } // abstract method func1 // it has no body abstract void func1();} // subclass class Bclass B extends A { // class B must override func1() method void func1() { System.out.println( \"Abstract method implemented.\"); }} // Driver classpublic class Demo { public static void main(String args[]) { // Calling the abstract // static method func() B.func(); B b = new B(); b.func1(); }}", "e": 28137, "s": 27435, "text": null }, { "code": null, "e": 28193, "s": 28137, "text": "Static method implemented.\nAbstract method implemented." }, { "code": null, "e": 28203, "s": 28195, "text": "pigenio" }, { "code": null, "e": 28218, "s": 28203, "text": "adnanirshad158" }, { "code": null, "e": 28235, "s": 28218, "text": "abstract keyword" }, { "code": null, "e": 28250, "s": 28235, "text": "Static Keyword" }, { "code": null, "e": 28255, "s": 28250, "text": "Java" }, { "code": null, "e": 28260, "s": 28255, "text": "Java" }, { "code": null, "e": 28358, "s": 28260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28373, "s": 28358, "text": "Stream In Java" }, { "code": null, "e": 28394, "s": 28373, "text": "Constructors in Java" }, { "code": null, "e": 28413, "s": 28394, "text": "Exceptions in Java" }, { "code": null, "e": 28443, "s": 28413, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28489, "s": 28443, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28506, "s": 28489, "text": "Generics in Java" }, { "code": null, "e": 28527, "s": 28506, "text": "Introduction to Java" }, { "code": null, "e": 28570, "s": 28527, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28606, "s": 28570, "text": "Internal Working of HashMap in Java" } ]
Kotlin | Type Checking and Smart Casting - GeeksforGeeks
28 Mar, 2022 In Kotlin, we can check the type of certain variable using the is operator at runtime. It is a way of checking the type of a variable at runtime to separate the flow for different objects. Kotlin program of type checking using if-else blocks- Kotlin fun main(args: Array<String>) { var name = "Praveen" var age = 24 var salary = 5000.55 val employeeDetails: List<Any> = listOf(name,age,salary) for(attribute in employeeDetails) { if (attribute is String) { println("Name: $attribute") } else if (attribute is Int) { println("Age: $attribute") } else if (attribute is Double) { println("Salary: $attribute") } else { println("Not an attribute") } }} Output: Name: Praveen Age: 24 Salary: 5000.55 Explanation: Here, we initialize three variables name, age and salary then passes into the list. Then, traverse the list with help of for loop, in each if-else block we check the type of the element using is operator and execute the respective print() statement. Using when expression – We can easily replace the if-else blocks with when expression. We have already learnt about when expression in control flow articles. For more details, we can refer when expression in Kotlin. Kotlin program of type checking using when – Kotlin fun main(args: Array<String>) { var name = "Praveen" var age = 24 var salary = 5000.55 var emp_id = 12345f val employeeDetails: List<Any> = listOf(name, age, salary, emp_id) for (attribute in employeeDetails) { when (attribute) { is String -> println("Name: $attribute ") is Int -> println("Age: $attribute") is Double -> println("Salary: $attribute") else -> println("Not an attribute") } }} Output: Name: Praveen Age: 24 Salary: 5000.55 Not an attribute In Java or other programming languages, there is a requirement of explicit type casting on the variable before accessing the properties of that variable but Kotlin does a smart casting. The Kotlin compiler automatically converts the variable to a particular class reference once it’s passed through any conditional operator. Let’s take an example of Java, First of all, we check the type of the variable using the instanceOf operator and then cast it to the target type like this – Java Object ob = "GeeksforGeeks"; if(ob instanceof String) { // Explicit type casting String str = (String) ob; System.out.println("length of String " + str.length()); } In Kotlin, smart type casting is one of the most interesting features available. We use is or !is operator to check the type of variable, and compiler automatically casts the variable to the target type like this- Kotlin fun main(args: Array<String>) { val str1: String? = "GeeksforGeeks" var str2: String? = null // prints String is null if(str1 is String) { // No Explicit type Casting needed. println("length of String ${str1.length}") } else { println("String is null") }} Output: length of String 13 Use of !is Operator Similarly using !is operator we can check the variable. Kotlin fun main(args: Array<String>) { val str1: String? = "GeeksforGeeks" var str2: String? = null // prints String is null if(str1 !is String) { println("String is null") } else { println("length of String ${str1.length}") }} Output: length of String 13 Note: Smart cast don’t work when the compiler can’t guarantee that the variable cannot change between the check and the usage. Smart casts are applicable according to the following rules: val local variables always works except for local delegated properties. val properties works only if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren’t applicable to open properties or properties that have custom getters. var local variables works only if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property. var properties – never works because the variable can be modified at any time. ayushpandey3july Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android How to Add and Customize Back Button of Action Bar in Android? How to Get Current Location in Android? Kotlin Android Tutorial How to Change the Color of Status Bar in an Android App? Kotlin when expression Kotlin Higher-Order Functions
[ { "code": null, "e": 25219, "s": 25191, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25463, "s": 25219, "text": "In Kotlin, we can check the type of certain variable using the is operator at runtime. It is a way of checking the type of a variable at runtime to separate the flow for different objects. Kotlin program of type checking using if-else blocks- " }, { "code": null, "e": 25470, "s": 25463, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { var name = \"Praveen\" var age = 24 var salary = 5000.55 val employeeDetails: List<Any> = listOf(name,age,salary) for(attribute in employeeDetails) { if (attribute is String) { println(\"Name: $attribute\") } else if (attribute is Int) { println(\"Age: $attribute\") } else if (attribute is Double) { println(\"Salary: $attribute\") } else { println(\"Not an attribute\") } }}", "e": 25967, "s": 25470, "text": null }, { "code": null, "e": 25975, "s": 25967, "text": "Output:" }, { "code": null, "e": 26013, "s": 25975, "text": "Name: Praveen\nAge: 24\nSalary: 5000.55" }, { "code": null, "e": 26538, "s": 26013, "text": "Explanation: Here, we initialize three variables name, age and salary then passes into the list. Then, traverse the list with help of for loop, in each if-else block we check the type of the element using is operator and execute the respective print() statement. Using when expression – We can easily replace the if-else blocks with when expression. We have already learnt about when expression in control flow articles. For more details, we can refer when expression in Kotlin. Kotlin program of type checking using when – " }, { "code": null, "e": 26545, "s": 26538, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { var name = \"Praveen\" var age = 24 var salary = 5000.55 var emp_id = 12345f val employeeDetails: List<Any> = listOf(name, age, salary, emp_id) for (attribute in employeeDetails) { when (attribute) { is String -> println(\"Name: $attribute \") is Int -> println(\"Age: $attribute\") is Double -> println(\"Salary: $attribute\") else -> println(\"Not an attribute\") } }}", "e": 27018, "s": 26545, "text": null }, { "code": null, "e": 27026, "s": 27018, "text": "Output:" }, { "code": null, "e": 27082, "s": 27026, "text": "Name: Praveen \nAge: 24\nSalary: 5000.55\nNot an attribute" }, { "code": null, "e": 27565, "s": 27082, "text": "In Java or other programming languages, there is a requirement of explicit type casting on the variable before accessing the properties of that variable but Kotlin does a smart casting. The Kotlin compiler automatically converts the variable to a particular class reference once it’s passed through any conditional operator. Let’s take an example of Java, First of all, we check the type of the variable using the instanceOf operator and then cast it to the target type like this – " }, { "code": null, "e": 27570, "s": 27565, "text": "Java" }, { "code": "Object ob = \"GeeksforGeeks\"; if(ob instanceof String) { // Explicit type casting String str = (String) ob; System.out.println(\"length of String \" + str.length()); }", "e": 27745, "s": 27570, "text": null }, { "code": null, "e": 27960, "s": 27745, "text": "In Kotlin, smart type casting is one of the most interesting features available. We use is or !is operator to check the type of variable, and compiler automatically casts the variable to the target type like this- " }, { "code": null, "e": 27967, "s": 27960, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { val str1: String? = \"GeeksforGeeks\" var str2: String? = null // prints String is null if(str1 is String) { // No Explicit type Casting needed. println(\"length of String ${str1.length}\") } else { println(\"String is null\") }}", "e": 28272, "s": 27967, "text": null }, { "code": null, "e": 28280, "s": 28272, "text": "Output:" }, { "code": null, "e": 28300, "s": 28280, "text": "length of String 13" }, { "code": null, "e": 28377, "s": 28300, "text": "Use of !is Operator Similarly using !is operator we can check the variable. " }, { "code": null, "e": 28384, "s": 28377, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { val str1: String? = \"GeeksforGeeks\" var str2: String? = null // prints String is null if(str1 !is String) { println(\"String is null\") } else { println(\"length of String ${str1.length}\") }}", "e": 28638, "s": 28384, "text": null }, { "code": null, "e": 28646, "s": 28638, "text": "Output:" }, { "code": null, "e": 28666, "s": 28646, "text": "length of String 13" }, { "code": null, "e": 28854, "s": 28666, "text": "Note: Smart cast don’t work when the compiler can’t guarantee that the variable cannot change between the check and the usage. Smart casts are applicable according to the following rules:" }, { "code": null, "e": 28926, "s": 28854, "text": "val local variables always works except for local delegated properties." }, { "code": null, "e": 29157, "s": 28926, "text": "val properties works only if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren’t applicable to open properties or properties that have custom getters." }, { "code": null, "e": 29338, "s": 29157, "text": "var local variables works only if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property." }, { "code": null, "e": 29417, "s": 29338, "text": "var properties – never works because the variable can be modified at any time." }, { "code": null, "e": 29434, "s": 29417, "text": "ayushpandey3july" }, { "code": null, "e": 29441, "s": 29434, "text": "Kotlin" }, { "code": null, "e": 29539, "s": 29441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29582, "s": 29539, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29613, "s": 29582, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29655, "s": 29613, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29697, "s": 29655, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29760, "s": 29697, "text": "How to Add and Customize Back Button of Action Bar in Android?" }, { "code": null, "e": 29800, "s": 29760, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 29824, "s": 29800, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 29881, "s": 29824, "text": "How to Change the Color of Status Bar in an Android App?" }, { "code": null, "e": 29904, "s": 29881, "text": "Kotlin when expression" } ]
Program to check Strength of Password - GeeksforGeeks
28 Feb, 2022 A password is said to be strong if it satisfies the following criteria: It contains at least one lowercase English character.It contains at least one uppercase English character.It contains at least one special character. The special characters are: !@#$%^&*()-+Its length is at least 8.It contains at least one digit. It contains at least one lowercase English character. It contains at least one uppercase English character. It contains at least one special character. The special characters are: !@#$%^&*()-+ Its length is at least 8. It contains at least one digit. Given a string, find its strength. Let a strong password is one that satisfies all above conditions. A moderate password is one that satisfies first three conditions and has length at least 6. Otherwise password is week. Examples : Input : “GeeksforGeeks!@12”Output : Strong Input : “gfg!@12”Output : Moderate C++ Java Python3 // C++ program to check if a given password is// strong or not.#include <bits/stdc++.h>using namespace std; void printStrongNess(string& input){ int n = input.length(); // Checking lower alphabet in string bool hasLower = false, hasUpper = false; bool hasDigit = false, specialChar = false; string normalChars = "abcdefghijklmnopqrstu" "vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "; for (int i = 0; i < n; i++) { if (islower(input[i])) hasLower = true; if (isupper(input[i])) hasUpper = true; if (isdigit(input[i])) hasDigit = true; size_t special = input.find_first_not_of(normalChars); if (special != string::npos) specialChar = true; } // Strength of password cout << "Strength of password:-"; if (hasLower && hasUpper && hasDigit && specialChar && (n >= 8)) cout << "Strong" << endl; else if ((hasLower || hasUpper) && specialChar && (n >= 6)) cout << "Moderate" << endl; else cout << "Weak" << endl;} // Driver codeint main(){ string input = "GeeksforGeeks!@12"; printStrongNess(input); return 0;} // Java implementation for the above approachimport java.io.*;import java.util.*; class GFG { public static void printStrongNess(String input) { // Checking lower alphabet in string int n = input.length(); boolean hasLower = false, hasUpper = false, hasDigit = false, specialChar = false; Set<Character> set = new HashSet<Character>( Arrays.asList('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+')); for (char i : input.toCharArray()) { if (Character.isLowerCase(i)) hasLower = true; if (Character.isUpperCase(i)) hasUpper = true; if (Character.isDigit(i)) hasDigit = true; if (set.contains(i)) specialChar = true; } // Strength of password System.out.print("Strength of password:- "); if (hasDigit && hasLower && hasUpper && specialChar && (n >= 8)) System.out.print(" Strong"); else if ((hasLower || hasUpper || specialChar) && (n >= 6)) System.out.print(" Moderate"); else System.out.print(" Weak"); } // Driver Code public static void main(String[] args) { String input = "GeeksforGeeks!@12"; printStrongNess(input); } }// contributed by Ashish Chhabra # Python3 program to check if a given# password is strong or not.def printStrongNess(input_string): n = len(input_string) # Checking lower alphabet in string hasLower = False hasUpper = False hasDigit = False specialChar = False normalChars = "abcdefghijklmnopqrstu" "vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " for i in range(n): if input_string[i].islower(): hasLower = True if input_string[i].isupper(): hasUpper = True if input_string[i].isdigit(): hasDigit = True if input_string[i] not in normalChars: specialChar = True # Strength of password print("Strength of password:-", end = "") if (hasLower and hasUpper and hasDigit and specialChar and n >= 8): print("Strong") elif ((hasLower or hasUpper) and specialChar and n >= 6): print("Moderate") else: print("Weak") # Driver codeif __name__=="__main__": input_string = "GeeksforGeeks!@12" printStrongNess(input_string) # This code is contributed by Yash_R Strength of password:-Strong This article is contributed by Apurva Agarwal. 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. Yash_R ashishchhabra2 avtarkumar719 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26477, "s": 26449, "text": "\n28 Feb, 2022" }, { "code": null, "e": 26550, "s": 26477, "text": "A password is said to be strong if it satisfies the following criteria: " }, { "code": null, "e": 26797, "s": 26550, "text": "It contains at least one lowercase English character.It contains at least one uppercase English character.It contains at least one special character. The special characters are: !@#$%^&*()-+Its length is at least 8.It contains at least one digit." }, { "code": null, "e": 26851, "s": 26797, "text": "It contains at least one lowercase English character." }, { "code": null, "e": 26905, "s": 26851, "text": "It contains at least one uppercase English character." }, { "code": null, "e": 26990, "s": 26905, "text": "It contains at least one special character. The special characters are: !@#$%^&*()-+" }, { "code": null, "e": 27016, "s": 26990, "text": "Its length is at least 8." }, { "code": null, "e": 27048, "s": 27016, "text": "It contains at least one digit." }, { "code": null, "e": 27269, "s": 27048, "text": "Given a string, find its strength. Let a strong password is one that satisfies all above conditions. A moderate password is one that satisfies first three conditions and has length at least 6. Otherwise password is week." }, { "code": null, "e": 27281, "s": 27269, "text": "Examples : " }, { "code": null, "e": 27324, "s": 27281, "text": "Input : “GeeksforGeeks!@12”Output : Strong" }, { "code": null, "e": 27359, "s": 27324, "text": "Input : “gfg!@12”Output : Moderate" }, { "code": null, "e": 27363, "s": 27359, "text": "C++" }, { "code": null, "e": 27368, "s": 27363, "text": "Java" }, { "code": null, "e": 27376, "s": 27368, "text": "Python3" }, { "code": "// C++ program to check if a given password is// strong or not.#include <bits/stdc++.h>using namespace std; void printStrongNess(string& input){ int n = input.length(); // Checking lower alphabet in string bool hasLower = false, hasUpper = false; bool hasDigit = false, specialChar = false; string normalChars = \"abcdefghijklmnopqrstu\" \"vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 \"; for (int i = 0; i < n; i++) { if (islower(input[i])) hasLower = true; if (isupper(input[i])) hasUpper = true; if (isdigit(input[i])) hasDigit = true; size_t special = input.find_first_not_of(normalChars); if (special != string::npos) specialChar = true; } // Strength of password cout << \"Strength of password:-\"; if (hasLower && hasUpper && hasDigit && specialChar && (n >= 8)) cout << \"Strong\" << endl; else if ((hasLower || hasUpper) && specialChar && (n >= 6)) cout << \"Moderate\" << endl; else cout << \"Weak\" << endl;} // Driver codeint main(){ string input = \"GeeksforGeeks!@12\"; printStrongNess(input); return 0;}", "e": 28553, "s": 27376, "text": null }, { "code": "// Java implementation for the above approachimport java.io.*;import java.util.*; class GFG { public static void printStrongNess(String input) { // Checking lower alphabet in string int n = input.length(); boolean hasLower = false, hasUpper = false, hasDigit = false, specialChar = false; Set<Character> set = new HashSet<Character>( Arrays.asList('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+')); for (char i : input.toCharArray()) { if (Character.isLowerCase(i)) hasLower = true; if (Character.isUpperCase(i)) hasUpper = true; if (Character.isDigit(i)) hasDigit = true; if (set.contains(i)) specialChar = true; } // Strength of password System.out.print(\"Strength of password:- \"); if (hasDigit && hasLower && hasUpper && specialChar && (n >= 8)) System.out.print(\" Strong\"); else if ((hasLower || hasUpper || specialChar) && (n >= 6)) System.out.print(\" Moderate\"); else System.out.print(\" Weak\"); } // Driver Code public static void main(String[] args) { String input = \"GeeksforGeeks!@12\"; printStrongNess(input); } }// contributed by Ashish Chhabra", "e": 29973, "s": 28553, "text": null }, { "code": "# Python3 program to check if a given# password is strong or not.def printStrongNess(input_string): n = len(input_string) # Checking lower alphabet in string hasLower = False hasUpper = False hasDigit = False specialChar = False normalChars = \"abcdefghijklmnopqrstu\" \"vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 \" for i in range(n): if input_string[i].islower(): hasLower = True if input_string[i].isupper(): hasUpper = True if input_string[i].isdigit(): hasDigit = True if input_string[i] not in normalChars: specialChar = True # Strength of password print(\"Strength of password:-\", end = \"\") if (hasLower and hasUpper and hasDigit and specialChar and n >= 8): print(\"Strong\") elif ((hasLower or hasUpper) and specialChar and n >= 6): print(\"Moderate\") else: print(\"Weak\") # Driver codeif __name__==\"__main__\": input_string = \"GeeksforGeeks!@12\" printStrongNess(input_string) # This code is contributed by Yash_R", "e": 31073, "s": 29973, "text": null }, { "code": null, "e": 31102, "s": 31073, "text": "Strength of password:-Strong" }, { "code": null, "e": 31526, "s": 31102, "text": "This article is contributed by Apurva Agarwal. 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": 31533, "s": 31526, "text": "Yash_R" }, { "code": null, "e": 31548, "s": 31533, "text": "ashishchhabra2" }, { "code": null, "e": 31562, "s": 31548, "text": "avtarkumar719" }, { "code": null, "e": 31570, "s": 31562, "text": "Strings" }, { "code": null, "e": 31578, "s": 31570, "text": "Strings" }, { "code": null, "e": 31676, "s": 31578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31751, "s": 31676, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 31808, "s": 31751, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31844, "s": 31808, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31891, "s": 31844, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 31944, "s": 31891, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31980, "s": 31944, "text": "Convert string to char array in C++" }, { "code": null, "e": 32018, "s": 31980, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32048, "s": 32018, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32100, "s": 32048, "text": "Check whether two strings are anagram of each other" } ]
Balance pans using given weights that are powers of a number - GeeksforGeeks
06 Jul, 2021 Given a simple weighting scale with two pans, we are given a weight T and some other weights which are the powers of a specific number a, our goal is to balance these pans using the given weights. More formally we need to satisfy this equation, T + (some power of a) = (some other powers of a) Remember that we are given exactly one weight corresponding to one power. Examples: T = 11 and a = 4 Then scale can be balanced as, 11 + 4 + 1 = 16 We can see that in this problem our first goal is to represent T in terms of powers of a so when we write T with the base of a, if representation has only 1s and 0s then we know that weight corresponding to 1s can make the T. For example, If T is 10 and a is 3 then representing 10 on base of 3 we get 101 i.e. using 0th power of 3 and 2nd power of 3 (1 + 9) we can get 10 Now if all digits of base representation are not 1 or 0, then we can’t balance the scale, except the case when in base representation some digit is (a – 1) because in that case, we can transfer corresponding power to T’s side and increase the left number in base representation by 1. For example, If T is 7 and a is 3 then representing 7 on base 3 we get 021. Now while looping over representation from right to left we get 2 (which is 3 - 1), in this case, we can transfer corresponding power(3^1) to T’s side and increase the left number by 1 i.e., T’s side 7 + 3 = 10 and representation 101 (9 + 1) which has only 1s and 0s now, so scale can be balanced. So now algorithm for solving this problem can be represented as follows, represent the T in base of a, if all digits of base representation are 1s or 0s, scale can be balanced otherwise loop from right side of the representation if any number is (a – 1) then increase left side number by 1, keep doing this and ignore 1, 0, (a – 1) and a cases in representation. If complete base representation is processed scale can be balanced otherwise not. C++ Java C# PHP Javascript // C++ code to check whether scale can be balanced or not#include <bits/stdc++.h>using namespace std; // method returns true if balancing of scale is possiblebool isBalancePossible(int T, int a){ // baseForm vector will store T's representation on // base a in reverse order vector<int> baseForm; // convert T to representation on base a while (T) { baseForm.push_back(T % a); T /= a; } // make first digit of representation as 0 baseForm.push_back(0); // loop over base representation of T for (int i = 0; i < baseForm.size(); i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm[i] != 0 && baseForm[i] != 1 && baseForm[i] != (a - 1) && baseForm[i] != a) return false; // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm[i] == a || baseForm[i] == (a - 1)) baseForm[i + 1] += 1; } // if representation is processed then balancing // is possible return true;} // Driver code to test above methodsint main(){ int T = 11; int a = 4; bool balancePossible = isBalancePossible(T, a); if (balancePossible) cout << "Balance is possible" << endl; else cout << "Balance is not possible" << endl; return 0;} // Java code to check whether// scale can be balanced or notimport java.util.*; class GFG{ // method returns true if balancing // of scale is possible static boolean isBalancePossible(int T, int a) { // baseForm vector will store T's // representation on base a // in reverse order Vector<Integer> baseForm = new Vector<>(); int s = 0; // convert T to representation on base a while (T > 0) { baseForm.add(T % a); T /= a; s++; } // make first digit of representation as 0 baseForm.add(0); // loop over base representation of T for (int i = 0; i < s; i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm.get(i) != 0 && baseForm.get(i) != 1 && baseForm.get(i) != (a - 1) && baseForm.get(i) != a) { return false; } // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm.get(i) == a || baseForm.get(i) == (a - 1)) { baseForm.add(i + 1, baseForm.get(i + 1) + 1); } } // if representation is processed // then balancing is possible return true; } // Driver code public static void main(String[] args) { int T = 11; int a = 4; boolean balancePossible = isBalancePossible(T, a); if (balancePossible) { System.out.println("Balance is possible"); } else { System.out.println("Balance is not possible"); } }} // This code has been contributed by 29AjayKumar // C# code to check whether// scale can be balanced or notusing System;using System.Collections.Generic; class GFG{ // method returns true if balancing // of scale is possible static bool isBalancePossible(int T, int a) { // baseForm vector will store T's // representation on base a // in reverse order List<int> baseForm = new List<int>(); int s = 0; // convert T to representation on base a while (T > 0) { baseForm.Add(T % a); T /= a; s++; } // make first digit of representation as 0 baseForm.Add(0); // loop over base representation of T for (int i = 0; i < s; i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm[i] != 0 && baseForm[i] != 1 && baseForm[i] != (a - 1) && baseForm[i] != a) { return false; } // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm[i] == a || baseForm[i] == (a - 1)) { baseForm.Insert(i + 1, baseForm[i+1] + 1); } } // if representation is processed // then balancing is possible return true; } // Driver code public static void Main() { int T = 11; int a = 4; bool balancePossible = isBalancePossible(T, a); if (balancePossible) { Console.WriteLine("Balance is possible"); } else { Console.WriteLine("Balance is not possible"); } }} /* This code contributed by PrinciRaj1992 */ <?php// PHP code to check whether scale// can be balanced or not // method returns true if balancing// of scale is possiblefunction isBalancePossible($T, $a){ // baseForm vector will store T's // representation on base a in reverse order $baseForm = array(); // convert T to representation on base a while ($T) { array_push($baseForm, $T % $a); $T = (int)($T / $a); } // make first digit of representation as 0 array_push($baseForm, 0); // loop over base representation of T for ($i = 0; $i < count($baseForm); $i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if ($baseForm[$i] != 0 && $baseForm[$i] != 1 && $baseForm[$i] != ($a - 1) && $baseForm[$i] != $a) return false; // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if ($baseForm[$i] == $a || $baseForm[$i] == ($a - 1)) $baseForm[$i + 1] += 1; } // if representation is processed then // balancing is possible return true;} // Driver Code$T = 11;$a = 4; $balancePossible = isBalancePossible($T, $a);if ($balancePossible) echo "Balance is possible\n";else echo "Balance is not possible\n"; // This code is contributed by mits?> <script>// Javascript code to check whether// scale can be balanced or not // method returns true if balancing // of scale is possiblefunction isBalancePossible(T,a){ // baseForm vector will store T's // representation on base a // in reverse order let baseForm = []; let s = 0; // convert T to representation on base a while (T > 0) { baseForm.push(T % a); T = Math.floor(T/a); s++; } // make first digit of representation as 0 baseForm.push(0); // loop over base representation of T for (let i = 0; i < s; i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm[i] != 0 && baseForm[i] != 1 && baseForm[i] != (a - 1) && baseForm[i] != a) { return false; } // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm[i] == a || baseForm[i] == (a - 1)) { baseForm.splice(i + 1,0, baseForm[i+1] + 1); } } // if representation is processed // then balancing is possible return true;} // Driver codelet T = 11;let a = 4; let balancePossible = isBalancePossible(T, a);if (balancePossible){ document.write("Balance is possible");}else{ document.write("Balance is not possible");} // This code is contributed by rag2127</script> Output: Balance is possible This article is contributed by Utkarsh Trivedi. 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. Mithun Kumar 29AjayKumar princiraj1992 rag2127 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25961, "s": 25933, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26341, "s": 25961, "text": "Given a simple weighting scale with two pans, we are given a weight T and some other weights which are the powers of a specific number a, our goal is to balance these pans using the given weights. More formally we need to satisfy this equation, T + (some power of a) = (some other powers of a) Remember that we are given exactly one weight corresponding to one power. Examples: " }, { "code": null, "e": 26417, "s": 26341, "text": "T = 11 and a = 4\nThen scale can be balanced as, \n11 + 4 + 1 = 16" }, { "code": null, "e": 26660, "s": 26419, "text": "We can see that in this problem our first goal is to represent T in terms of powers of a so when we write T with the base of a, if representation has only 1s and 0s then we know that weight corresponding to 1s can make the T. For example, " }, { "code": null, "e": 26797, "s": 26660, "text": "If T is 10 and a is 3 then representing 10 on \nbase of 3 we get 101 i.e. using 0th power of 3 \nand 2nd power of 3 (1 + 9) we can get 10" }, { "code": null, "e": 27096, "s": 26797, "text": "Now if all digits of base representation are not 1 or 0, then we can’t balance the scale, except the case when in base representation some digit is (a – 1) because in that case, we can transfer corresponding power to T’s side and increase the left number in base representation by 1. For example, " }, { "code": null, "e": 27468, "s": 27096, "text": "If T is 7 and a is 3 then representing 7 on base \n3 we get 021.\nNow while looping over representation from right \nto left we get 2 (which is 3 - 1), in this case, \nwe can transfer corresponding power(3^1) to T’s \nside and increase the left number by 1 i.e.,\nT’s side 7 + 3 = 10 and representation 101 (9 + 1) \nwhich has only 1s and 0s now, so scale can be balanced." }, { "code": null, "e": 27915, "s": 27468, "text": "So now algorithm for solving this problem can be represented as follows, represent the T in base of a, if all digits of base representation are 1s or 0s, scale can be balanced otherwise loop from right side of the representation if any number is (a – 1) then increase left side number by 1, keep doing this and ignore 1, 0, (a – 1) and a cases in representation. If complete base representation is processed scale can be balanced otherwise not. " }, { "code": null, "e": 27919, "s": 27915, "text": "C++" }, { "code": null, "e": 27924, "s": 27919, "text": "Java" }, { "code": null, "e": 27927, "s": 27924, "text": "C#" }, { "code": null, "e": 27931, "s": 27927, "text": "PHP" }, { "code": null, "e": 27942, "s": 27931, "text": "Javascript" }, { "code": "// C++ code to check whether scale can be balanced or not#include <bits/stdc++.h>using namespace std; // method returns true if balancing of scale is possiblebool isBalancePossible(int T, int a){ // baseForm vector will store T's representation on // base a in reverse order vector<int> baseForm; // convert T to representation on base a while (T) { baseForm.push_back(T % a); T /= a; } // make first digit of representation as 0 baseForm.push_back(0); // loop over base representation of T for (int i = 0; i < baseForm.size(); i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm[i] != 0 && baseForm[i] != 1 && baseForm[i] != (a - 1) && baseForm[i] != a) return false; // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm[i] == a || baseForm[i] == (a - 1)) baseForm[i + 1] += 1; } // if representation is processed then balancing // is possible return true;} // Driver code to test above methodsint main(){ int T = 11; int a = 4; bool balancePossible = isBalancePossible(T, a); if (balancePossible) cout << \"Balance is possible\" << endl; else cout << \"Balance is not possible\" << endl; return 0;}", "e": 29354, "s": 27942, "text": null }, { "code": "// Java code to check whether// scale can be balanced or notimport java.util.*; class GFG{ // method returns true if balancing // of scale is possible static boolean isBalancePossible(int T, int a) { // baseForm vector will store T's // representation on base a // in reverse order Vector<Integer> baseForm = new Vector<>(); int s = 0; // convert T to representation on base a while (T > 0) { baseForm.add(T % a); T /= a; s++; } // make first digit of representation as 0 baseForm.add(0); // loop over base representation of T for (int i = 0; i < s; i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm.get(i) != 0 && baseForm.get(i) != 1 && baseForm.get(i) != (a - 1) && baseForm.get(i) != a) { return false; } // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm.get(i) == a || baseForm.get(i) == (a - 1)) { baseForm.add(i + 1, baseForm.get(i + 1) + 1); } } // if representation is processed // then balancing is possible return true; } // Driver code public static void main(String[] args) { int T = 11; int a = 4; boolean balancePossible = isBalancePossible(T, a); if (balancePossible) { System.out.println(\"Balance is possible\"); } else { System.out.println(\"Balance is not possible\"); } }} // This code has been contributed by 29AjayKumar", "e": 31206, "s": 29354, "text": null }, { "code": "// C# code to check whether// scale can be balanced or notusing System;using System.Collections.Generic; class GFG{ // method returns true if balancing // of scale is possible static bool isBalancePossible(int T, int a) { // baseForm vector will store T's // representation on base a // in reverse order List<int> baseForm = new List<int>(); int s = 0; // convert T to representation on base a while (T > 0) { baseForm.Add(T % a); T /= a; s++; } // make first digit of representation as 0 baseForm.Add(0); // loop over base representation of T for (int i = 0; i < s; i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm[i] != 0 && baseForm[i] != 1 && baseForm[i] != (a - 1) && baseForm[i] != a) { return false; } // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm[i] == a || baseForm[i] == (a - 1)) { baseForm.Insert(i + 1, baseForm[i+1] + 1); } } // if representation is processed // then balancing is possible return true; } // Driver code public static void Main() { int T = 11; int a = 4; bool balancePossible = isBalancePossible(T, a); if (balancePossible) { Console.WriteLine(\"Balance is possible\"); } else { Console.WriteLine(\"Balance is not possible\"); } }} /* This code contributed by PrinciRaj1992 */", "e": 33025, "s": 31206, "text": null }, { "code": "<?php// PHP code to check whether scale// can be balanced or not // method returns true if balancing// of scale is possiblefunction isBalancePossible($T, $a){ // baseForm vector will store T's // representation on base a in reverse order $baseForm = array(); // convert T to representation on base a while ($T) { array_push($baseForm, $T % $a); $T = (int)($T / $a); } // make first digit of representation as 0 array_push($baseForm, 0); // loop over base representation of T for ($i = 0; $i < count($baseForm); $i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if ($baseForm[$i] != 0 && $baseForm[$i] != 1 && $baseForm[$i] != ($a - 1) && $baseForm[$i] != $a) return false; // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if ($baseForm[$i] == $a || $baseForm[$i] == ($a - 1)) $baseForm[$i + 1] += 1; } // if representation is processed then // balancing is possible return true;} // Driver Code$T = 11;$a = 4; $balancePossible = isBalancePossible($T, $a);if ($balancePossible) echo \"Balance is possible\\n\";else echo \"Balance is not possible\\n\"; // This code is contributed by mits?>", "e": 34380, "s": 33025, "text": null }, { "code": "<script>// Javascript code to check whether// scale can be balanced or not // method returns true if balancing // of scale is possiblefunction isBalancePossible(T,a){ // baseForm vector will store T's // representation on base a // in reverse order let baseForm = []; let s = 0; // convert T to representation on base a while (T > 0) { baseForm.push(T % a); T = Math.floor(T/a); s++; } // make first digit of representation as 0 baseForm.push(0); // loop over base representation of T for (let i = 0; i < s; i++) { // if any digit is not 0, 1, (a - 1) or a // then balancing is not possible if (baseForm[i] != 0 && baseForm[i] != 1 && baseForm[i] != (a - 1) && baseForm[i] != a) { return false; } // if digit is a or (a - 1) then increase left // index's count/ (case, when this weight is // transferred to T's side) if (baseForm[i] == a || baseForm[i] == (a - 1)) { baseForm.splice(i + 1,0, baseForm[i+1] + 1); } } // if representation is processed // then balancing is possible return true;} // Driver codelet T = 11;let a = 4; let balancePossible = isBalancePossible(T, a);if (balancePossible){ document.write(\"Balance is possible\");}else{ document.write(\"Balance is not possible\");} // This code is contributed by rag2127</script>", "e": 36008, "s": 34380, "text": null }, { "code": null, "e": 36018, "s": 36008, "text": "Output: " }, { "code": null, "e": 36038, "s": 36018, "text": "Balance is possible" }, { "code": null, "e": 36462, "s": 36038, "text": "This article is contributed by Utkarsh Trivedi. 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": 36475, "s": 36462, "text": "Mithun Kumar" }, { "code": null, "e": 36487, "s": 36475, "text": "29AjayKumar" }, { "code": null, "e": 36501, "s": 36487, "text": "princiraj1992" }, { "code": null, "e": 36509, "s": 36501, "text": "rag2127" }, { "code": null, "e": 36522, "s": 36509, "text": "Mathematical" }, { "code": null, "e": 36535, "s": 36522, "text": "Mathematical" }, { "code": null, "e": 36633, "s": 36535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36677, "s": 36633, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 36719, "s": 36677, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 36750, "s": 36719, "text": "Modular multiplicative inverse" }, { "code": null, "e": 36821, "s": 36750, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 36846, "s": 36821, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 36878, "s": 36846, "text": "Check if a number is Palindrome" }, { "code": null, "e": 36911, "s": 36878, "text": "Program to multiply two matrices" }, { "code": null, "e": 36957, "s": 36911, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 37001, "s": 36957, "text": "Generate all permutation of a set in Python" } ]
Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function) - GeeksforGeeks
17 Mar, 2022 Prerequisite : Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the placement of pieces on the board. This function is often known as Evaluation Function. It is sometimes also called Heuristic Function.The evaluation function is unique for every type of game. In this post, evaluation function for the game Tic-Tac-Toe is discussed. The basic idea behind the evaluation function is to give a high value for a board if maximizer‘s turn or a low value for the board if minimizer‘s turn.For this scenario let us consider X as the maximizer and O as the minimizer.Let us build our evaluation function : If X wins on the board we give it a positive value of +10. If X wins on the board we give it a positive value of +10. If O wins on the board we give it a negative value of -10. If O wins on the board we give it a negative value of -10. If no one has won or the game results in a draw then we give a value of +0. If no one has won or the game results in a draw then we give a value of +0. We could have chosen any positive / negative value other than 10. For the sake of simplicity we chose 10 for the sake of simplicity we shall use lower case ‘x’ and lower case ‘o’ to represent the players and an underscore ‘_’ to represent a blank space on the board. If we represent our board as a 3×3 2D character matrix, like char board[3][3]; then we have to check each row, each column and the diagonals to check if either of the players have gotten 3 in a row. C++ Java Python3 C# Javascript // C++ program to compute evaluation function for// Tic Tac Toe Game.#include<stdio.h>#include<algorithm>using namespace std; // Returns a value based on who is winning// b[3][3] is the Tic-Tac-Toe boardint evaluate(char b[3][3]){ // Checking for Rows for X or O victory. for (int row = 0; row<3; row++) { if (b[row][0]==b[row][1] && b[row][1]==b[row][2]) { if (b[row][0]=='x') return +10; else if (b[row][0]=='o') return -10; } } // Checking for Columns for X or O victory. for (int col = 0; col<3; col++) { if (b[0][col]==b[1][col] && b[1][col]==b[2][col]) { if (b[0][col]=='x') return +10; else if (b[0][col]=='o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0][0]==b[1][1] && b[1][1]==b[2][2]) { if (b[0][0]=='x') return +10; else if (b[0][0]=='o') return -10; } if (b[0][2]==b[1][1] && b[1][1]==b[2][0]) { if (b[0][2]=='x') return +10; else if (b[0][2]=='o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codeint main(){ char board[3][3] = { { 'x', '_', 'o'}, { '_', 'x', 'o'}, { '_', '_', 'x'} }; int value = evaluate(board); printf("The value of this board is %d\n", value); return 0;} // Java program to compute evaluation function for// Tic Tac Toe Game. class GFG{ // Returns a value based on who is winning// b[3][3] is the Tic-Tac-Toe boardstatic int evaluate(char b[][]){ // Checking for Rows for X or O victory. for (int row = 0; row < 3; row++) { if (b[row][0] == b[row][1] && b[row][1] == b[row][2]) { if (b[row][0] == 'x') return +10; else if (b[row][0] == 'o') return -10; } } // Checking for Columns for X or O victory. for (int col = 0; col < 3; col++) { if (b[0][col] == b[1][col] && b[1][col] == b[2][col]) { if (b[0][col] == 'x') return +10; else if (b[0][col] == 'o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { if (b[0][0] == 'x') return +10; else if (b[0][0] == 'o') return -10; } if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { if (b[0][2] == 'x') return +10; else if (b[0][2] == 'o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codepublic static void main(String[] args){ char board[][] = { { 'x', '_', 'o'}, { '_', 'x', 'o'}, { '_', '_', 'x'} }; int value = evaluate(board); System.out.printf("The value of this board is %d\n", value);}} // This code is contributed by PrinciRaj1992 # Python3 program to compute evaluation# function for Tic Tac Toe Game. # Returns a value based on who is winning# b[3][3] is the Tic-Tac-Toe boarddef evaluate(b): # Checking for Rows for X or O victory. for row in range(0, 3): if b[row][0] == b[row][1] and b[row][1] == b[row][2]: if b[row][0] == 'x': return 10 else if b[row][0] == 'o': return -10 # Checking for Columns for X or O victory. for col in range(0, 3): if b[0][col] == b[1][col] and b[1][col] == b[2][col]: if b[0][col]=='x': return 10 else if b[0][col] == 'o': return -10 # Checking for Diagonals for X or O victory. if b[0][0] == b[1][1] and b[1][1] == b[2][2]: if b[0][0] == 'x': return 10 else if b[0][0] == 'o': return -10 if b[0][2] == b[1][1] and b[1][1] == b[2][0]: if b[0][2] == 'x': return 10 else if b[0][2] == 'o': return -10 # Else if none of them have won then return 0 return 0 # Driver codeif __name__ == "__main__": board = [['x', '_', 'o'], ['_', 'x', 'o'], ['_', '_', 'x']] value = evaluate(board) print("The value of this board is", value) # This code is contributed by Rituraj Jain // C# program to compute evaluation function for// Tic Tac Toe Game.using System; class GFG{ // Returns a value based on who is winning// b[3,3] is the Tic-Tac-Toe boardstatic int evaluate(char [,]b){ // Checking for Rows for X or O victory. for (int row = 0; row < 3; row++) { if (b[row, 0] == b[row, 1] && b[row, 1] == b[row, 2]) { if (b[row, 0] == 'x') return +10; else if (b[row, 0] == 'o') return -10; } } // Checking for Columns for X or O victory. for (int col = 0; col < 3; col++) { if (b[0, col] == b[1, col] && b[1, col] == b[2, col]) { if (b[0, col] == 'x') return +10; else if (b[0, col] == 'o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0, 0] == b[1, 1] && b[1, 1] == b[2, 2]) { if (b[0, 0] == 'x') return +10; else if (b[0, 0] == 'o') return -10; } if (b[0, 2] == b[1, 1] && b[1, 1] == b[2, 0]) { if (b[0, 2] == 'x') return +10; else if (b[0, 2] == 'o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codepublic static void Main(String[] args){ char [,]board = { { 'x', '_', 'o'}, { '_', 'x', 'o'}, { '_', '_', 'x'} }; int value = evaluate(board); Console.Write("The value of this board is {0}\n", value);}} // This code is contributed by Rajput-Ji <script>// Javascript program to compute evaluation function for// Tic Tac Toe Game. // Returns a value based on who is winning// b[3][3] is the Tic-Tac-Toe boardfunction evaluate(b){ // Checking for Rows for X or O victory. for (let row = 0; row < 3; row++) { if (b[row][0] == b[row][1] && b[row][1] == b[row][2]) { if (b[row][0] == 'x') return +10; else if (b[row][0] == 'o') return -10; } } // Checking for Columns for X or O victory. for (let col = 0; col < 3; col++) { if (b[0][col] == b[1][col] && b[1][col] == b[2][col]) { if (b[0][col] == 'x') return +10; else if (b[0][col] == 'o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { if (b[0][0] == 'x') return +10; else if (b[0][0] == 'o') return -10; } if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { if (b[0][2] == 'x') return +10; else if (b[0][2] == 'o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codelet board=[[ 'x', '_', 'o'], [ '_', 'x', 'o'], [ '_', '_', 'x']]; let value = evaluate(board);document.write("The value of this board is "+ value+"<br>"); // This code is contributed by avanitrachhadiya2155</script> Output : The value of this board is 10 The idea of this article is to understand how to write a simple evaluation function for the game Tic-Tac-Toe. In the next article we shall see how to combine this evaluation function with the minimax function. Stay Tuned.This article is written by Akshay L. Aradhya. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rituraj_jain princiraj1992 Rajput-Ji avanitrachhadiya2155 simmytarika5 chhabradhanvi Game Theory Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Classification of Algorithms with Examples A Binary String Game Find the winner of the Game to Win by erasing any two consecutive similar alphabets Random Number Memory Game in C Two player game in which a player can remove all occurrences of a number Find the player who will win the Coin game Find the player who will win by choosing a number in range [1, K] with sum total N Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game) Make a palindromic string from given string Maximum and minimum isolated vertices in a graph
[ { "code": null, "e": 26371, "s": 26343, "text": "\n17 Mar, 2022" }, { "code": null, "e": 27252, "s": 26371, "text": "Prerequisite : Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the placement of pieces on the board. This function is often known as Evaluation Function. It is sometimes also called Heuristic Function.The evaluation function is unique for every type of game. In this post, evaluation function for the game Tic-Tac-Toe is discussed. The basic idea behind the evaluation function is to give a high value for a board if maximizer‘s turn or a low value for the board if minimizer‘s turn.For this scenario let us consider X as the maximizer and O as the minimizer.Let us build our evaluation function : " }, { "code": null, "e": 27313, "s": 27252, "text": "If X wins on the board we give it a positive value of +10. " }, { "code": null, "e": 27374, "s": 27313, "text": "If X wins on the board we give it a positive value of +10. " }, { "code": null, "e": 27435, "s": 27374, "text": "If O wins on the board we give it a negative value of -10. " }, { "code": null, "e": 27496, "s": 27435, "text": "If O wins on the board we give it a negative value of -10. " }, { "code": null, "e": 27574, "s": 27496, "text": "If no one has won or the game results in a draw then we give a value of +0. " }, { "code": null, "e": 27652, "s": 27574, "text": "If no one has won or the game results in a draw then we give a value of +0. " }, { "code": null, "e": 28119, "s": 27652, "text": "We could have chosen any positive / negative value other than 10. For the sake of simplicity we chose 10 for the sake of simplicity we shall use lower case ‘x’ and lower case ‘o’ to represent the players and an underscore ‘_’ to represent a blank space on the board. If we represent our board as a 3×3 2D character matrix, like char board[3][3]; then we have to check each row, each column and the diagonals to check if either of the players have gotten 3 in a row. " }, { "code": null, "e": 28123, "s": 28119, "text": "C++" }, { "code": null, "e": 28128, "s": 28123, "text": "Java" }, { "code": null, "e": 28136, "s": 28128, "text": "Python3" }, { "code": null, "e": 28139, "s": 28136, "text": "C#" }, { "code": null, "e": 28150, "s": 28139, "text": "Javascript" }, { "code": "// C++ program to compute evaluation function for// Tic Tac Toe Game.#include<stdio.h>#include<algorithm>using namespace std; // Returns a value based on who is winning// b[3][3] is the Tic-Tac-Toe boardint evaluate(char b[3][3]){ // Checking for Rows for X or O victory. for (int row = 0; row<3; row++) { if (b[row][0]==b[row][1] && b[row][1]==b[row][2]) { if (b[row][0]=='x') return +10; else if (b[row][0]=='o') return -10; } } // Checking for Columns for X or O victory. for (int col = 0; col<3; col++) { if (b[0][col]==b[1][col] && b[1][col]==b[2][col]) { if (b[0][col]=='x') return +10; else if (b[0][col]=='o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0][0]==b[1][1] && b[1][1]==b[2][2]) { if (b[0][0]=='x') return +10; else if (b[0][0]=='o') return -10; } if (b[0][2]==b[1][1] && b[1][1]==b[2][0]) { if (b[0][2]=='x') return +10; else if (b[0][2]=='o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codeint main(){ char board[3][3] = { { 'x', '_', 'o'}, { '_', 'x', 'o'}, { '_', '_', 'x'} }; int value = evaluate(board); printf(\"The value of this board is %d\\n\", value); return 0;}", "e": 29613, "s": 28150, "text": null }, { "code": "// Java program to compute evaluation function for// Tic Tac Toe Game. class GFG{ // Returns a value based on who is winning// b[3][3] is the Tic-Tac-Toe boardstatic int evaluate(char b[][]){ // Checking for Rows for X or O victory. for (int row = 0; row < 3; row++) { if (b[row][0] == b[row][1] && b[row][1] == b[row][2]) { if (b[row][0] == 'x') return +10; else if (b[row][0] == 'o') return -10; } } // Checking for Columns for X or O victory. for (int col = 0; col < 3; col++) { if (b[0][col] == b[1][col] && b[1][col] == b[2][col]) { if (b[0][col] == 'x') return +10; else if (b[0][col] == 'o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { if (b[0][0] == 'x') return +10; else if (b[0][0] == 'o') return -10; } if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { if (b[0][2] == 'x') return +10; else if (b[0][2] == 'o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codepublic static void main(String[] args){ char board[][] = { { 'x', '_', 'o'}, { '_', 'x', 'o'}, { '_', '_', 'x'} }; int value = evaluate(board); System.out.printf(\"The value of this board is %d\\n\", value);}} // This code is contributed by PrinciRaj1992", "e": 31137, "s": 29613, "text": null }, { "code": "# Python3 program to compute evaluation# function for Tic Tac Toe Game. # Returns a value based on who is winning# b[3][3] is the Tic-Tac-Toe boarddef evaluate(b): # Checking for Rows for X or O victory. for row in range(0, 3): if b[row][0] == b[row][1] and b[row][1] == b[row][2]: if b[row][0] == 'x': return 10 else if b[row][0] == 'o': return -10 # Checking for Columns for X or O victory. for col in range(0, 3): if b[0][col] == b[1][col] and b[1][col] == b[2][col]: if b[0][col]=='x': return 10 else if b[0][col] == 'o': return -10 # Checking for Diagonals for X or O victory. if b[0][0] == b[1][1] and b[1][1] == b[2][2]: if b[0][0] == 'x': return 10 else if b[0][0] == 'o': return -10 if b[0][2] == b[1][1] and b[1][1] == b[2][0]: if b[0][2] == 'x': return 10 else if b[0][2] == 'o': return -10 # Else if none of them have won then return 0 return 0 # Driver codeif __name__ == \"__main__\": board = [['x', '_', 'o'], ['_', 'x', 'o'], ['_', '_', 'x']] value = evaluate(board) print(\"The value of this board is\", value) # This code is contributed by Rituraj Jain", "e": 32523, "s": 31137, "text": null }, { "code": "// C# program to compute evaluation function for// Tic Tac Toe Game.using System; class GFG{ // Returns a value based on who is winning// b[3,3] is the Tic-Tac-Toe boardstatic int evaluate(char [,]b){ // Checking for Rows for X or O victory. for (int row = 0; row < 3; row++) { if (b[row, 0] == b[row, 1] && b[row, 1] == b[row, 2]) { if (b[row, 0] == 'x') return +10; else if (b[row, 0] == 'o') return -10; } } // Checking for Columns for X or O victory. for (int col = 0; col < 3; col++) { if (b[0, col] == b[1, col] && b[1, col] == b[2, col]) { if (b[0, col] == 'x') return +10; else if (b[0, col] == 'o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0, 0] == b[1, 1] && b[1, 1] == b[2, 2]) { if (b[0, 0] == 'x') return +10; else if (b[0, 0] == 'o') return -10; } if (b[0, 2] == b[1, 1] && b[1, 1] == b[2, 0]) { if (b[0, 2] == 'x') return +10; else if (b[0, 2] == 'o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codepublic static void Main(String[] args){ char [,]board = { { 'x', '_', 'o'}, { '_', 'x', 'o'}, { '_', '_', 'x'} }; int value = evaluate(board); Console.Write(\"The value of this board is {0}\\n\", value);}} // This code is contributed by Rajput-Ji", "e": 34048, "s": 32523, "text": null }, { "code": "<script>// Javascript program to compute evaluation function for// Tic Tac Toe Game. // Returns a value based on who is winning// b[3][3] is the Tic-Tac-Toe boardfunction evaluate(b){ // Checking for Rows for X or O victory. for (let row = 0; row < 3; row++) { if (b[row][0] == b[row][1] && b[row][1] == b[row][2]) { if (b[row][0] == 'x') return +10; else if (b[row][0] == 'o') return -10; } } // Checking for Columns for X or O victory. for (let col = 0; col < 3; col++) { if (b[0][col] == b[1][col] && b[1][col] == b[2][col]) { if (b[0][col] == 'x') return +10; else if (b[0][col] == 'o') return -10; } } // Checking for Diagonals for X or O victory. if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { if (b[0][0] == 'x') return +10; else if (b[0][0] == 'o') return -10; } if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { if (b[0][2] == 'x') return +10; else if (b[0][2] == 'o') return -10; } // Else if none of them have won then return 0 return 0;} // Driver codelet board=[[ 'x', '_', 'o'], [ '_', 'x', 'o'], [ '_', '_', 'x']]; let value = evaluate(board);document.write(\"The value of this board is \"+ value+\"<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 35520, "s": 34048, "text": null }, { "code": null, "e": 35530, "s": 35520, "text": "Output : " }, { "code": null, "e": 35560, "s": 35530, "text": "The value of this board is 10" }, { "code": null, "e": 36173, "s": 35560, "text": "The idea of this article is to understand how to write a simple evaluation function for the game Tic-Tac-Toe. In the next article we shall see how to combine this evaluation function with the minimax function. Stay Tuned.This article is written by Akshay L. Aradhya. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36186, "s": 36173, "text": "rituraj_jain" }, { "code": null, "e": 36200, "s": 36186, "text": "princiraj1992" }, { "code": null, "e": 36210, "s": 36200, "text": "Rajput-Ji" }, { "code": null, "e": 36231, "s": 36210, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36244, "s": 36231, "text": "simmytarika5" }, { "code": null, "e": 36258, "s": 36244, "text": "chhabradhanvi" }, { "code": null, "e": 36270, "s": 36258, "text": "Game Theory" }, { "code": null, "e": 36282, "s": 36270, "text": "Game Theory" }, { "code": null, "e": 36380, "s": 36282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36423, "s": 36380, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 36444, "s": 36423, "text": "A Binary String Game" }, { "code": null, "e": 36528, "s": 36444, "text": "Find the winner of the Game to Win by erasing any two consecutive similar alphabets" }, { "code": null, "e": 36559, "s": 36528, "text": "Random Number Memory Game in C" }, { "code": null, "e": 36632, "s": 36559, "text": "Two player game in which a player can remove all occurrences of a number" }, { "code": null, "e": 36675, "s": 36632, "text": "Find the player who will win the Coin game" }, { "code": null, "e": 36758, "s": 36675, "text": "Find the player who will win by choosing a number in range [1, K] with sum total N" }, { "code": null, "e": 36829, "s": 36758, "text": "Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)" }, { "code": null, "e": 36873, "s": 36829, "text": "Make a palindromic string from given string" } ]
Scala Iterator count() method with example - GeeksforGeeks
30 Jun, 2019 The count() method belongs to the concrete value members of the class Abstract Iterator. It is defined in the class IterableOnceOps. It counts the number of elements in the stated collection which satisfy the given predicate. Method Definition : def count(p: (A) => Boolean): Int Where, p is the predicate used. Return Type :It returns the number of elements satisfying the predicate p. Example #1: // Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(5, 6, 8) // Applying count method val result = iter.count(x => {x % 3 != 0}) // Displays output println(result) }} 2 Here, only two elements satisfies the stated predicate so, two is returned.Example #2: // Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(4, 6, 10, 11, 13) // Applying count method val result = iter.count(x => {x % 2 == 0}) // Displays output println(result) }} 3 Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala Constructors Scala String substring() method with example Scala | Arrays How to get the first element of List in Scala Scala String replace() method with example
[ { "code": null, "e": 25223, "s": 25195, "text": "\n30 Jun, 2019" }, { "code": null, "e": 25449, "s": 25223, "text": "The count() method belongs to the concrete value members of the class Abstract Iterator. It is defined in the class IterableOnceOps. It counts the number of elements in the stated collection which satisfy the given predicate." }, { "code": null, "e": 25503, "s": 25449, "text": "Method Definition : def count(p: (A) => Boolean): Int" }, { "code": null, "e": 25535, "s": 25503, "text": "Where, p is the predicate used." }, { "code": null, "e": 25610, "s": 25535, "text": "Return Type :It returns the number of elements satisfying the predicate p." }, { "code": null, "e": 25622, "s": 25610, "text": "Example #1:" }, { "code": "// Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(5, 6, 8) // Applying count method val result = iter.count(x => {x % 3 != 0}) // Displays output println(result) }}", "e": 25985, "s": 25622, "text": null }, { "code": null, "e": 25988, "s": 25985, "text": "2\n" }, { "code": null, "e": 26075, "s": 25988, "text": "Here, only two elements satisfies the stated predicate so, two is returned.Example #2:" }, { "code": "// Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(4, 6, 10, 11, 13) // Applying count method val result = iter.count(x => {x % 2 == 0}) // Displays output println(result) }}", "e": 26447, "s": 26075, "text": null }, { "code": null, "e": 26450, "s": 26447, "text": "3\n" }, { "code": null, "e": 26456, "s": 26450, "text": "Scala" }, { "code": null, "e": 26469, "s": 26456, "text": "Scala-Method" }, { "code": null, "e": 26475, "s": 26469, "text": "Scala" }, { "code": null, "e": 26573, "s": 26475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26595, "s": 26573, "text": "Type Casting in Scala" }, { "code": null, "e": 26621, "s": 26595, "text": "Class and Object in Scala" }, { "code": null, "e": 26633, "s": 26621, "text": "Scala Lists" }, { "code": null, "e": 26686, "s": 26633, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 26705, "s": 26686, "text": "Operators in Scala" }, { "code": null, "e": 26724, "s": 26705, "text": "Scala Constructors" }, { "code": null, "e": 26769, "s": 26724, "text": "Scala String substring() method with example" }, { "code": null, "e": 26784, "s": 26769, "text": "Scala | Arrays" }, { "code": null, "e": 26830, "s": 26784, "text": "How to get the first element of List in Scala" } ]
Minimum increment operations to make the array in increasing order - GeeksforGeeks
23 Apr, 2021 Given an array of size N and X. Find minimum moves required to make the array in increasing order. In each move one can add X to any element in the array. Examples: Input : a = { 1, 3, 3, 2 }, X = 2 Output : 3 Explanation : Modified array is { 1, 3, 5, 6 } Input : a = { 3, 5, 6 }, X = 5 Output : 0 Observation : Let’s take two numbers a and b. a >= b and convert this into a < b by adding some number X. so, a < b + k*X ( a – b ) / x < kso, the minimum possible value of k is ( a – b ) / x + 1. Approach : Iterate over the given array and take two numbers when a[i] >= a[i-1] and apply above observation. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find minimum moves required// to make the array in increasing order#include <bits/stdc++.h>using namespace std; // function to find minimum moves required// to make the array in increasing orderint MinimumMoves(int a[], int n, int x){ // to store answer int ans = 0; // iterate over an array for (int i = 1; i < n; i++) { // non- increasing order if (a[i] <= a[i - 1]) { int p = (a[i - 1] - a[i]) / x + 1; // add moves to answer ans += p; // increase the element a[i] += p * x; } } // return required answer return ans;} // Driver codeint main(){ int arr[] = { 1, 3, 3, 2 }; int x = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << MinimumMoves(arr, n, x); return 0;} // Java program to find minimum moves required// to make the array in increasing orderimport java.util.*;import java.lang.*;import java.io.*; class GFG{// function to find minimum moves required// to make the array in increasing orderstatic int MinimumMoves(int a[], int n, int x){ // to store answer int ans = 0; // iterate over an array for (int i = 1; i < n; i++) { // non- increasing order if (a[i] <= a[i - 1]) { int p = (a[i - 1] - a[i]) / x + 1; // add moves to answer ans += p; // increase the element a[i] += p * x; } } // return required answer return ans;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 3, 2 }; int x = 2; int n = arr.length; System.out.println(MinimumMoves(arr, n, x)); }} # Python3 program to find minimum# moves required to make the array# in increasing order # function to find minimum moves required# to make the array in increasing orderdef MinimumMoves(a, n, x) : # to store answer ans = 0 # iterate over an array for i in range(1, n) : # non- increasing order if a[i] <= a[i - 1] : p = (a[i - 1] - a[i]) // x + 1 # add moves to answer ans += p # increase the element a[i] += p * x # return required answer return ans # Driver code if __name__ == "__main__" : arr = [1, 3, 3, 2] x = 2 n = len(arr) print(MinimumMoves(arr, n, x)) # This code is contributed by ANKITRAI1 // C# program to find minimum moves required// to make the array in increasing orderusing System; class GFG { // function to find minimum moves required// to make the array in increasing orderstatic int MinimumMoves(int[] a, int n, int x){ // to store answer int ans = 0; // iterate over an array for (int i = 1; i < n; i++) { // non- increasing order if (a[i] <= a[i - 1]) { int p = (a[i - 1] - a[i]) / x + 1; // add moves to answer ans += p; // increase the element a[i] += p * x; } } // return required answer return ans;} // Driver codepublic static void Main(){ int[] arr = {1, 3, 3, 2}; int x = 2; int n = arr.Length; Console.Write(MinimumMoves(arr, n, x)); }} // This code is contributed by ChitraNayal <?php// PHP program to find minimum// moves required to make the// array in increasing order // function to find minimum// moves required to make the// array in increasing orderfunction MinimumMoves(&$a, $n, $x){ // to store answer $ans = 0; // iterate over an array for ($i = 1; $i < $n; $i++) { // non- increasing order if ($a[$i] <= $a[$i - 1]) { $p = ($a[$i - 1] - $a[$i]) / $x + 1; // add moves to answer $ans += $p; // increase the element $a[$i] += $p * $x; } } // return required answer return $ans;} // Driver code$arr = array(1, 3, 3, 2 );$x = 2;$n = sizeof($arr); echo ((int)MinimumMoves($arr, $n, $x)); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program to find minimum// moves required to make the array in// increasing order // Function to find minimum moves required// to make the array in increasing orderfunction MinimumMoves(a, n, x){ // To store answer var ans = 0; // Tterate over an array for(i = 1; i < n; i++) { // Non- increasing order if (a[i] <= a[i - 1]) { var p = parseInt((a[i - 1] - a[i]) / x + 1); // Add moves to answer ans += p; // Increase the element a[i] += p * x; } } // Return required answer return ans;} // Driver codevar arr = [ 1, 3, 3, 2 ];var x = 2;var n = arr.length; document.write(MinimumMoves(arr, n, x)); // This code is contributed by aashish1995 </script> 3 ankthon Shivi_Aggarwal tufan_gupta2000 ukasp aashish1995 Arrays Competitive Programming Mathematical Arrays Mathematical 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 Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26305, "s": 26277, "text": "\n23 Apr, 2021" }, { "code": null, "e": 26460, "s": 26305, "text": "Given an array of size N and X. Find minimum moves required to make the array in increasing order. In each move one can add X to any element in the array." }, { "code": null, "e": 26471, "s": 26460, "text": "Examples: " }, { "code": null, "e": 26606, "s": 26471, "text": "Input : a = { 1, 3, 3, 2 }, X = 2\nOutput : 3\nExplanation : Modified array is { 1, 3, 5, 6 }\n\nInput : a = { 3, 5, 6 }, X = 5\nOutput : 0" }, { "code": null, "e": 26621, "s": 26606, "text": "Observation : " }, { "code": null, "e": 26806, "s": 26621, "text": "Let’s take two numbers a and b. a >= b and convert this into a < b by adding some number X. so, a < b + k*X ( a – b ) / x < kso, the minimum possible value of k is ( a – b ) / x + 1. " }, { "code": null, "e": 26819, "s": 26806, "text": "Approach : " }, { "code": null, "e": 26919, "s": 26819, "text": "Iterate over the given array and take two numbers when a[i] >= a[i-1] \nand apply above observation." }, { "code": null, "e": 26971, "s": 26919, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26975, "s": 26971, "text": "C++" }, { "code": null, "e": 26980, "s": 26975, "text": "Java" }, { "code": null, "e": 26988, "s": 26980, "text": "Python3" }, { "code": null, "e": 26991, "s": 26988, "text": "C#" }, { "code": null, "e": 26995, "s": 26991, "text": "PHP" }, { "code": null, "e": 27006, "s": 26995, "text": "Javascript" }, { "code": "// C++ program to find minimum moves required// to make the array in increasing order#include <bits/stdc++.h>using namespace std; // function to find minimum moves required// to make the array in increasing orderint MinimumMoves(int a[], int n, int x){ // to store answer int ans = 0; // iterate over an array for (int i = 1; i < n; i++) { // non- increasing order if (a[i] <= a[i - 1]) { int p = (a[i - 1] - a[i]) / x + 1; // add moves to answer ans += p; // increase the element a[i] += p * x; } } // return required answer return ans;} // Driver codeint main(){ int arr[] = { 1, 3, 3, 2 }; int x = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << MinimumMoves(arr, n, x); return 0;}", "e": 27811, "s": 27006, "text": null }, { "code": "// Java program to find minimum moves required// to make the array in increasing orderimport java.util.*;import java.lang.*;import java.io.*; class GFG{// function to find minimum moves required// to make the array in increasing orderstatic int MinimumMoves(int a[], int n, int x){ // to store answer int ans = 0; // iterate over an array for (int i = 1; i < n; i++) { // non- increasing order if (a[i] <= a[i - 1]) { int p = (a[i - 1] - a[i]) / x + 1; // add moves to answer ans += p; // increase the element a[i] += p * x; } } // return required answer return ans;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 3, 2 }; int x = 2; int n = arr.length; System.out.println(MinimumMoves(arr, n, x)); }}", "e": 28663, "s": 27811, "text": null }, { "code": "# Python3 program to find minimum# moves required to make the array# in increasing order # function to find minimum moves required# to make the array in increasing orderdef MinimumMoves(a, n, x) : # to store answer ans = 0 # iterate over an array for i in range(1, n) : # non- increasing order if a[i] <= a[i - 1] : p = (a[i - 1] - a[i]) // x + 1 # add moves to answer ans += p # increase the element a[i] += p * x # return required answer return ans # Driver code if __name__ == \"__main__\" : arr = [1, 3, 3, 2] x = 2 n = len(arr) print(MinimumMoves(arr, n, x)) # This code is contributed by ANKITRAI1", "e": 29385, "s": 28663, "text": null }, { "code": "// C# program to find minimum moves required// to make the array in increasing orderusing System; class GFG { // function to find minimum moves required// to make the array in increasing orderstatic int MinimumMoves(int[] a, int n, int x){ // to store answer int ans = 0; // iterate over an array for (int i = 1; i < n; i++) { // non- increasing order if (a[i] <= a[i - 1]) { int p = (a[i - 1] - a[i]) / x + 1; // add moves to answer ans += p; // increase the element a[i] += p * x; } } // return required answer return ans;} // Driver codepublic static void Main(){ int[] arr = {1, 3, 3, 2}; int x = 2; int n = arr.Length; Console.Write(MinimumMoves(arr, n, x)); }} // This code is contributed by ChitraNayal", "e": 30269, "s": 29385, "text": null }, { "code": "<?php// PHP program to find minimum// moves required to make the// array in increasing order // function to find minimum// moves required to make the// array in increasing orderfunction MinimumMoves(&$a, $n, $x){ // to store answer $ans = 0; // iterate over an array for ($i = 1; $i < $n; $i++) { // non- increasing order if ($a[$i] <= $a[$i - 1]) { $p = ($a[$i - 1] - $a[$i]) / $x + 1; // add moves to answer $ans += $p; // increase the element $a[$i] += $p * $x; } } // return required answer return $ans;} // Driver code$arr = array(1, 3, 3, 2 );$x = 2;$n = sizeof($arr); echo ((int)MinimumMoves($arr, $n, $x)); // This code is contributed// by Shivi_Aggarwal?>", "e": 31046, "s": 30269, "text": null }, { "code": "<script> // Javascript program to find minimum// moves required to make the array in// increasing order // Function to find minimum moves required// to make the array in increasing orderfunction MinimumMoves(a, n, x){ // To store answer var ans = 0; // Tterate over an array for(i = 1; i < n; i++) { // Non- increasing order if (a[i] <= a[i - 1]) { var p = parseInt((a[i - 1] - a[i]) / x + 1); // Add moves to answer ans += p; // Increase the element a[i] += p * x; } } // Return required answer return ans;} // Driver codevar arr = [ 1, 3, 3, 2 ];var x = 2;var n = arr.length; document.write(MinimumMoves(arr, n, x)); // This code is contributed by aashish1995 </script>", "e": 31875, "s": 31046, "text": null }, { "code": null, "e": 31877, "s": 31875, "text": "3" }, { "code": null, "e": 31887, "s": 31879, "text": "ankthon" }, { "code": null, "e": 31902, "s": 31887, "text": "Shivi_Aggarwal" }, { "code": null, "e": 31918, "s": 31902, "text": "tufan_gupta2000" }, { "code": null, "e": 31924, "s": 31918, "text": "ukasp" }, { "code": null, "e": 31936, "s": 31924, "text": "aashish1995" }, { "code": null, "e": 31943, "s": 31936, "text": "Arrays" }, { "code": null, "e": 31967, "s": 31943, "text": "Competitive Programming" }, { "code": null, "e": 31980, "s": 31967, "text": "Mathematical" }, { "code": null, "e": 31987, "s": 31980, "text": "Arrays" }, { "code": null, "e": 32000, "s": 31987, "text": "Mathematical" }, { "code": null, "e": 32098, "s": 32000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32166, "s": 32098, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32210, "s": 32166, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32258, "s": 32210, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32281, "s": 32258, "text": "Introduction to Arrays" }, { "code": null, "e": 32313, "s": 32281, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32356, "s": 32313, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 32399, "s": 32356, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 32440, "s": 32399, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32518, "s": 32440, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
java.time.ZoneId Class in Java - GeeksforGeeks
03 Mar, 2021 A ZoneId is used to identify the rules that used to convert between a LocalDateTime and an Instant of time. The actual rules, describing when and the way the offset changes, are defined by ZoneRules. This class is just an ID wont to obtain the underlying rules. The given approach has opted because the government defines the rules and alters frequently, whereas the ID is stable. There are two distinct types of ID: Fixed offsets is a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-timesGeographical regions are a neighborhood where a selected set of rules for locating the offset from UTC/Greenwich apply Fixed offsets is a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times Geographical regions are a neighborhood where a selected set of rules for locating the offset from UTC/Greenwich apply Declaration of java.time.ZoneId class public abstract class ZoneId extends Object implements Serializable A zone map overrides to enable the short time-zone names to be used. The use of short zone IDs has been deprecated in java.util.TimeZone. This map allows the IDs to still be used via the of(String, Map) factory method. This map contains a mapping of the IDs that’s in line with TZDB 2005r and later, where ‘EST’, ‘MST’ and ‘HST’ map to IDs that don’t include daylight savings. This maps as follows: EST HST MST ACT AET AGT ART AST BET BST CAT CNT CST CTT EAT ECT IET IST JST MIT NET NST PLT PNT PRT PST SST Note: The map is unmodifiable. Methods of ZoneId class: Below is an example of the implementation of some methods: Java // java.time.ZoneId Class in Java with exampleimport java.time.*;public class GFG { public static void main(String[] args) { // Setting Zone1 ZoneId zoneid1 = ZoneId.of("Asia/Kolkata"); // Setting Zone2 ZoneId zoneid2 = ZoneId.of("Europe/London"); LocalTime time1 = LocalTime.now(zoneid1); LocalTime time2 = LocalTime.now(zoneid2); System.out.println(time1); System.out.println(time2); // Checking if the time of zone1 // comes before time of second zone System.out.println(time1.isBefore(time2)); }} 22:34:11.044312 17:04:11.044385 false Java-time package Java-ZoneId Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n03 Mar, 2021" }, { "code": null, "e": 25606, "s": 25225, "text": "A ZoneId is used to identify the rules that used to convert between a LocalDateTime and an Instant of time. The actual rules, describing when and the way the offset changes, are defined by ZoneRules. This class is just an ID wont to obtain the underlying rules. The given approach has opted because the government defines the rules and alters frequently, whereas the ID is stable." }, { "code": null, "e": 25642, "s": 25606, "text": "There are two distinct types of ID:" }, { "code": null, "e": 25872, "s": 25642, "text": "Fixed offsets is a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-timesGeographical regions are a neighborhood where a selected set of rules for locating the offset from UTC/Greenwich apply" }, { "code": null, "e": 25984, "s": 25872, "text": "Fixed offsets is a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times" }, { "code": null, "e": 26103, "s": 25984, "text": "Geographical regions are a neighborhood where a selected set of rules for locating the offset from UTC/Greenwich apply" }, { "code": null, "e": 26141, "s": 26103, "text": "Declaration of java.time.ZoneId class" }, { "code": null, "e": 26211, "s": 26141, "text": "public abstract class ZoneId extends Object implements Serializable " }, { "code": null, "e": 26588, "s": 26211, "text": "A zone map overrides to enable the short time-zone names to be used. The use of short zone IDs has been deprecated in java.util.TimeZone. This map allows the IDs to still be used via the of(String, Map) factory method. This map contains a mapping of the IDs that’s in line with TZDB 2005r and later, where ‘EST’, ‘MST’ and ‘HST’ map to IDs that don’t include daylight savings." }, { "code": null, "e": 26610, "s": 26588, "text": "This maps as follows:" }, { "code": null, "e": 26614, "s": 26610, "text": "EST" }, { "code": null, "e": 26619, "s": 26614, "text": "HST " }, { "code": null, "e": 26624, "s": 26619, "text": "MST " }, { "code": null, "e": 26629, "s": 26624, "text": "ACT " }, { "code": null, "e": 26634, "s": 26629, "text": "AET " }, { "code": null, "e": 26639, "s": 26634, "text": "AGT " }, { "code": null, "e": 26643, "s": 26639, "text": "ART" }, { "code": null, "e": 26648, "s": 26643, "text": "AST " }, { "code": null, "e": 26653, "s": 26648, "text": "BET " }, { "code": null, "e": 26658, "s": 26653, "text": "BST " }, { "code": null, "e": 26663, "s": 26658, "text": "CAT " }, { "code": null, "e": 26668, "s": 26663, "text": "CNT " }, { "code": null, "e": 26673, "s": 26668, "text": "CST " }, { "code": null, "e": 26678, "s": 26673, "text": "CTT " }, { "code": null, "e": 26683, "s": 26678, "text": "EAT " }, { "code": null, "e": 26688, "s": 26683, "text": "ECT " }, { "code": null, "e": 26693, "s": 26688, "text": "IET " }, { "code": null, "e": 26698, "s": 26693, "text": "IST " }, { "code": null, "e": 26703, "s": 26698, "text": "JST " }, { "code": null, "e": 26708, "s": 26703, "text": "MIT " }, { "code": null, "e": 26713, "s": 26708, "text": "NET " }, { "code": null, "e": 26718, "s": 26713, "text": "NST " }, { "code": null, "e": 26723, "s": 26718, "text": "PLT " }, { "code": null, "e": 26727, "s": 26723, "text": "PNT" }, { "code": null, "e": 26732, "s": 26727, "text": "PRT " }, { "code": null, "e": 26737, "s": 26732, "text": "PST " }, { "code": null, "e": 26742, "s": 26737, "text": "SST " }, { "code": null, "e": 26773, "s": 26742, "text": "Note: The map is unmodifiable." }, { "code": null, "e": 26798, "s": 26773, "text": "Methods of ZoneId class:" }, { "code": null, "e": 26857, "s": 26798, "text": "Below is an example of the implementation of some methods:" }, { "code": null, "e": 26862, "s": 26857, "text": "Java" }, { "code": "// java.time.ZoneId Class in Java with exampleimport java.time.*;public class GFG { public static void main(String[] args) { // Setting Zone1 ZoneId zoneid1 = ZoneId.of(\"Asia/Kolkata\"); // Setting Zone2 ZoneId zoneid2 = ZoneId.of(\"Europe/London\"); LocalTime time1 = LocalTime.now(zoneid1); LocalTime time2 = LocalTime.now(zoneid2); System.out.println(time1); System.out.println(time2); // Checking if the time of zone1 // comes before time of second zone System.out.println(time1.isBefore(time2)); }}", "e": 27453, "s": 26862, "text": null }, { "code": null, "e": 27491, "s": 27453, "text": "22:34:11.044312\n17:04:11.044385\nfalse" }, { "code": null, "e": 27509, "s": 27491, "text": "Java-time package" }, { "code": null, "e": 27521, "s": 27509, "text": "Java-ZoneId" }, { "code": null, "e": 27528, "s": 27521, "text": "Picked" }, { "code": null, "e": 27552, "s": 27528, "text": "Technical Scripter 2020" }, { "code": null, "e": 27557, "s": 27552, "text": "Java" }, { "code": null, "e": 27576, "s": 27557, "text": "Technical Scripter" }, { "code": null, "e": 27581, "s": 27576, "text": "Java" }, { "code": null, "e": 27679, "s": 27581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27694, "s": 27679, "text": "Stream In Java" }, { "code": null, "e": 27715, "s": 27694, "text": "Constructors in Java" }, { "code": null, "e": 27734, "s": 27715, "text": "Exceptions in Java" }, { "code": null, "e": 27764, "s": 27734, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27810, "s": 27764, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27827, "s": 27810, "text": "Generics in Java" }, { "code": null, "e": 27848, "s": 27827, "text": "Introduction to Java" }, { "code": null, "e": 27891, "s": 27848, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27927, "s": 27891, "text": "Internal Working of HashMap in Java" } ]
Lowest Common Ancestor in a Binary Tree | Set 1 - GeeksforGeeks
17 Apr, 2022 Given a binary tree (not a binary search tree) and two values say n1 and n2, write a program to find the least common ancestor. Following is definition of LCA from Wikipedia: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor. (Source Wiki) We have discussed an efficient solution to find LCA in Binary Search Tree. In Binary Search Tree, using BST properties, we can find LCA in O(h) time where h is the height of the tree. Such an implementation is not possible in Binary Tree as keys Binary Tree nodes don’t follow any order. The following are different approaches to find LCA in Binary Tree. Method 1 (By Storing root to n1 and root to n2 paths): Following is a simple O(n) algorithm to find LCA of n1 and n2. 1) Find a path from the root to n1 and store it in a vector or array. 2) Find a path from the root to n2 and store it in another vector or array. 3) Traverse both paths till the values in arrays are the same. Return the common element just before the mismatch. Following is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ Program for Lowest Common Ancestor in a Binary Tree// A O(n) solution to find LCA of two given values n1 and n2#include <iostream>#include <vector> using namespace std; // A Binary Tree nodestruct Node{ int key; struct Node *left, *right;}; // Utility function creates a new binary tree node with given keyNode * newNode(int k){ Node *temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp;} // Finds the path from root node to given root of the tree, Stores the// path in a vector path[], returns true if path exists otherwise falsebool findPath(Node *root, vector<int> &path, int k){ // base case if (root == NULL) return false; // Store this node in path vector. The node will be removed if // not in path from root to k path.push_back(root->key); // See if the k is same as root's key if (root->key == k) return true; // Check if k is found in left or right sub-tree if ( (root->left && findPath(root->left, path, k)) || (root->right && findPath(root->right, path, k)) ) return true; // If not present in subtree rooted with root, remove root from // path[] and return false path.pop_back(); return false;} // Returns LCA if node n1, n2 are present in the given binary tree,// otherwise return -1int findLCA(Node *root, int n1, int n2){ // to store paths to n1 and n2 from the root vector<int> path1, path2; // Find paths from root to n1 and root to n1. If either n1 or n2 // is not present, return -1 if ( !findPath(root, path1, n1) || !findPath(root, path2, n2)) return -1; /* Compare the paths to get the first different value */ int i; for (i = 0; i < path1.size() && i < path2.size() ; i++) if (path1[i] != path2[i]) break; return path1[i-1];} // Driver program to test above functionsint main(){ // Let us create the Binary Tree shown in above diagram. Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << "LCA(4, 5) = " << findLCA(root, 4, 5); cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6); cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4); cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4); return 0;} // Java Program for Lowest Common Ancestor in a Binary Tree// A O(n) solution to find LCA of two given values n1 and n2import java.util.ArrayList;import java.util.List; // A Binary Tree nodeclass Node { int data; Node left, right; Node(int value) { data = value; left = right = null; }} public class BT_NoParentPtr_Solution1{ Node root; private List<Integer> path1 = new ArrayList<>(); private List<Integer> path2 = new ArrayList<>(); // Finds the path from root node to given root of the tree. int findLCA(int n1, int n2) { path1.clear(); path2.clear(); return findLCAInternal(root, n1, n2); } private int findLCAInternal(Node root, int n1, int n2) { if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { System.out.println((path1.size() > 0) ? "n1 is present" : "n1 is missing"); System.out.println((path2.size() > 0) ? "n2 is present" : "n2 is missing"); return -1; } int i; for (i = 0; i < path1.size() && i < path2.size(); i++) { // System.out.println(path1.get(i) + " " + path2.get(i)); if (!path1.get(i).equals(path2.get(i))) break; } return path1.get(i-1); } // Finds the path from root node to given root of the tree, Stores the // path in a vector path[], returns true if path exists otherwise false private boolean findPath(Node root, int n, List<Integer> path) { // base case if (root == null) { return false; } // Store this node . The node will be removed if // not in path from root to n. path.add(root.data); if (root.data == n) { return true; } if (root.left != null && findPath(root.left, n, path)) { return true; } if (root.right != null && findPath(root.right, n, path)) { return true; } // If not present in subtree rooted with root, remove root from // path[] and return false path.remove(path.size()-1); return false; } // Driver code public static void main(String[] args) { BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); System.out.println("LCA(4, 5): " + tree.findLCA(4,5)); System.out.println("LCA(4, 6): " + tree.findLCA(4,6)); System.out.println("LCA(3, 4): " + tree.findLCA(3,4)); System.out.println("LCA(2, 4): " + tree.findLCA(2,4)); }}// This code is contributed by Sreenivasulu Rayanki. # Python Program for Lowest Common Ancestor in a Binary Tree# O(n) solution to find LCS of two given values n1 and n2 # A binary tree nodeclass Node: # Constructor to create a new binary node def __init__(self, key): self.key = key self.left = None self.right = None # Finds the path from root node to given root of the tree.# Stores the path in a list path[], returns true if path# exists otherwise falsedef findPath( root, path, k): # Baes Case if root is None: return False # Store this node is path vector. The node will be # removed if not in path from root to k path.append(root.key) # See if the k is same as root's key if root.key == k : return True # Check if k is found in left or right sub-tree if ((root.left != None and findPath(root.left, path, k)) or (root.right!= None and findPath(root.right, path, k))): return True # If not present in subtree rooted with root, remove # root from path and return False path.pop() return False # Returns LCA if node n1 , n2 are present in the given# binary tree otherwise return -1def findLCA(root, n1, n2): # To store paths to n1 and n2 fromthe root path1 = [] path2 = [] # Find paths from root to n1 and root to n2. # If either n1 or n2 is not present , return -1 if (not findPath(root, path1, n1) or not findPath(root, path2, n2)): return -1 # Compare the paths to get the first different value i = 0 while(i < len(path1) and i < len(path2)): if path1[i] != path2[i]: break i += 1 return path1[i-1] # Driver program to test above function# Let's create the Binary Tree shown in above diagramroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7) print ("LCA(4, 5) = %d" %(findLCA(root, 4, 5,)))print ("LCA(4, 6) = %d" %(findLCA(root, 4, 6)))print ("LCA(3, 4) = %d" %(findLCA(root,3,4)))print ("LCA(2, 4) = %d" %(findLCA(root,2, 4))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# Program for Lowest Common// Ancestor in a Binary Tree// A O(n) solution to find LCA// of two given values n1 and n2using System.Collections;using System; // A Binary Tree nodeclass Node{ public int data; public Node left, right; public Node(int value) { data = value; left = right = null; }} public class BT_NoParentPtr_Solution1{ Node root; private ArrayList path1 = new ArrayList(); private ArrayList path2 = new ArrayList(); // Finds the path from root // node to given root of the // tree. int findLCA(int n1, int n2) { path1.Clear(); path2.Clear(); return findLCAInternal(root, n1, n2); } private int findLCAInternal(Node root, int n1, int n2){ if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { Console.Write((path1.Count > 0) ? "n1 is present" : "n1 is missing"); Console.Write((path2.Count > 0) ? "n2 is present" : "n2 is missing"); return -1; } int i; for (i = 0; i < path1.Count && i < path2.Count; i++) { // System.out.println(path1.get(i) // + " " + path2.get(i)); if ((int)path1[i] != (int)path2[i]) break; } return (int)path1[i - 1];} // Finds the path from root node// to given root of the tree,// Stores the path in a vector// path[], returns true if path// exists otherwise falseprivate bool findPath(Node root, int n, ArrayList path){ // base case if (root == null) { return false; } // Store this node . The node // will be removed if not in // path from root to n. path.Add(root.data); if (root.data == n) { return true; } if (root.left != null && findPath(root.left, n, path)) { return true; } if (root.right != null && findPath(root.right, n, path)) { return true; } // If not present in subtree //rooted with root, remove root // from path[] and return false path.RemoveAt(path.Count - 1); return false;} // Driver codepublic static void Main(String[] args){ BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Console.Write("LCA(4, 5): " + tree.findLCA(4, 5)); Console.Write("\nLCA(4, 6): " + tree.findLCA(4, 6)); Console.Write("\nLCA(3, 4): " + tree.findLCA(3, 4)); Console.Write("\nLCA(2, 4): " + tree.findLCA(2, 4));}} // This code is contributed by Rutvik_56 <script> // JavaScript Program for Lowest Common // Ancestor in a Binary Tree // A O(n) solution to find LCA of // two given values n1 and n2 class Node { constructor(value) { this.left = null; this.right = null; this.data = value; } } let root; let path1 = []; let path2 = []; // Finds the path from root node to given root of the tree. function findLCA(n1, n2) { path1 = []; path2 = []; return findLCAInternal(root, n1, n2); } function findLCAInternal(root, n1, n2) { if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { document.write((path1.length > 0) ? "n1 is present" : "n1 is missing"); document.write((path2.length > 0) ? "n2 is present" : "n2 is missing"); return -1; } let i; for (i = 0; i < path1.length && i < path2.length; i++) { // System.out.println(path1.get(i) + " " + path2.get(i)); if (path1[i] != path2[i]) break; } return path1[i-1]; } // Finds the path from root node to // given root of the tree, Stores the // path in a vector path[], returns true // if path exists otherwise false function findPath(root, n, path) { // base case if (root == null) { return false; } // Store this node . The node will be removed if // not in path from root to n. path.push(root.data); if (root.data == n) { return true; } if (root.left != null && findPath(root.left, n, path)) { return true; } if (root.right != null && findPath(root.right, n, path)) { return true; } // If not present in subtree rooted with root, // remove root from // path[] and return false path.pop(); return false; } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); document.write("LCA(4, 5) = " + findLCA(4,5) + "</br>"); document.write("LCA(4, 6) = " + findLCA(4,6) + "</br>"); document.write("LCA(3, 4) = " + findLCA(3,4) + "</br>"); document.write("LCA(2, 4) = " + findLCA(2,4)); </script> Output: LCA(4, 5) = 2 LCA(4, 6) = 1 LCA(3, 4) = 1 LCA(2, 4) = 2 Time Complexity: The time complexity of the above solution is O(n). The tree is traversed twice, and then path arrays are compared. Thanks to Ravi Chandra Enaganti for suggesting the initial solution based on this method. Method 2 (Using Single Traversal) Method 1 finds LCA in O(n) time but requires three tree traversals plus extra spaces for path arrays. If we assume that the keys n1 and n2 are present in Binary Tree, we can find LCA using a single traversal of Binary Tree and without extra storage for path arrays. The idea is to traverse the tree starting from the root. If any of the given keys (n1 and n2) matches with the root, then the root is LCA (assuming that both keys are present). If the root doesn’t match with any of the keys, we recur for the left and right subtree. The node which has one key present in its left subtree and the other key present in the right subtree is the LCA. If both keys lie in the left subtree, then the left subtree has LCA also, otherwise, LCA lies in the right subtree. C++ C Java Python3 C# Javascript /* C++ Program to find LCA of n1 and n2 using one traversal of Binary Tree */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ struct Node *left, *right; int key;}; // Utility function to create a new tree NodeNode* newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // This function returns pointer to LCA of two given values n1 and n2.// This function assumes that n1 and n2 are present in Binary Treestruct Node *findLCA(struct Node* root, int n1, int n2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node *left_lca = findLCA(root->left, n1, n2); Node *right_lca = findLCA(root->right, n1, n2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is LCA return (left_lca != NULL)? left_lca: right_lca;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above example Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << "LCA(4, 5) = " << findLCA(root, 4, 5)->key; cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6)->key; cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4)->key; cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4)->key; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C Program to find LCA of n1 and n2 using one traversalof// Binary Tree#include <stdio.h>#include <stdlib.h> // A Binary Tree Nodetypedef struct Node { struct Node *left, *right; int key;}Node; // Utility function to create a new tree NodeNode* newNode(int key){ Node* temp = (Node*)malloc(sizeof(Node)); temp->key = key; temp->left = temp->right = NULL; return temp;} // This function returns pointer to LCA of two given values// n1 and n2. This function assumes that n1 and n2 are// present in Binary TreeNode* findLCA(Node* root, int n1, int n2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node* left_lca = findLCA(root->left, n1, n2); Node* right_lca = findLCA(root->right, n1, n2); // If both of the above calls return Non-NULL, then one // key is present in once subtree and other is present // in other, So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is // LCA return (left_lca != NULL) ? left_lca : right_lca;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); printf("LCA(4, 5) = %d", findLCA(root, 4, 5)->key); printf("\nLCA(4, 6) = %d", findLCA(root, 4, 6)->key); printf("\nLCA(3, 4) = %d", findLCA(root, 3, 4)->key); printf("\nLCA(2, 4) = %d", findLCA(root, 2, 4)->key); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) //Java implementation to find lowest common ancestor of// n1 and n2 using one traversal of binary tree /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ //Root of the Binary Tree Node root; Node findLCA(int n1, int n2) { return findLCA(root, n1, n2); } // This function returns pointer to LCA of two given // values n1 and n2. This function assumes that n1 and // n2 are present in Binary Tree Node findLCA(Node node, int n1, int n2) { // Base case if (node == null) return null; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (node.data == n1 || node.data == n2) return node; // Look for keys in left and right subtrees Node left_lca = findLCA(node.left, n1, n2); Node right_lca = findLCA(node.right, n1, n2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca!=null && right_lca!=null) return node; // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); System.out.println("LCA(4, 5) = " + tree.findLCA(4, 5).data); System.out.println("LCA(4, 6) = " + tree.findLCA(4, 6).data); System.out.println("LCA(3, 4) = " + tree.findLCA(3, 4).data); System.out.println("LCA(2, 4) = " + tree.findLCA(2, 4).data); }} # Python program to find LCA of n1 and n2 using one# traversal of Binary tree # A binary tree nodeclass Node: # Constructor to create a new tree node def __init__(self, key): self.key = key self.left = None self.right = None # This function returns pointer to LCA of two given# values n1 and n2# This function assumes that n1 and n2 are present in# Binary Treedef findLCA(root, n1, n2): # Base Case if root is None: return None # If either n1 or n2 matches with root's key, report # the presence by returning root (Note that if a key is # ancestor of other, then the ancestor key becomes LCA if root.key == n1 or root.key == n2: return root # Look for keys in left and right subtrees left_lca = findLCA(root.left, n1, n2) right_lca = findLCA(root.right, n1, n2) # If both of the above calls return Non-NULL, then one key # is present in once subtree and other is present in other, # So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right subtree is LCA return left_lca if left_lca is not None else right_lca # Driver program to test above function # Let us create a binary tree given in the above exampleroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)print ("LCA(4,5) = ", findLCA(root, 4, 5).key)print ("LCA(4,6) = ", findLCA(root, 4, 6).key)print ("LCA(3,4) = ", findLCA(root, 3, 4).key)print ("LCA(2,4) = ", findLCA(root, 2, 4).key) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# implementation to find lowest common// ancestor of n1 and n2 using one traversal// of binary treeusing System; // Class containing left and right// child of current node and key valuepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ // Root of the Binary TreeNode root; Node findLCA(int n1, int n2){ return findLCA(root, n1, n2);} // This function returns pointer to LCA// of two given values n1 and n2. This// function assumes that n1 and n2 are// present in Binary TreeNode findLCA(Node node, int n1, int n2){ // Base case if (node == null) return null; // If either n1 or n2 matches with // root's key, report the presence // by returning root (Note that if // a key is ancestor of other, // then the ancestor key becomes LCA if (node.data == n1 || node.data == n2) return node; // Look for keys in left and right subtrees Node left_lca = findLCA(node.left, n1, n2); Node right_lca = findLCA(node.right, n1, n2); // If both of the above calls return Non-NULL, // then one key is present in once subtree // and other is present in other, So this // node is the LCA if (left_lca != null && right_lca != null) return node; // Otherwise check if left subtree or // right subtree is LCA return (left_lca != null) ? left_lca : right_lca;} // Driver codepublic static void Main(string []args){ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Console.WriteLine("LCA(4, 5) = " + tree.findLCA(4, 5).data); Console.WriteLine("LCA(4, 6) = " + tree.findLCA(4, 6).data); Console.WriteLine("LCA(3, 4) = " + tree.findLCA(3, 4).data); Console.WriteLine("LCA(2, 4) = " + tree.findLCA(2, 4).data);}} // This code is contributed by pratham76 <script> // JavaScript implementation to find // lowest common ancestor of // n1 and n2 using one traversal of binary tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } //Root of the Binary Tree let root; function findlCA(n1, n2) { return findLCA(root, n1, n2); } // This function returns pointer to LCA of two given // values n1 and n2. This function assumes that n1 and // n2 are present in Binary Tree function findLCA(node, n1, n2) { // Base case if (node == null) return null; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (node.data == n1 || node.data == n2) return node; // Look for keys in left and right subtrees let left_lca = findLCA(node.left, n1, n2); let right_lca = findLCA(node.right, n1, n2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca!=null && right_lca!=null) return node; // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); document.write("LCA(4, 5) = " + findlCA(4, 5).data + "</br>"); document.write("LCA(4, 6) = " + findlCA(4, 6).data + "</br>"); document.write("LCA(3, 4) = " + findlCA(3, 4).data + "</br>"); document.write("LCA(2, 4) = " + findlCA(2, 4).data + "</br>"); </script> Output: LCA(4, 5) = 2 LCA(4, 6) = 1 LCA(3, 4) = 1 LCA(2, 4) = 2 Thanks to Atul Singh for suggesting this solution. Time Complexity: The time complexity of the above solution is O(n) as the method does a simple tree traversal in a bottom-up fashion. Note that the above method assumes that keys are present in Binary Tree. If one key is present and the other is absent, then it returns the present key as LCA (Ideally should have returned NULL). We can extend this method to handle all cases bypassing two boolean variables v1 and v2. v1 is set as true when n1 is present in the tree and v2 is set as true if n2 is present in the tree. C++ Java Python3 C# Javascript /* C++ program to find LCA of n1 and n2 using one traversal of Binary Tree. It handles all cases even when n1 or n2 is not there in Binary Tree */#include <iostream>using namespace std; // A Binary Tree Nodestruct Node{ struct Node *left, *right; int key;}; // Utility function to create a new tree NodeNode* newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // This function returns pointer to LCA of two given values n1 and n2.// v1 is set as true by this function if n1 is found// v2 is set as true by this function if n2 is foundstruct Node *findLCAUtil(struct Node* root, int n1, int n2, bool &v1, bool &v2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report the presence // by setting v1 or v2 as true and return root (Note that if a key // is ancestor of other, then the ancestor key becomes LCA) if (root->key == n1) { v1 = true; return root; } if (root->key == n2) { v2 = true; return root; } // Look for keys in left and right subtrees Node *left_lca = findLCAUtil(root->left, n1, n2, v1, v2); Node *right_lca = findLCAUtil(root->right, n1, n2, v1, v2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is LCA return (left_lca != NULL)? left_lca: right_lca;} // Returns true if key k is present in tree rooted with rootbool find(Node *root, int k){ // Base Case if (root == NULL) return false; // If key is present at root, or in left subtree or right subtree, // return true; if (root->key == k || find(root->left, k) || find(root->right, k)) return true; // Else return false return false;} // This function returns LCA of n1 and n2 only if both n1 and n2 are present// in tree, otherwise returns NULL;Node *findLCA(Node *root, int n1, int n2){ // Initialize n1 and n2 as not visited bool v1 = false, v2 = false; // Find lca of n1 and n2 using the technique discussed above Node *lca = findLCAUtil(root, n1, n2, v1, v2); // Return LCA only if both n1 and n2 are present in tree if (v1 && v2 || v1 && find(lca, n2) || v2 && find(lca, n1)) return lca; // Else return NULL return NULL;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above example Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); Node *lca = findLCA(root, 4, 5); if (lca != NULL) cout << "LCA(4, 5) = " << lca->key; else cout << "Keys are not present "; lca = findLCA(root, 4, 10); if (lca != NULL) cout << "\nLCA(4, 10) = " << lca->key; else cout << "\nKeys are not present "; return 0;} // Java implementation to find lowest common ancestor of// n1 and n2 using one traversal of binary tree// It also handles cases even when n1 and n2 are not there in Tree /* Class containing left and right child of current node and key */class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ // Root of the Binary Tree Node root; static boolean v1 = false, v2 = false; // This function returns pointer to LCA of two given // values n1 and n2. // v1 is set as true by this function if n1 is found // v2 is set as true by this function if n2 is found Node findLCAUtil(Node node, int n1, int n2) { // Base case if (node == null) return null; //Store result in temp, in case of key match so that we can search for other key also. Node temp=null; // If either n1 or n2 matches with root's key, report the presence // by setting v1 or v2 as true and return root (Note that if a key // is ancestor of other, then the ancestor key becomes LCA) if (node.data == n1) { v1 = true; temp = node; } if (node.data == n2) { v2 = true; temp = node; } // Look for keys in left and right subtrees Node left_lca = findLCAUtil(node.left, n1, n2); Node right_lca = findLCAUtil(node.right, n1, n2); if (temp != null) return temp; // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca != null && right_lca != null) return node; // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // Finds lca of n1 and n2 under the subtree rooted with 'node' Node findLCA(int n1, int n2) { // Initialize n1 and n2 as not visited v1 = false; v2 = false; // Find lca of n1 and n2 using the technique discussed above Node lca = findLCAUtil(root, n1, n2); // Return LCA only if both n1 and n2 are present in tree if (v1 && v2) return lca; // Else return NULL return null; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Node lca = tree.findLCA(4, 5); if (lca != null) System.out.println("LCA(4, 5) = " + lca.data); else System.out.println("Keys are not present"); lca = tree.findLCA(4, 10); if (lca != null) System.out.println("LCA(4, 10) = " + lca.data); else System.out.println("Keys are not present"); }} """ Program to find LCA of n1 and n2 using one traversal of Binary treeIt handles all cases even when n1 or n2 is not there in tree""" # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # This function return pointer to LCA of two given values# n1 and n2# v1 is set as true by this function if n1 is found# v2 is set as true by this function if n2 is founddef findLCAUtil(root, n1, n2, v): # Base Case if root is None: return None # IF either n1 or n2 matches ith root's key, report # the presence by setting v1 or v2 as true and return # root (Note that if a key is ancestor of other, then # the ancestor key becomes LCA) if root.key == n1 : v[0] = True return root if root.key == n2: v[1] = True return root # Look for keys in left and right subtree left_lca = findLCAUtil(root.left, n1, n2, v) right_lca = findLCAUtil(root.right, n1, n2, v) # If both of the above calls return Non-NULL, then one key # is present in once subtree and other is present in other, # So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right subtree is LCA return left_lca if left_lca is not None else right_lca def find(root, k): # Base Case if root is None: return False # If key is present at root, or if left subtree or right # subtree , return true if (root.key == k or find(root.left, k) or find(root.right, k)): return True # Else return false return False # This function returns LCA of n1 and n2 on value if both# n1 and n2 are present in tree, otherwise returns Nonedef findLCA(root, n1, n2): # Initialize n1 and n2 as not visited v = [False, False] # Find lca of n1 and n2 using the technique discussed above lca = findLCAUtil(root, n1, n2, v) # Returns LCA only if both n1 and n2 are present in tree if (v[0] and v[1] or v[0] and find(lca, n2) or v[1] and find(lca, n1)): return lca # Else return None return None # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7) lca = findLCA(root, 4, 5) if lca is not None: print ("LCA(4, 5) = ", lca.key)else : print ("Keys are not present") lca = findLCA(root, 4, 10)if lca is not None: print ("LCA(4,10) = ", lca.key)else: print ("Keys are not present") # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // c# implementation to find lowest common ancestor of// n1 and n2 using one traversal of binary tree// It also handles cases even when n1 and n2 are not there in Tree /* Class containing left and right child of current node and key */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ // Root of the Binary Tree public Node root; public static bool v1 = false, v2 = false; // This function returns pointer to LCA of two given // values n1 and n2. // v1 is set as true by this function if n1 is found // v2 is set as true by this function if n2 is found public virtual Node findLCAUtil(Node node, int n1, int n2) { // Base case if (node == null) { return null; } //Store result in temp, in case of key match so that we can search for other key also. Node temp = null; // If either n1 or n2 matches with root's key, report the presence // by setting v1 or v2 as true and return root (Note that if a key // is ancestor of other, then the ancestor key becomes LCA) if (node.data == n1) { v1 = true; temp = node; } if (node.data == n2) { v2 = true; temp = node; } // Look for keys in left and right subtrees Node left_lca = findLCAUtil(node.left, n1, n2); Node right_lca = findLCAUtil(node.right, n1, n2); if (temp != null) { return temp; } // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca != null && right_lca != null) { return node; } // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // Finds lca of n1 and n2 under the subtree rooted with 'node' public virtual Node findLCA(int n1, int n2) { // Initialize n1 and n2 as not visited v1 = false; v2 = false; // Find lca of n1 and n2 using the technique discussed above Node lca = findLCAUtil(root, n1, n2); // Return LCA only if both n1 and n2 are present in tree if (v1 && v2) { return lca; } // Else return NULL return null; } /* Driver program to test above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Node lca = tree.findLCA(4, 5); if (lca != null) { Console.WriteLine("LCA(4, 5) = " + lca.data); } else { Console.WriteLine("Keys are not present"); } lca = tree.findLCA(4, 10); if (lca != null) { Console.WriteLine("LCA(4, 10) = " + lca.data); } else { Console.WriteLine("Keys are not present"); } }} // This code is contributed by Shrikant13 <script> // JavaScript implementation to find lowest// common ancestor of n1 and n2 using one// traversal of binary tree. It also handles// cases even when n1 and n2 are not there in Tree // Class containing left and right child// of current node and keyclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} class BinaryTree{ // Root of the Binary Treeconstructor(){ this.root = null; this.v1 = false; this.v2 = false;} // This function returns pointer to LCA// of two given values n1 and n2.// v1 is set as true by this function// if n1 is found// v2 is set as true by this function// if n2 is foundfindLCAUtil(node, n1, n2){ // Base case if (node == null) { return null; } // Store result in temp, in case of // key match so that we can search // for other key also. var temp = null; // If either n1 or n2 matches with root's key, // report the presence by setting v1 or v2 as // true and return root (Note that if a key // is ancestor of other, then the ancestor // key becomes LCA) if (node.data == n1) { this.v1 = true; temp = node; } if (node.data == n2) { this.v2 = true; temp = node; } // Look for keys in left and right subtrees var left_lca = this.findLCAUtil(node.left, n1, n2); var right_lca = this.findLCAUtil(node.right, n1, n2); if (temp != null) { return temp; } // If both of the above calls return Non-NULL, // then one key is present in once subtree and // other is present in other, So this node is the LCA if (left_lca != null && right_lca != null) { return node; } // Otherwise check if left subtree or // right subtree is LCA return left_lca != null ? left_lca : right_lca;} // Finds lca of n1 and n2 under the// subtree rooted with 'node'findLCA(n1, n2){ // Initialize n1 and n2 as not visited this.v1 = false; this.v2 = false; // Find lca of n1 and n2 using the // technique discussed above var lca = this.findLCAUtil(this.root, n1, n2); // Return LCA only if both n1 and n2 // are present in tree if (this.v1 && this.v2) { return lca; } // Else return NULL return null;}} // Driver codevar tree = new BinaryTree();tree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);tree.root.right.left = new Node(6);tree.root.right.right = new Node(7); var lca = tree.findLCA(4, 5);if (lca != null){ document.write("LCA(4, 5) = " + lca.data + "<br>");} else{ document.write("Keys are not present" + "<br>");} lca = tree.findLCA(4, 10);if (lca != null){ document.write("LCA(4, 10) = " + lca.data + "<br>");}else{ document.write("Keys are not present" + "<br>");} // This code is contributed by rdtank </script> Output: LCA(4, 5) = 2 Keys are not present Thanks to Dhruv for suggesting this extended solution. You may like to see the below articles as well : LCA using Parent Pointer Lowest Common Ancestor in a Binary Search Tree. Find LCA in Binary Tree using RMQPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Tushar Garg 6 shrikanth13 rutvik_56 pratham76 mukesh07 rdtank divyeshrabadiya07 surinderdawra388 samriddhisrivastava0626 amartyaghoshgfg simmytarika5 adityakumar129 Accolite Amazon American Express Expedia LCA MakeMyTrip Microsoft Payu Snapdeal Times Internet Twitter Tree Accolite Amazon Microsoft Snapdeal MakeMyTrip Payu Times Internet Expedia Twitter American Express Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Binary Tree | Set 2 (Properties) Decision Tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Deletion in a Binary Tree BFS vs DFS for Binary Tree
[ { "code": null, "e": 26523, "s": 26495, "text": "\n17 Apr, 2022" }, { "code": null, "e": 26651, "s": 26523, "text": "Given a binary tree (not a binary search tree) and two values say n1 and n2, write a program to find the least common ancestor." }, { "code": null, "e": 27366, "s": 26651, "text": "Following is definition of LCA from Wikipedia: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor. (Source Wiki) " }, { "code": null, "e": 27723, "s": 27368, "text": "We have discussed an efficient solution to find LCA in Binary Search Tree. In Binary Search Tree, using BST properties, we can find LCA in O(h) time where h is the height of the tree. Such an implementation is not possible in Binary Tree as keys Binary Tree nodes don’t follow any order. The following are different approaches to find LCA in Binary Tree." }, { "code": null, "e": 28103, "s": 27723, "text": "Method 1 (By Storing root to n1 and root to n2 paths): Following is a simple O(n) algorithm to find LCA of n1 and n2. 1) Find a path from the root to n1 and store it in a vector or array. 2) Find a path from the root to n2 and store it in another vector or array. 3) Traverse both paths till the values in arrays are the same. Return the common element just before the mismatch. " }, { "code": null, "e": 28159, "s": 28103, "text": "Following is the implementation of the above algorithm." }, { "code": null, "e": 28163, "s": 28159, "text": "C++" }, { "code": null, "e": 28168, "s": 28163, "text": "Java" }, { "code": null, "e": 28176, "s": 28168, "text": "Python3" }, { "code": null, "e": 28179, "s": 28176, "text": "C#" }, { "code": null, "e": 28190, "s": 28179, "text": "Javascript" }, { "code": "// C++ Program for Lowest Common Ancestor in a Binary Tree// A O(n) solution to find LCA of two given values n1 and n2#include <iostream>#include <vector> using namespace std; // A Binary Tree nodestruct Node{ int key; struct Node *left, *right;}; // Utility function creates a new binary tree node with given keyNode * newNode(int k){ Node *temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp;} // Finds the path from root node to given root of the tree, Stores the// path in a vector path[], returns true if path exists otherwise falsebool findPath(Node *root, vector<int> &path, int k){ // base case if (root == NULL) return false; // Store this node in path vector. The node will be removed if // not in path from root to k path.push_back(root->key); // See if the k is same as root's key if (root->key == k) return true; // Check if k is found in left or right sub-tree if ( (root->left && findPath(root->left, path, k)) || (root->right && findPath(root->right, path, k)) ) return true; // If not present in subtree rooted with root, remove root from // path[] and return false path.pop_back(); return false;} // Returns LCA if node n1, n2 are present in the given binary tree,// otherwise return -1int findLCA(Node *root, int n1, int n2){ // to store paths to n1 and n2 from the root vector<int> path1, path2; // Find paths from root to n1 and root to n1. If either n1 or n2 // is not present, return -1 if ( !findPath(root, path1, n1) || !findPath(root, path2, n2)) return -1; /* Compare the paths to get the first different value */ int i; for (i = 0; i < path1.size() && i < path2.size() ; i++) if (path1[i] != path2[i]) break; return path1[i-1];} // Driver program to test above functionsint main(){ // Let us create the Binary Tree shown in above diagram. Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << \"LCA(4, 5) = \" << findLCA(root, 4, 5); cout << \"\\nLCA(4, 6) = \" << findLCA(root, 4, 6); cout << \"\\nLCA(3, 4) = \" << findLCA(root, 3, 4); cout << \"\\nLCA(2, 4) = \" << findLCA(root, 2, 4); return 0;}", "e": 30570, "s": 28190, "text": null }, { "code": "// Java Program for Lowest Common Ancestor in a Binary Tree// A O(n) solution to find LCA of two given values n1 and n2import java.util.ArrayList;import java.util.List; // A Binary Tree nodeclass Node { int data; Node left, right; Node(int value) { data = value; left = right = null; }} public class BT_NoParentPtr_Solution1{ Node root; private List<Integer> path1 = new ArrayList<>(); private List<Integer> path2 = new ArrayList<>(); // Finds the path from root node to given root of the tree. int findLCA(int n1, int n2) { path1.clear(); path2.clear(); return findLCAInternal(root, n1, n2); } private int findLCAInternal(Node root, int n1, int n2) { if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { System.out.println((path1.size() > 0) ? \"n1 is present\" : \"n1 is missing\"); System.out.println((path2.size() > 0) ? \"n2 is present\" : \"n2 is missing\"); return -1; } int i; for (i = 0; i < path1.size() && i < path2.size(); i++) { // System.out.println(path1.get(i) + \" \" + path2.get(i)); if (!path1.get(i).equals(path2.get(i))) break; } return path1.get(i-1); } // Finds the path from root node to given root of the tree, Stores the // path in a vector path[], returns true if path exists otherwise false private boolean findPath(Node root, int n, List<Integer> path) { // base case if (root == null) { return false; } // Store this node . The node will be removed if // not in path from root to n. path.add(root.data); if (root.data == n) { return true; } if (root.left != null && findPath(root.left, n, path)) { return true; } if (root.right != null && findPath(root.right, n, path)) { return true; } // If not present in subtree rooted with root, remove root from // path[] and return false path.remove(path.size()-1); return false; } // Driver code public static void main(String[] args) { BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); System.out.println(\"LCA(4, 5): \" + tree.findLCA(4,5)); System.out.println(\"LCA(4, 6): \" + tree.findLCA(4,6)); System.out.println(\"LCA(3, 4): \" + tree.findLCA(3,4)); System.out.println(\"LCA(2, 4): \" + tree.findLCA(2,4)); }}// This code is contributed by Sreenivasulu Rayanki.", "e": 33440, "s": 30570, "text": null }, { "code": "# Python Program for Lowest Common Ancestor in a Binary Tree# O(n) solution to find LCS of two given values n1 and n2 # A binary tree nodeclass Node: # Constructor to create a new binary node def __init__(self, key): self.key = key self.left = None self.right = None # Finds the path from root node to given root of the tree.# Stores the path in a list path[], returns true if path# exists otherwise falsedef findPath( root, path, k): # Baes Case if root is None: return False # Store this node is path vector. The node will be # removed if not in path from root to k path.append(root.key) # See if the k is same as root's key if root.key == k : return True # Check if k is found in left or right sub-tree if ((root.left != None and findPath(root.left, path, k)) or (root.right!= None and findPath(root.right, path, k))): return True # If not present in subtree rooted with root, remove # root from path and return False path.pop() return False # Returns LCA if node n1 , n2 are present in the given# binary tree otherwise return -1def findLCA(root, n1, n2): # To store paths to n1 and n2 fromthe root path1 = [] path2 = [] # Find paths from root to n1 and root to n2. # If either n1 or n2 is not present , return -1 if (not findPath(root, path1, n1) or not findPath(root, path2, n2)): return -1 # Compare the paths to get the first different value i = 0 while(i < len(path1) and i < len(path2)): if path1[i] != path2[i]: break i += 1 return path1[i-1] # Driver program to test above function# Let's create the Binary Tree shown in above diagramroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7) print (\"LCA(4, 5) = %d\" %(findLCA(root, 4, 5,)))print (\"LCA(4, 6) = %d\" %(findLCA(root, 4, 6)))print (\"LCA(3, 4) = %d\" %(findLCA(root,3,4)))print (\"LCA(2, 4) = %d\" %(findLCA(root,2, 4))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 35565, "s": 33440, "text": null }, { "code": "// C# Program for Lowest Common// Ancestor in a Binary Tree// A O(n) solution to find LCA// of two given values n1 and n2using System.Collections;using System; // A Binary Tree nodeclass Node{ public int data; public Node left, right; public Node(int value) { data = value; left = right = null; }} public class BT_NoParentPtr_Solution1{ Node root; private ArrayList path1 = new ArrayList(); private ArrayList path2 = new ArrayList(); // Finds the path from root // node to given root of the // tree. int findLCA(int n1, int n2) { path1.Clear(); path2.Clear(); return findLCAInternal(root, n1, n2); } private int findLCAInternal(Node root, int n1, int n2){ if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { Console.Write((path1.Count > 0) ? \"n1 is present\" : \"n1 is missing\"); Console.Write((path2.Count > 0) ? \"n2 is present\" : \"n2 is missing\"); return -1; } int i; for (i = 0; i < path1.Count && i < path2.Count; i++) { // System.out.println(path1.get(i) // + \" \" + path2.get(i)); if ((int)path1[i] != (int)path2[i]) break; } return (int)path1[i - 1];} // Finds the path from root node// to given root of the tree,// Stores the path in a vector// path[], returns true if path// exists otherwise falseprivate bool findPath(Node root, int n, ArrayList path){ // base case if (root == null) { return false; } // Store this node . The node // will be removed if not in // path from root to n. path.Add(root.data); if (root.data == n) { return true; } if (root.left != null && findPath(root.left, n, path)) { return true; } if (root.right != null && findPath(root.right, n, path)) { return true; } // If not present in subtree //rooted with root, remove root // from path[] and return false path.RemoveAt(path.Count - 1); return false;} // Driver codepublic static void Main(String[] args){ BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Console.Write(\"LCA(4, 5): \" + tree.findLCA(4, 5)); Console.Write(\"\\nLCA(4, 6): \" + tree.findLCA(4, 6)); Console.Write(\"\\nLCA(3, 4): \" + tree.findLCA(3, 4)); Console.Write(\"\\nLCA(2, 4): \" + tree.findLCA(2, 4));}} // This code is contributed by Rutvik_56", "e": 38353, "s": 35565, "text": null }, { "code": "<script> // JavaScript Program for Lowest Common // Ancestor in a Binary Tree // A O(n) solution to find LCA of // two given values n1 and n2 class Node { constructor(value) { this.left = null; this.right = null; this.data = value; } } let root; let path1 = []; let path2 = []; // Finds the path from root node to given root of the tree. function findLCA(n1, n2) { path1 = []; path2 = []; return findLCAInternal(root, n1, n2); } function findLCAInternal(root, n1, n2) { if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { document.write((path1.length > 0) ? \"n1 is present\" : \"n1 is missing\"); document.write((path2.length > 0) ? \"n2 is present\" : \"n2 is missing\"); return -1; } let i; for (i = 0; i < path1.length && i < path2.length; i++) { // System.out.println(path1.get(i) + \" \" + path2.get(i)); if (path1[i] != path2[i]) break; } return path1[i-1]; } // Finds the path from root node to // given root of the tree, Stores the // path in a vector path[], returns true // if path exists otherwise false function findPath(root, n, path) { // base case if (root == null) { return false; } // Store this node . The node will be removed if // not in path from root to n. path.push(root.data); if (root.data == n) { return true; } if (root.left != null && findPath(root.left, n, path)) { return true; } if (root.right != null && findPath(root.right, n, path)) { return true; } // If not present in subtree rooted with root, // remove root from // path[] and return false path.pop(); return false; } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); document.write(\"LCA(4, 5) = \" + findLCA(4,5) + \"</br>\"); document.write(\"LCA(4, 6) = \" + findLCA(4,6) + \"</br>\"); document.write(\"LCA(3, 4) = \" + findLCA(3,4) + \"</br>\"); document.write(\"LCA(2, 4) = \" + findLCA(2,4)); </script>", "e": 40816, "s": 38353, "text": null }, { "code": null, "e": 40825, "s": 40816, "text": "Output: " }, { "code": null, "e": 40881, "s": 40825, "text": "LCA(4, 5) = 2\nLCA(4, 6) = 1\nLCA(3, 4) = 1\nLCA(2, 4) = 2" }, { "code": null, "e": 41104, "s": 40881, "text": "Time Complexity: The time complexity of the above solution is O(n). The tree is traversed twice, and then path arrays are compared. Thanks to Ravi Chandra Enaganti for suggesting the initial solution based on this method. " }, { "code": null, "e": 41902, "s": 41104, "text": "Method 2 (Using Single Traversal) Method 1 finds LCA in O(n) time but requires three tree traversals plus extra spaces for path arrays. If we assume that the keys n1 and n2 are present in Binary Tree, we can find LCA using a single traversal of Binary Tree and without extra storage for path arrays. The idea is to traverse the tree starting from the root. If any of the given keys (n1 and n2) matches with the root, then the root is LCA (assuming that both keys are present). If the root doesn’t match with any of the keys, we recur for the left and right subtree. The node which has one key present in its left subtree and the other key present in the right subtree is the LCA. If both keys lie in the left subtree, then the left subtree has LCA also, otherwise, LCA lies in the right subtree. " }, { "code": null, "e": 41906, "s": 41902, "text": "C++" }, { "code": null, "e": 41908, "s": 41906, "text": "C" }, { "code": null, "e": 41913, "s": 41908, "text": "Java" }, { "code": null, "e": 41921, "s": 41913, "text": "Python3" }, { "code": null, "e": 41924, "s": 41921, "text": "C#" }, { "code": null, "e": 41935, "s": 41924, "text": "Javascript" }, { "code": "/* C++ Program to find LCA of n1 and n2 using one traversal of Binary Tree */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ struct Node *left, *right; int key;}; // Utility function to create a new tree NodeNode* newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // This function returns pointer to LCA of two given values n1 and n2.// This function assumes that n1 and n2 are present in Binary Treestruct Node *findLCA(struct Node* root, int n1, int n2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node *left_lca = findLCA(root->left, n1, n2); Node *right_lca = findLCA(root->right, n1, n2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is LCA return (left_lca != NULL)? left_lca: right_lca;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above example Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << \"LCA(4, 5) = \" << findLCA(root, 4, 5)->key; cout << \"\\nLCA(4, 6) = \" << findLCA(root, 4, 6)->key; cout << \"\\nLCA(3, 4) = \" << findLCA(root, 3, 4)->key; cout << \"\\nLCA(2, 4) = \" << findLCA(root, 2, 4)->key; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 43891, "s": 41935, "text": null }, { "code": "// C Program to find LCA of n1 and n2 using one traversalof// Binary Tree#include <stdio.h>#include <stdlib.h> // A Binary Tree Nodetypedef struct Node { struct Node *left, *right; int key;}Node; // Utility function to create a new tree NodeNode* newNode(int key){ Node* temp = (Node*)malloc(sizeof(Node)); temp->key = key; temp->left = temp->right = NULL; return temp;} // This function returns pointer to LCA of two given values// n1 and n2. This function assumes that n1 and n2 are// present in Binary TreeNode* findLCA(Node* root, int n1, int n2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node* left_lca = findLCA(root->left, n1, n2); Node* right_lca = findLCA(root->right, n1, n2); // If both of the above calls return Non-NULL, then one // key is present in once subtree and other is present // in other, So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is // LCA return (left_lca != NULL) ? left_lca : right_lca;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); printf(\"LCA(4, 5) = %d\", findLCA(root, 4, 5)->key); printf(\"\\nLCA(4, 6) = %d\", findLCA(root, 4, 6)->key); printf(\"\\nLCA(3, 4) = %d\", findLCA(root, 3, 4)->key); printf(\"\\nLCA(2, 4) = %d\", findLCA(root, 2, 4)->key); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 45875, "s": 43891, "text": null }, { "code": "//Java implementation to find lowest common ancestor of// n1 and n2 using one traversal of binary tree /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ //Root of the Binary Tree Node root; Node findLCA(int n1, int n2) { return findLCA(root, n1, n2); } // This function returns pointer to LCA of two given // values n1 and n2. This function assumes that n1 and // n2 are present in Binary Tree Node findLCA(Node node, int n1, int n2) { // Base case if (node == null) return null; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (node.data == n1 || node.data == n2) return node; // Look for keys in left and right subtrees Node left_lca = findLCA(node.left, n1, n2); Node right_lca = findLCA(node.right, n1, n2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca!=null && right_lca!=null) return node; // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); System.out.println(\"LCA(4, 5) = \" + tree.findLCA(4, 5).data); System.out.println(\"LCA(4, 6) = \" + tree.findLCA(4, 6).data); System.out.println(\"LCA(3, 4) = \" + tree.findLCA(3, 4).data); System.out.println(\"LCA(2, 4) = \" + tree.findLCA(2, 4).data); }}", "e": 48190, "s": 45875, "text": null }, { "code": "# Python program to find LCA of n1 and n2 using one# traversal of Binary tree # A binary tree nodeclass Node: # Constructor to create a new tree node def __init__(self, key): self.key = key self.left = None self.right = None # This function returns pointer to LCA of two given# values n1 and n2# This function assumes that n1 and n2 are present in# Binary Treedef findLCA(root, n1, n2): # Base Case if root is None: return None # If either n1 or n2 matches with root's key, report # the presence by returning root (Note that if a key is # ancestor of other, then the ancestor key becomes LCA if root.key == n1 or root.key == n2: return root # Look for keys in left and right subtrees left_lca = findLCA(root.left, n1, n2) right_lca = findLCA(root.right, n1, n2) # If both of the above calls return Non-NULL, then one key # is present in once subtree and other is present in other, # So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right subtree is LCA return left_lca if left_lca is not None else right_lca # Driver program to test above function # Let us create a binary tree given in the above exampleroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)print (\"LCA(4,5) = \", findLCA(root, 4, 5).key)print (\"LCA(4,6) = \", findLCA(root, 4, 6).key)print (\"LCA(3,4) = \", findLCA(root, 3, 4).key)print (\"LCA(2,4) = \", findLCA(root, 2, 4).key) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 49860, "s": 48190, "text": null }, { "code": "// C# implementation to find lowest common// ancestor of n1 and n2 using one traversal// of binary treeusing System; // Class containing left and right// child of current node and key valuepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ // Root of the Binary TreeNode root; Node findLCA(int n1, int n2){ return findLCA(root, n1, n2);} // This function returns pointer to LCA// of two given values n1 and n2. This// function assumes that n1 and n2 are// present in Binary TreeNode findLCA(Node node, int n1, int n2){ // Base case if (node == null) return null; // If either n1 or n2 matches with // root's key, report the presence // by returning root (Note that if // a key is ancestor of other, // then the ancestor key becomes LCA if (node.data == n1 || node.data == n2) return node; // Look for keys in left and right subtrees Node left_lca = findLCA(node.left, n1, n2); Node right_lca = findLCA(node.right, n1, n2); // If both of the above calls return Non-NULL, // then one key is present in once subtree // and other is present in other, So this // node is the LCA if (left_lca != null && right_lca != null) return node; // Otherwise check if left subtree or // right subtree is LCA return (left_lca != null) ? left_lca : right_lca;} // Driver codepublic static void Main(string []args){ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Console.WriteLine(\"LCA(4, 5) = \" + tree.findLCA(4, 5).data); Console.WriteLine(\"LCA(4, 6) = \" + tree.findLCA(4, 6).data); Console.WriteLine(\"LCA(3, 4) = \" + tree.findLCA(3, 4).data); Console.WriteLine(\"LCA(2, 4) = \" + tree.findLCA(2, 4).data);}} // This code is contributed by pratham76", "e": 52060, "s": 49860, "text": null }, { "code": "<script> // JavaScript implementation to find // lowest common ancestor of // n1 and n2 using one traversal of binary tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } //Root of the Binary Tree let root; function findlCA(n1, n2) { return findLCA(root, n1, n2); } // This function returns pointer to LCA of two given // values n1 and n2. This function assumes that n1 and // n2 are present in Binary Tree function findLCA(node, n1, n2) { // Base case if (node == null) return null; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (node.data == n1 || node.data == n2) return node; // Look for keys in left and right subtrees let left_lca = findLCA(node.left, n1, n2); let right_lca = findLCA(node.right, n1, n2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca!=null && right_lca!=null) return node; // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); document.write(\"LCA(4, 5) = \" + findlCA(4, 5).data + \"</br>\"); document.write(\"LCA(4, 6) = \" + findlCA(4, 6).data + \"</br>\"); document.write(\"LCA(3, 4) = \" + findlCA(3, 4).data + \"</br>\"); document.write(\"LCA(2, 4) = \" + findlCA(2, 4).data + \"</br>\"); </script>", "e": 54101, "s": 52060, "text": null }, { "code": null, "e": 54110, "s": 54101, "text": "Output: " }, { "code": null, "e": 54166, "s": 54110, "text": "LCA(4, 5) = 2\nLCA(4, 6) = 1\nLCA(3, 4) = 1\nLCA(2, 4) = 2" }, { "code": null, "e": 54218, "s": 54166, "text": "Thanks to Atul Singh for suggesting this solution. " }, { "code": null, "e": 54353, "s": 54218, "text": "Time Complexity: The time complexity of the above solution is O(n) as the method does a simple tree traversal in a bottom-up fashion. " }, { "code": null, "e": 54550, "s": 54353, "text": "Note that the above method assumes that keys are present in Binary Tree. If one key is present and the other is absent, then it returns the present key as LCA (Ideally should have returned NULL). " }, { "code": null, "e": 54741, "s": 54550, "text": "We can extend this method to handle all cases bypassing two boolean variables v1 and v2. v1 is set as true when n1 is present in the tree and v2 is set as true if n2 is present in the tree. " }, { "code": null, "e": 54745, "s": 54741, "text": "C++" }, { "code": null, "e": 54750, "s": 54745, "text": "Java" }, { "code": null, "e": 54758, "s": 54750, "text": "Python3" }, { "code": null, "e": 54761, "s": 54758, "text": "C#" }, { "code": null, "e": 54772, "s": 54761, "text": "Javascript" }, { "code": "/* C++ program to find LCA of n1 and n2 using one traversal of Binary Tree. It handles all cases even when n1 or n2 is not there in Binary Tree */#include <iostream>using namespace std; // A Binary Tree Nodestruct Node{ struct Node *left, *right; int key;}; // Utility function to create a new tree NodeNode* newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // This function returns pointer to LCA of two given values n1 and n2.// v1 is set as true by this function if n1 is found// v2 is set as true by this function if n2 is foundstruct Node *findLCAUtil(struct Node* root, int n1, int n2, bool &v1, bool &v2){ // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report the presence // by setting v1 or v2 as true and return root (Note that if a key // is ancestor of other, then the ancestor key becomes LCA) if (root->key == n1) { v1 = true; return root; } if (root->key == n2) { v2 = true; return root; } // Look for keys in left and right subtrees Node *left_lca = findLCAUtil(root->left, n1, n2, v1, v2); Node *right_lca = findLCAUtil(root->right, n1, n2, v1, v2); // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is LCA return (left_lca != NULL)? left_lca: right_lca;} // Returns true if key k is present in tree rooted with rootbool find(Node *root, int k){ // Base Case if (root == NULL) return false; // If key is present at root, or in left subtree or right subtree, // return true; if (root->key == k || find(root->left, k) || find(root->right, k)) return true; // Else return false return false;} // This function returns LCA of n1 and n2 only if both n1 and n2 are present// in tree, otherwise returns NULL;Node *findLCA(Node *root, int n1, int n2){ // Initialize n1 and n2 as not visited bool v1 = false, v2 = false; // Find lca of n1 and n2 using the technique discussed above Node *lca = findLCAUtil(root, n1, n2, v1, v2); // Return LCA only if both n1 and n2 are present in tree if (v1 && v2 || v1 && find(lca, n2) || v2 && find(lca, n1)) return lca; // Else return NULL return NULL;} // Driver program to test above functionsint main(){ // Let us create binary tree given in the above example Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); Node *lca = findLCA(root, 4, 5); if (lca != NULL) cout << \"LCA(4, 5) = \" << lca->key; else cout << \"Keys are not present \"; lca = findLCA(root, 4, 10); if (lca != NULL) cout << \"\\nLCA(4, 10) = \" << lca->key; else cout << \"\\nKeys are not present \"; return 0;}", "e": 57894, "s": 54772, "text": null }, { "code": "// Java implementation to find lowest common ancestor of// n1 and n2 using one traversal of binary tree// It also handles cases even when n1 and n2 are not there in Tree /* Class containing left and right child of current node and key */class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ // Root of the Binary Tree Node root; static boolean v1 = false, v2 = false; // This function returns pointer to LCA of two given // values n1 and n2. // v1 is set as true by this function if n1 is found // v2 is set as true by this function if n2 is found Node findLCAUtil(Node node, int n1, int n2) { // Base case if (node == null) return null; //Store result in temp, in case of key match so that we can search for other key also. Node temp=null; // If either n1 or n2 matches with root's key, report the presence // by setting v1 or v2 as true and return root (Note that if a key // is ancestor of other, then the ancestor key becomes LCA) if (node.data == n1) { v1 = true; temp = node; } if (node.data == n2) { v2 = true; temp = node; } // Look for keys in left and right subtrees Node left_lca = findLCAUtil(node.left, n1, n2); Node right_lca = findLCAUtil(node.right, n1, n2); if (temp != null) return temp; // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca != null && right_lca != null) return node; // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // Finds lca of n1 and n2 under the subtree rooted with 'node' Node findLCA(int n1, int n2) { // Initialize n1 and n2 as not visited v1 = false; v2 = false; // Find lca of n1 and n2 using the technique discussed above Node lca = findLCAUtil(root, n1, n2); // Return LCA only if both n1 and n2 are present in tree if (v1 && v2) return lca; // Else return NULL return null; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Node lca = tree.findLCA(4, 5); if (lca != null) System.out.println(\"LCA(4, 5) = \" + lca.data); else System.out.println(\"Keys are not present\"); lca = tree.findLCA(4, 10); if (lca != null) System.out.println(\"LCA(4, 10) = \" + lca.data); else System.out.println(\"Keys are not present\"); }}", "e": 61061, "s": 57894, "text": null }, { "code": "\"\"\" Program to find LCA of n1 and n2 using one traversal of Binary treeIt handles all cases even when n1 or n2 is not there in tree\"\"\" # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # This function return pointer to LCA of two given values# n1 and n2# v1 is set as true by this function if n1 is found# v2 is set as true by this function if n2 is founddef findLCAUtil(root, n1, n2, v): # Base Case if root is None: return None # IF either n1 or n2 matches ith root's key, report # the presence by setting v1 or v2 as true and return # root (Note that if a key is ancestor of other, then # the ancestor key becomes LCA) if root.key == n1 : v[0] = True return root if root.key == n2: v[1] = True return root # Look for keys in left and right subtree left_lca = findLCAUtil(root.left, n1, n2, v) right_lca = findLCAUtil(root.right, n1, n2, v) # If both of the above calls return Non-NULL, then one key # is present in once subtree and other is present in other, # So this node is the LCA if left_lca and right_lca: return root # Otherwise check if left subtree or right subtree is LCA return left_lca if left_lca is not None else right_lca def find(root, k): # Base Case if root is None: return False # If key is present at root, or if left subtree or right # subtree , return true if (root.key == k or find(root.left, k) or find(root.right, k)): return True # Else return false return False # This function returns LCA of n1 and n2 on value if both# n1 and n2 are present in tree, otherwise returns Nonedef findLCA(root, n1, n2): # Initialize n1 and n2 as not visited v = [False, False] # Find lca of n1 and n2 using the technique discussed above lca = findLCAUtil(root, n1, n2, v) # Returns LCA only if both n1 and n2 are present in tree if (v[0] and v[1] or v[0] and find(lca, n2) or v[1] and find(lca, n1)): return lca # Else return None return None # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7) lca = findLCA(root, 4, 5) if lca is not None: print (\"LCA(4, 5) = \", lca.key)else : print (\"Keys are not present\") lca = findLCA(root, 4, 10)if lca is not None: print (\"LCA(4,10) = \", lca.key)else: print (\"Keys are not present\") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 63739, "s": 61061, "text": null }, { "code": "using System; // c# implementation to find lowest common ancestor of// n1 and n2 using one traversal of binary tree// It also handles cases even when n1 and n2 are not there in Tree /* Class containing left and right child of current node and key */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ // Root of the Binary Tree public Node root; public static bool v1 = false, v2 = false; // This function returns pointer to LCA of two given // values n1 and n2. // v1 is set as true by this function if n1 is found // v2 is set as true by this function if n2 is found public virtual Node findLCAUtil(Node node, int n1, int n2) { // Base case if (node == null) { return null; } //Store result in temp, in case of key match so that we can search for other key also. Node temp = null; // If either n1 or n2 matches with root's key, report the presence // by setting v1 or v2 as true and return root (Note that if a key // is ancestor of other, then the ancestor key becomes LCA) if (node.data == n1) { v1 = true; temp = node; } if (node.data == n2) { v2 = true; temp = node; } // Look for keys in left and right subtrees Node left_lca = findLCAUtil(node.left, n1, n2); Node right_lca = findLCAUtil(node.right, n1, n2); if (temp != null) { return temp; } // If both of the above calls return Non-NULL, then one key // is present in once subtree and other is present in other, // So this node is the LCA if (left_lca != null && right_lca != null) { return node; } // Otherwise check if left subtree or right subtree is LCA return (left_lca != null) ? left_lca : right_lca; } // Finds lca of n1 and n2 under the subtree rooted with 'node' public virtual Node findLCA(int n1, int n2) { // Initialize n1 and n2 as not visited v1 = false; v2 = false; // Find lca of n1 and n2 using the technique discussed above Node lca = findLCAUtil(root, n1, n2); // Return LCA only if both n1 and n2 are present in tree if (v1 && v2) { return lca; } // Else return NULL return null; } /* Driver program to test above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Node lca = tree.findLCA(4, 5); if (lca != null) { Console.WriteLine(\"LCA(4, 5) = \" + lca.data); } else { Console.WriteLine(\"Keys are not present\"); } lca = tree.findLCA(4, 10); if (lca != null) { Console.WriteLine(\"LCA(4, 10) = \" + lca.data); } else { Console.WriteLine(\"Keys are not present\"); } }} // This code is contributed by Shrikant13", "e": 67158, "s": 63739, "text": null }, { "code": "<script> // JavaScript implementation to find lowest// common ancestor of n1 and n2 using one// traversal of binary tree. It also handles// cases even when n1 and n2 are not there in Tree // Class containing left and right child// of current node and keyclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} class BinaryTree{ // Root of the Binary Treeconstructor(){ this.root = null; this.v1 = false; this.v2 = false;} // This function returns pointer to LCA// of two given values n1 and n2.// v1 is set as true by this function// if n1 is found// v2 is set as true by this function// if n2 is foundfindLCAUtil(node, n1, n2){ // Base case if (node == null) { return null; } // Store result in temp, in case of // key match so that we can search // for other key also. var temp = null; // If either n1 or n2 matches with root's key, // report the presence by setting v1 or v2 as // true and return root (Note that if a key // is ancestor of other, then the ancestor // key becomes LCA) if (node.data == n1) { this.v1 = true; temp = node; } if (node.data == n2) { this.v2 = true; temp = node; } // Look for keys in left and right subtrees var left_lca = this.findLCAUtil(node.left, n1, n2); var right_lca = this.findLCAUtil(node.right, n1, n2); if (temp != null) { return temp; } // If both of the above calls return Non-NULL, // then one key is present in once subtree and // other is present in other, So this node is the LCA if (left_lca != null && right_lca != null) { return node; } // Otherwise check if left subtree or // right subtree is LCA return left_lca != null ? left_lca : right_lca;} // Finds lca of n1 and n2 under the// subtree rooted with 'node'findLCA(n1, n2){ // Initialize n1 and n2 as not visited this.v1 = false; this.v2 = false; // Find lca of n1 and n2 using the // technique discussed above var lca = this.findLCAUtil(this.root, n1, n2); // Return LCA only if both n1 and n2 // are present in tree if (this.v1 && this.v2) { return lca; } // Else return NULL return null;}} // Driver codevar tree = new BinaryTree();tree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);tree.root.right.left = new Node(6);tree.root.right.right = new Node(7); var lca = tree.findLCA(4, 5);if (lca != null){ document.write(\"LCA(4, 5) = \" + lca.data + \"<br>\");} else{ document.write(\"Keys are not present\" + \"<br>\");} lca = tree.findLCA(4, 10);if (lca != null){ document.write(\"LCA(4, 10) = \" + lca.data + \"<br>\");}else{ document.write(\"Keys are not present\" + \"<br>\");} // This code is contributed by rdtank </script>", "e": 70158, "s": 67158, "text": null }, { "code": null, "e": 70167, "s": 70158, "text": "Output: " }, { "code": null, "e": 70202, "s": 70167, "text": "LCA(4, 5) = 2\nKeys are not present" }, { "code": null, "e": 70332, "s": 70202, "text": "Thanks to Dhruv for suggesting this extended solution. You may like to see the below articles as well : LCA using Parent Pointer " }, { "code": null, "e": 70381, "s": 70332, "text": "Lowest Common Ancestor in a Binary Search Tree. " }, { "code": null, "e": 70538, "s": 70381, "text": "Find LCA in Binary Tree using RMQPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 70552, "s": 70538, "text": "Tushar Garg 6" }, { "code": null, "e": 70564, "s": 70552, "text": "shrikanth13" }, { "code": null, "e": 70574, "s": 70564, "text": "rutvik_56" }, { "code": null, "e": 70584, "s": 70574, "text": "pratham76" }, { "code": null, "e": 70593, "s": 70584, "text": "mukesh07" }, { "code": null, "e": 70600, "s": 70593, "text": "rdtank" }, { "code": null, "e": 70618, "s": 70600, "text": "divyeshrabadiya07" }, { "code": null, "e": 70635, "s": 70618, "text": "surinderdawra388" }, { "code": null, "e": 70659, "s": 70635, "text": "samriddhisrivastava0626" }, { "code": null, "e": 70675, "s": 70659, "text": "amartyaghoshgfg" }, { "code": null, "e": 70688, "s": 70675, "text": "simmytarika5" }, { "code": null, "e": 70703, "s": 70688, "text": "adityakumar129" }, { "code": null, "e": 70712, "s": 70703, "text": "Accolite" }, { "code": null, "e": 70719, "s": 70712, "text": "Amazon" }, { "code": null, "e": 70736, "s": 70719, "text": "American Express" }, { "code": null, "e": 70744, "s": 70736, "text": "Expedia" }, { "code": null, "e": 70748, "s": 70744, "text": "LCA" }, { "code": null, "e": 70759, "s": 70748, "text": "MakeMyTrip" }, { "code": null, "e": 70769, "s": 70759, "text": "Microsoft" }, { "code": null, "e": 70774, "s": 70769, "text": "Payu" }, { "code": null, "e": 70783, "s": 70774, "text": "Snapdeal" }, { "code": null, "e": 70798, "s": 70783, "text": "Times Internet" }, { "code": null, "e": 70806, "s": 70798, "text": "Twitter" }, { "code": null, "e": 70811, "s": 70806, "text": "Tree" }, { "code": null, "e": 70820, "s": 70811, "text": "Accolite" }, { "code": null, "e": 70827, "s": 70820, "text": "Amazon" }, { "code": null, "e": 70837, "s": 70827, "text": "Microsoft" }, { "code": null, "e": 70846, "s": 70837, "text": "Snapdeal" }, { "code": null, "e": 70857, "s": 70846, "text": "MakeMyTrip" }, { "code": null, "e": 70862, "s": 70857, "text": "Payu" }, { "code": null, "e": 70877, "s": 70862, "text": "Times Internet" }, { "code": null, "e": 70885, "s": 70877, "text": "Expedia" }, { "code": null, "e": 70893, "s": 70885, "text": "Twitter" }, { "code": null, "e": 70910, "s": 70893, "text": "American Express" }, { "code": null, "e": 70915, "s": 70910, "text": "Tree" }, { "code": null, "e": 71013, "s": 70915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 71056, "s": 71013, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 71097, "s": 71056, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 71130, "s": 71097, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 71144, "s": 71130, "text": "Decision Tree" }, { "code": null, "e": 71202, "s": 71144, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 71238, "s": 71202, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 71321, "s": 71238, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 71337, "s": 71321, "text": "Expression Tree" }, { "code": null, "e": 71363, "s": 71337, "text": "Deletion in a Binary Tree" } ]
DCL Full Form - GeeksforGeeks
14 May, 2020 DCL stands for Data Control Language in Structured Query Language (SQL). As the name suggests these commands are used to control privilege in the database. The privileges (Right to access the data) are required for performing all the database operations like creating tables, views, or sequences.DCL command is a statement that is used to perform the work related to the rights, permissions, and other control of the database system. There are two types of Privileges in database: System Privilege Object Privilege Unauthorized access to the data should be prevented in order to achieve security in our database DCL commands maintain the database effectively than anyone else other than database administrator is not allowed to access the data without permission. These commands provide flexibility to the data administrator to set and remove database permissions in granular fashion. The two most important DCL commands are: GRANT REVOKE This command is used to grant permission to the user to perform a particular operation on a particular object. If you are a database administrator and you want to restrict user accessibility such as one who only views the data or may only update the data. You can give the privilege permission to the users according to your wish. Syntax: GRANT privilege_list ON Object_name TO user_name; This command is used to take permission/access back from the user. If you want to return permission from the database that you have granted to the users at that time you need to run REVOKE command. Syntax: REVOKE privilege_list ON object_name FROM user_name; Following commands are granted to the user as a Privilege List: EXECUTE UPDATE SELECT DELETE ALTER ALL It allows to restrict the user from accessing data in database. It ensures security in database when the data is exposed to multiple users. It is the wholesome responsibility of the data owner or data administrator to maintain the authority of grant and revoke privileges to the users preventing any threat to data. It prevents other users to make changes in database who have no access to Database Picked DBMS Full Form SQL Write From Home DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS What is Temporary Table in SQL? KDD Process in Data Mining Conflict Serializability in DBMS DBA Full Form HTTP Full Form RDBMS Full Form CDMA Full Form SCTP Full Form
[ { "code": null, "e": 25549, "s": 25521, "text": "\n14 May, 2020" }, { "code": null, "e": 25983, "s": 25549, "text": "DCL stands for Data Control Language in Structured Query Language (SQL). As the name suggests these commands are used to control privilege in the database. The privileges (Right to access the data) are required for performing all the database operations like creating tables, views, or sequences.DCL command is a statement that is used to perform the work related to the rights, permissions, and other control of the database system." }, { "code": null, "e": 26030, "s": 25983, "text": "There are two types of Privileges in database:" }, { "code": null, "e": 26047, "s": 26030, "text": "System Privilege" }, { "code": null, "e": 26064, "s": 26047, "text": "Object Privilege" }, { "code": null, "e": 26161, "s": 26064, "text": "Unauthorized access to the data should be prevented in order to achieve security in our database" }, { "code": null, "e": 26313, "s": 26161, "text": "DCL commands maintain the database effectively than anyone else other than database administrator is not allowed to access the data without permission." }, { "code": null, "e": 26434, "s": 26313, "text": "These commands provide flexibility to the data administrator to set and remove database permissions in granular fashion." }, { "code": null, "e": 26475, "s": 26434, "text": "The two most important DCL commands are:" }, { "code": null, "e": 26481, "s": 26475, "text": "GRANT" }, { "code": null, "e": 26488, "s": 26481, "text": "REVOKE" }, { "code": null, "e": 26819, "s": 26488, "text": "This command is used to grant permission to the user to perform a particular operation on a particular object. If you are a database administrator and you want to restrict user accessibility such as one who only views the data or may only update the data. You can give the privilege permission to the users according to your wish." }, { "code": null, "e": 26827, "s": 26819, "text": "Syntax:" }, { "code": null, "e": 26878, "s": 26827, "text": "GRANT privilege_list\nON Object_name\nTO user_name;\n" }, { "code": null, "e": 27076, "s": 26878, "text": "This command is used to take permission/access back from the user. If you want to return permission from the database that you have granted to the users at that time you need to run REVOKE command." }, { "code": null, "e": 27084, "s": 27076, "text": "Syntax:" }, { "code": null, "e": 27138, "s": 27084, "text": "REVOKE privilege_list\nON object_name\nFROM user_name;\n" }, { "code": null, "e": 27202, "s": 27138, "text": "Following commands are granted to the user as a Privilege List:" }, { "code": null, "e": 27210, "s": 27202, "text": "EXECUTE" }, { "code": null, "e": 27217, "s": 27210, "text": "UPDATE" }, { "code": null, "e": 27224, "s": 27217, "text": "SELECT" }, { "code": null, "e": 27231, "s": 27224, "text": "DELETE" }, { "code": null, "e": 27237, "s": 27231, "text": "ALTER" }, { "code": null, "e": 27241, "s": 27237, "text": "ALL" }, { "code": null, "e": 27305, "s": 27241, "text": "It allows to restrict the user from accessing data in database." }, { "code": null, "e": 27381, "s": 27305, "text": "It ensures security in database when the data is exposed to multiple users." }, { "code": null, "e": 27557, "s": 27381, "text": "It is the wholesome responsibility of the data owner or data administrator to maintain the authority of grant and revoke privileges to the users preventing any threat to data." }, { "code": null, "e": 27640, "s": 27557, "text": "It prevents other users to make changes in database who have no access to Database" }, { "code": null, "e": 27647, "s": 27640, "text": "Picked" }, { "code": null, "e": 27652, "s": 27647, "text": "DBMS" }, { "code": null, "e": 27662, "s": 27652, "text": "Full Form" }, { "code": null, "e": 27666, "s": 27662, "text": "SQL" }, { "code": null, "e": 27682, "s": 27666, "text": "Write From Home" }, { "code": null, "e": 27687, "s": 27682, "text": "DBMS" }, { "code": null, "e": 27691, "s": 27687, "text": "SQL" }, { "code": null, "e": 27789, "s": 27691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27806, "s": 27789, "text": "Deadlock in DBMS" }, { "code": null, "e": 27847, "s": 27806, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27879, "s": 27847, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27906, "s": 27879, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27939, "s": 27906, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 27953, "s": 27939, "text": "DBA Full Form" }, { "code": null, "e": 27968, "s": 27953, "text": "HTTP Full Form" }, { "code": null, "e": 27984, "s": 27968, "text": "RDBMS Full Form" }, { "code": null, "e": 27999, "s": 27984, "text": "CDMA Full Form" } ]
ASCII() Function in SQL Server - GeeksforGeeks
07 Oct, 2020 The ASCII() function returns the ASCII value of the leftmost character of a character expression. Syntax : ASCII(character_expression) Parameter :This method accepts a single-parameter as mentioned above and described below :character_expression :It can be a literal character, an expression of a string, or a column. If more than one character is entered, it will only return the value for the leftmost character.Returns :It returns the ASCII code value of its leftmost character. Example-1 :When the arguments hold the single uppercase and lowercase letter. SELECT ASCII('A') AS A, ASCII('a') AS a, ASCII('Z') AS Z, ASCII('z') AS z; Output : Example-2 :When the arguments hold the single number and special character. SELECT ASCII('1') AS [1], ASCII('#') AS #, ASCII(9) AS [9], ASCII('@') AS [@]; Output : Example-3 :When the arguments hold the expression of a string. SELECT ASCII('GeeksForGeeks'); Output : 71 Example-4 :Using ASCII() function with table columns.Table – Player_Details SELECT PlayerName, ASCII(PlayerName) AS AsciiCodeOfFirstChar FROM Player_Details; Output : SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL?
[ { "code": null, "e": 25098, "s": 25070, "text": "\n07 Oct, 2020" }, { "code": null, "e": 25196, "s": 25098, "text": "The ASCII() function returns the ASCII value of the leftmost character of a character expression." }, { "code": null, "e": 25205, "s": 25196, "text": "Syntax :" }, { "code": null, "e": 25233, "s": 25205, "text": "ASCII(character_expression)" }, { "code": null, "e": 25580, "s": 25233, "text": "Parameter :This method accepts a single-parameter as mentioned above and described below :character_expression :It can be a literal character, an expression of a string, or a column. If more than one character is entered, it will only return the value for the leftmost character.Returns :It returns the ASCII code value of its leftmost character." }, { "code": null, "e": 25658, "s": 25580, "text": "Example-1 :When the arguments hold the single uppercase and lowercase letter." }, { "code": null, "e": 25733, "s": 25658, "text": "SELECT ASCII('A') AS A, ASCII('a') AS a,\nASCII('Z') AS Z, ASCII('z') AS z;" }, { "code": null, "e": 25742, "s": 25733, "text": "Output :" }, { "code": null, "e": 25818, "s": 25742, "text": "Example-2 :When the arguments hold the single number and special character." }, { "code": null, "e": 25898, "s": 25818, "text": "SELECT ASCII('1') AS [1], ASCII('#') AS #,\nASCII(9) AS [9], ASCII('@') AS [@]; " }, { "code": null, "e": 25907, "s": 25898, "text": "Output :" }, { "code": null, "e": 25970, "s": 25907, "text": "Example-3 :When the arguments hold the expression of a string." }, { "code": null, "e": 26001, "s": 25970, "text": "SELECT ASCII('GeeksForGeeks');" }, { "code": null, "e": 26010, "s": 26001, "text": "Output :" }, { "code": null, "e": 26013, "s": 26010, "text": "71" }, { "code": null, "e": 26089, "s": 26013, "text": "Example-4 :Using ASCII() function with table columns.Table – Player_Details" }, { "code": null, "e": 26171, "s": 26089, "text": "SELECT PlayerName, ASCII(PlayerName) AS AsciiCodeOfFirstChar\nFROM Player_Details;" }, { "code": null, "e": 26180, "s": 26171, "text": "Output :" }, { "code": null, "e": 26191, "s": 26180, "text": "SQL-Server" }, { "code": null, "e": 26195, "s": 26191, "text": "SQL" }, { "code": null, "e": 26199, "s": 26195, "text": "SQL" }, { "code": null, "e": 26297, "s": 26199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26321, "s": 26297, "text": "SQL Interview Questions" }, { "code": null, "e": 26332, "s": 26321, "text": "CTE in SQL" }, { "code": null, "e": 26398, "s": 26332, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26443, "s": 26398, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26475, "s": 26443, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26514, "s": 26475, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 26529, "s": 26514, "text": "SQL - ORDER BY" }, { "code": null, "e": 26544, "s": 26529, "text": "SQL | Subquery" }, { "code": null, "e": 26601, "s": 26544, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" } ]
conj() function in C++ with Examples - GeeksforGeeks
05 Aug, 2021 The conj() function is defined in the complex header file. This function is used to find the conjugate of the complex number z. If we represent a complex number z as (real, img), then its conjugate is (real, -img).Syntax: template<class T> complex<T> conj (const complex<T>& Z); Parameter: z: This method takes a mandatory parameter z which represents the complex number. Return value: This function returns the conjugate of the complex number z.Below programs illustrate the conj() function for complex number in C++:Example 1:- CPP // C++ program to demonstrate// example of conj() function. #include <bits/stdc++.h>using namespace std; // driver programint main (){ complex<double> complexnumber (3.0, 2.4); cout << "The conjugate of " << complexnumber << " is: "; // use of conj() function cout << conj(complexnumber) << endl; return 0;} The conjugate of (3,2.4) is: (3,-2.4) Example 2:- CPP // C++ program to demonstrate// example of conj() function. #include <bits/stdc++.h>using namespace std; // driver programint main (){ complex<double> complexnumber (2.0, 9.0); cout << "The conjugate of " << complexnumber << " is: "; // use of conj() function cout << conj(complexnumber) << endl; return 0;} The conjugate of (2,9) is: (2,-9) sagar0719kumar CPP-Library cpp-math C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Convert string to char array in C++ Iterators in C++ STL Inline Functions in C++ List in C++ Standard Template Library (STL) Multithreading in C++
[ { "code": null, "e": 24098, "s": 24070, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24322, "s": 24098, "text": "The conj() function is defined in the complex header file. This function is used to find the conjugate of the complex number z. If we represent a complex number z as (real, img), then its conjugate is (real, -img).Syntax: " }, { "code": null, "e": 24385, "s": 24322, "text": "template<class T> complex<T> \n conj (const complex<T>& Z);" }, { "code": null, "e": 24398, "s": 24385, "text": "Parameter: " }, { "code": null, "e": 24480, "s": 24398, "text": "z: This method takes a mandatory parameter z which represents the complex number." }, { "code": null, "e": 24639, "s": 24480, "text": "Return value: This function returns the conjugate of the complex number z.Below programs illustrate the conj() function for complex number in C++:Example 1:- " }, { "code": null, "e": 24643, "s": 24639, "text": "CPP" }, { "code": "// C++ program to demonstrate// example of conj() function. #include <bits/stdc++.h>using namespace std; // driver programint main (){ complex<double> complexnumber (3.0, 2.4); cout << \"The conjugate of \" << complexnumber << \" is: \"; // use of conj() function cout << conj(complexnumber) << endl; return 0;}", "e": 24962, "s": 24643, "text": null }, { "code": null, "e": 25000, "s": 24962, "text": "The conjugate of (3,2.4) is: (3,-2.4)" }, { "code": null, "e": 25014, "s": 25002, "text": "Example 2:-" }, { "code": null, "e": 25018, "s": 25014, "text": "CPP" }, { "code": "// C++ program to demonstrate// example of conj() function. #include <bits/stdc++.h>using namespace std; // driver programint main (){ complex<double> complexnumber (2.0, 9.0); cout << \"The conjugate of \" << complexnumber << \" is: \"; // use of conj() function cout << conj(complexnumber) << endl; return 0;}", "e": 25337, "s": 25018, "text": null }, { "code": null, "e": 25371, "s": 25337, "text": "The conjugate of (2,9) is: (2,-9)" }, { "code": null, "e": 25388, "s": 25373, "text": "sagar0719kumar" }, { "code": null, "e": 25400, "s": 25388, "text": "CPP-Library" }, { "code": null, "e": 25409, "s": 25400, "text": "cpp-math" }, { "code": null, "e": 25413, "s": 25409, "text": "C++" }, { "code": null, "e": 25417, "s": 25413, "text": "CPP" }, { "code": null, "e": 25515, "s": 25417, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25543, "s": 25515, "text": "Operator Overloading in C++" }, { "code": null, "e": 25563, "s": 25543, "text": "Polymorphism in C++" }, { "code": null, "e": 25587, "s": 25563, "text": "Sorting a vector in C++" }, { "code": null, "e": 25620, "s": 25587, "text": "Friend class and function in C++" }, { "code": null, "e": 25664, "s": 25620, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 25700, "s": 25664, "text": "Convert string to char array in C++" }, { "code": null, "e": 25721, "s": 25700, "text": "Iterators in C++ STL" }, { "code": null, "e": 25745, "s": 25721, "text": "Inline Functions in C++" }, { "code": null, "e": 25789, "s": 25745, "text": "List in C++ Standard Template Library (STL)" } ]
Groovy - sqrt()
The method returns the square root of the argument. double sqrt(double d) d - Any primitive data type. This method Returns the square root of the argument. Following is an example of the usage of this method − class Example { static void main(String[] args) { double x = 11.635; double y = 2.76; System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x)); } } When we run the above program, we will get the following result − The value of e is 2.7183 sqrt(11.635) is 3.411 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2290, "s": 2238, "text": "The method returns the square root of the argument." }, { "code": null, "e": 2313, "s": 2290, "text": "double sqrt(double d)\n" }, { "code": null, "e": 2342, "s": 2313, "text": "d - Any primitive data type." }, { "code": null, "e": 2395, "s": 2342, "text": "This method Returns the square root of the argument." }, { "code": null, "e": 2449, "s": 2395, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2695, "s": 2449, "text": "class Example { \n static void main(String[] args) { \n double x = 11.635; \n double y = 2.76; \n\t \n System.out.printf(\"The value of e is %.4f%n\", Math.E); \n System.out.printf(\"sqrt(%.3f) is %.3f%n\", x, Math.sqrt(x)); \n } \n}" }, { "code": null, "e": 2761, "s": 2695, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2810, "s": 2761, "text": "The value of e is 2.7183 \nsqrt(11.635) is 3.411\n" }, { "code": null, "e": 2843, "s": 2810, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2861, "s": 2843, "text": " Krishna Sakinala" }, { "code": null, "e": 2896, "s": 2861, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2914, "s": 2896, "text": " Packt Publishing" }, { "code": null, "e": 2921, "s": 2914, "text": " Print" }, { "code": null, "e": 2932, "s": 2921, "text": " Add Notes" } ]
Web Scraping using Selenium and YOLO to build Computer Vision datasets | by Borja Souto García | Towards Data Science
If we ask several experts about the keys of a Computer Vision project (especially if we want a real application), maybe one the most repeated element (and in my opinion the most important thing) is the dataset. The problem appears when we also ask about the most arduous and laborious task, which answer also usually is the same: the dataset. The task to compose a dataset can be summarized in three steps: Capture images.Annotate images: labeling the sample for a set of classes.Validation: checking if the labels are correct. Capture images. Annotate images: labeling the sample for a set of classes. Validation: checking if the labels are correct. The first thing we would do is to resort to state-of-the-art datasets that can be used for our task, but the problem is we don’t always find what we need. At this moment we are facing a manual and a painful task. This article shows how to avoid this manual work. Using Selenium [1](an open-source web-based automation tool), Instagram (indirectly one of the largest image databases in the world) and YOLO [2](one of the most employed deep learning algorithms in object detection) we can generate a dataset automatically (the only thing you can’t avoid is the validation step). To show a simple example, we will generate a simple dataset of two classes: cat and dog. We will design a bot with Selenium that will access and move through Instagram automatically. Also, we will use YOLO, a Convolutional Neural Network to detect and order the dogs and cats we need. The programming language we are going to use is Python 3.6, which allows us to use Selenium and YOLO easily. We will need the following external dependencies: GluonCV: Framework that provides implementations of state-of-the-art deep learning algorithms in computer vision. This toolkit offers us a large number of pre-trained models. We are going to use one of them [3]. Pillow: Python Imaging Library. Selenium: It is an umbrella project for a range of tools and libraries that enable and support the automation of web browsers. We will use the Python module provided by this library. Requests: It is an elegant and simple HTTP library for Python. We will use it to download images. You can install these dependencies with this command: pip install mxnet gluoncv Pillow selenium beautifulsoup4 requests In addition, you will need the ChromeDriver. This provides capabilities for navigating to web pages from Selenium. You have to copy it to usr/local/bin, and voilà! You can now control your Chrome browser from Selenium! As we have already mentioned, we will use the YoloV3 as a detection module (By the way, YoloV4 is available from one month ago). In this way, we will try to find and differentiate cats and dogs. Summarizing, YOLO (You Only Look Once) is basically a single CNN that provides multiple predictions (bounding boxes) with an associated probability for each class. In addition, NMS (Non-Maximum Suppression) is used to merge multiple detections into a single one. We are facing a fast neural network that works in real-time. We will use Selenium to program a bot to login and move through Instagram automatically downloading the images using the detection module. As you can see in the __call__() method, we can divide the code into 4 main steps: Open Instagram home page.Login on Instagram with your username and password.Put your hashtag to restrict the search, this case #PETS, because we want dogs and cats in this example.And the most important step, scroll and download images. Open Instagram home page. Login on Instagram with your username and password. Put your hashtag to restrict the search, this case #PETS, because we want dogs and cats in this example. And the most important step, scroll and download images. In this last step, we scroll and parse the HTML to obtain the URL that we need to download the image and compose it with Pillow. At this point, we check if the image contains a dog, a cat, or nothing, to then save it in the corresponding folder to each class, or discard the image. Finally, you only have to worry about validating the sample. Enjoy! 😉 If you want to launch this code easily you can find it in this repository. You just have to follow the steps indicated in the README. github.com In the following GIF, you can see how the dataset is automatically generated: the bot accesses to Instagram with username and password, enters the #PETS hashtag, and scrolls while downloading only the images of dogs (bottom folder) and cats (top folder). Emphasize that this is a simple example, there are many open datasets of dogs and cats of course. We can add the complexity that we want to our generator, this is a proof of concept, possibly our tasks are not so simple, nor the data that we need so basic. Thanks for reading!
[ { "code": null, "e": 515, "s": 172, "text": "If we ask several experts about the keys of a Computer Vision project (especially if we want a real application), maybe one the most repeated element (and in my opinion the most important thing) is the dataset. The problem appears when we also ask about the most arduous and laborious task, which answer also usually is the same: the dataset." }, { "code": null, "e": 579, "s": 515, "text": "The task to compose a dataset can be summarized in three steps:" }, { "code": null, "e": 700, "s": 579, "text": "Capture images.Annotate images: labeling the sample for a set of classes.Validation: checking if the labels are correct." }, { "code": null, "e": 716, "s": 700, "text": "Capture images." }, { "code": null, "e": 775, "s": 716, "text": "Annotate images: labeling the sample for a set of classes." }, { "code": null, "e": 823, "s": 775, "text": "Validation: checking if the labels are correct." }, { "code": null, "e": 1086, "s": 823, "text": "The first thing we would do is to resort to state-of-the-art datasets that can be used for our task, but the problem is we don’t always find what we need. At this moment we are facing a manual and a painful task. This article shows how to avoid this manual work." }, { "code": null, "e": 1489, "s": 1086, "text": "Using Selenium [1](an open-source web-based automation tool), Instagram (indirectly one of the largest image databases in the world) and YOLO [2](one of the most employed deep learning algorithms in object detection) we can generate a dataset automatically (the only thing you can’t avoid is the validation step). To show a simple example, we will generate a simple dataset of two classes: cat and dog." }, { "code": null, "e": 1685, "s": 1489, "text": "We will design a bot with Selenium that will access and move through Instagram automatically. Also, we will use YOLO, a Convolutional Neural Network to detect and order the dogs and cats we need." }, { "code": null, "e": 1794, "s": 1685, "text": "The programming language we are going to use is Python 3.6, which allows us to use Selenium and YOLO easily." }, { "code": null, "e": 1844, "s": 1794, "text": "We will need the following external dependencies:" }, { "code": null, "e": 2056, "s": 1844, "text": "GluonCV: Framework that provides implementations of state-of-the-art deep learning algorithms in computer vision. This toolkit offers us a large number of pre-trained models. We are going to use one of them [3]." }, { "code": null, "e": 2088, "s": 2056, "text": "Pillow: Python Imaging Library." }, { "code": null, "e": 2271, "s": 2088, "text": "Selenium: It is an umbrella project for a range of tools and libraries that enable and support the automation of web browsers. We will use the Python module provided by this library." }, { "code": null, "e": 2369, "s": 2271, "text": "Requests: It is an elegant and simple HTTP library for Python. We will use it to download images." }, { "code": null, "e": 2423, "s": 2369, "text": "You can install these dependencies with this command:" }, { "code": null, "e": 2489, "s": 2423, "text": "pip install mxnet gluoncv Pillow selenium beautifulsoup4 requests" }, { "code": null, "e": 2709, "s": 2489, "text": "In addition, you will need the ChromeDriver. This provides capabilities for navigating to web pages from Selenium. You have to copy it to usr/local/bin, and voilà! You can now control your Chrome browser from Selenium!" }, { "code": null, "e": 2904, "s": 2709, "text": "As we have already mentioned, we will use the YoloV3 as a detection module (By the way, YoloV4 is available from one month ago). In this way, we will try to find and differentiate cats and dogs." }, { "code": null, "e": 3228, "s": 2904, "text": "Summarizing, YOLO (You Only Look Once) is basically a single CNN that provides multiple predictions (bounding boxes) with an associated probability for each class. In addition, NMS (Non-Maximum Suppression) is used to merge multiple detections into a single one. We are facing a fast neural network that works in real-time." }, { "code": null, "e": 3367, "s": 3228, "text": "We will use Selenium to program a bot to login and move through Instagram automatically downloading the images using the detection module." }, { "code": null, "e": 3450, "s": 3367, "text": "As you can see in the __call__() method, we can divide the code into 4 main steps:" }, { "code": null, "e": 3687, "s": 3450, "text": "Open Instagram home page.Login on Instagram with your username and password.Put your hashtag to restrict the search, this case #PETS, because we want dogs and cats in this example.And the most important step, scroll and download images." }, { "code": null, "e": 3713, "s": 3687, "text": "Open Instagram home page." }, { "code": null, "e": 3765, "s": 3713, "text": "Login on Instagram with your username and password." }, { "code": null, "e": 3870, "s": 3765, "text": "Put your hashtag to restrict the search, this case #PETS, because we want dogs and cats in this example." }, { "code": null, "e": 3927, "s": 3870, "text": "And the most important step, scroll and download images." }, { "code": null, "e": 4209, "s": 3927, "text": "In this last step, we scroll and parse the HTML to obtain the URL that we need to download the image and compose it with Pillow. At this point, we check if the image contains a dog, a cat, or nothing, to then save it in the corresponding folder to each class, or discard the image." }, { "code": null, "e": 4279, "s": 4209, "text": "Finally, you only have to worry about validating the sample. Enjoy! 😉" }, { "code": null, "e": 4413, "s": 4279, "text": "If you want to launch this code easily you can find it in this repository. You just have to follow the steps indicated in the README." }, { "code": null, "e": 4424, "s": 4413, "text": "github.com" }, { "code": null, "e": 4679, "s": 4424, "text": "In the following GIF, you can see how the dataset is automatically generated: the bot accesses to Instagram with username and password, enters the #PETS hashtag, and scrolls while downloading only the images of dogs (bottom folder) and cats (top folder)." }, { "code": null, "e": 4936, "s": 4679, "text": "Emphasize that this is a simple example, there are many open datasets of dogs and cats of course. We can add the complexity that we want to our generator, this is a proof of concept, possibly our tasks are not so simple, nor the data that we need so basic." } ]
Convolutional Neural Network. Learn Convolutional Neural Network from... | by dshahid380 | Towards Data Science
What is CNN ? Why should we use CNN ? Few Definitions Layers in CNN Keras Implementation Computer vision is evolving rapidly day-by-day. Its one of the reason is deep learning. When we talk about computer vision, a term convolutional neural network( abbreviated as CNN) comes in our mind because CNN is heavily used here. Examples of CNN in computer vision are face recognition, image classification etc. It is similar to the basic neural network. CNN also have learnable parameter like neural network i.e, weights, biases etc. Suppose you are working with MNIST dataset, you know each image in MNIST is 28 x 28 x 1(black & white image contains only 1 channel). Total number of neurons in input layer will 28 x 28 = 784, this can be manageable. What if the size of image is 1000 x 1000 which means you need 106 neurons in input layer. Oh! This seems a huge number of neurons are required for operation. It is computationally ineffective right. So here comes Convolutional Neural Network or CNN. In simple word what CNN does is, it extract the feature of image and convert it into lower dimension without loosing its characteristics. In the following example you can see that initial the size of the image is 224 x 224 x 3. If you proceed without convolution then you need 224 x 224 x 3 = 100, 352 numbers of neurons in input layer but after applying convolution you input tensor dimension is reduced to 1 x 1 x 1000. It means you only need 1000 neurons in first layer of feedforward neural network. There are few definitions you should know before understanding CNN Thinking about images, its easy to understand that it has a height and width, so it would make sense to represent the information contained in it with a two dimensional structure (a matrix) until you remember that images have colors, and to add information about the colors, we need another dimension, and that is when Tensors become particularly helpful. Images are encoded into color channels, the image data is represented into each color intensity in a color channel at a given point, the most common one being RGB, which means Red, Blue and Green. The information contained into an image is the intensity of each channel color into the width and height of the image, just like this So the intensity of the red channel at each point with width and height can be represented into a matrix, the same goes for the blue and green channels, so we end up having three matrices, and when these are combined they form a tensor. Every image has vertical and horizontal edges which actually combining to form a image. Convolution operation is used with some filters for detecting edges. Suppose you have gray scale image with dimension 6 x 6 and filter of dimension 3 x 3(say). When 6 x 6 grey scale image convolve with 3 x 3 filter, we get 4 x 4 image. First of all 3 x 3 filter matrix get multiplied with first 3 x 3 size of our grey scale image, then we shift one column right up to end , after that we shift one row and so on. The convolution operation can be visualized in the following way. Here our image dimension is 4 x 4 and filter is 3 x 3, hence we are getting output after convolution is 2 x 2. If we have N x N image size and F x F filter size then after convolution result will be (N x N) * (F x F) = (N-F+1)x(N-F+1)(Apply this for above case) Stride denotes how many steps we are moving in each steps in convolution.By default it is one. We can observe that the size of output is smaller that input. To maintain the dimension of output as in input , we use padding. Padding is a process of adding zeros to the input matrix symmetrically. In the following example,the extra grey blocks denote the padding. It is used to make the dimension of output same as input. Let say ‘p’ is the padding Initially(without padding) (N x N) * (F x F) = (N-F+1)x(N-F+1)---(1) After applying padding If we apply filter F x F in (N+2p) x (N+2p) input matrix with padding, then we will get output matrix dimension (N+2p-F+1) x (N+2p-F+1). As we know that after applying padding we will get the same dimension as original input dimension (N x N). Hence we have, (N+2p-F+1)x(N+2p-F+1) equivalent to NxN N+2p-F+1 = N ---(2) p = (F-1)/2 ---(3) The equation (3) clearly shows that Padding depends on the dimension of filter. There are five different layers in CNN Input layer Convo layer (Convo + ReLU) Pooling layer Fully connected(FC) layer Softmax/logistic layer Output layer Input layer in CNN should contain image data. Image data is represented by three dimensional matrix as we saw earlier. You need to reshape it into a single column. Suppose you have image of dimension 28 x 28 =784, you need to convert it into 784 x 1 before feeding into input. If you have “m” training examples then dimension of input will be (784, m). Convo layer is sometimes called feature extractor layer because features of the image are get extracted within this layer. First of all, a part of image is connected to Convo layer to perform convolution operation as we saw earlier and calculating the dot product between receptive field(it is a local region of the input image that has the same size as that of filter) and the filter. Result of the operation is single integer of the output volume. Then we slide the filter over the next receptive field of the same input image by a Stride and do the same operation again. We will repeat the same process again and again until we go through the whole image. The output will be the input for the next layer. Convo layer also contains ReLU activation to make all negative value to zero. Pooling layer is used to reduce the spatial volume of input image after convolution. It is used between two convolution layer. If we apply FC after Convo layer without applying pooling or max pooling, then it will be computationally expensive and we don’t want it. So, the max pooling is only way to reduce the spatial volume of input image. In the above example, we have applied max pooling in single depth slice with Stride of 2. You can observe the 4 x 4 dimension input is reduce to 2 x 2 dimension. There is no parameter in pooling layer but it has two hyperparameters — Filter(F) and Stride(S). In general, if we have input dimension W1 x H1 x D1, then W2 = (W1−F)/S+1 H2 = (H1−F)/S+1 D2 = D1 Where W2, H2 and D2 are the width, height and depth of output. Fully connected layer involves weights, biases, and neurons. It connects neurons in one layer to neurons in another layer. It is used to classify images between different category by training. Softmax or Logistic layer is the last layer of CNN. It resides at the end of FC layer. Logistic is used for binary classification and softmax is for multi-classification. Output layer contains the label which is in the form of one-hot encoded. Now you have a good understanding of CNN. Let’s implement a CNN in Keras. We will use CIFAR-10 dataset to build a CNN image classifier. CIFAR-10 dataset has 10 different labels Airplane Automobile Bird Cat Deer Dog Frog Horse Ship Truck It has 50,000 training data and 10,000 testing image data. Image size in CIFAR-10 is 32 x 32 x 3. It comes with Keras library. If you are using google colaboratory, then make sure you are using GPU. To check whether your GPU is on or not. Try following code. Output: Found GPU at: /device:GPU:0 First of all, import all necessary modules and libraries. Then load the dataset and split it into train and test sets. We will print training sample shape, test sample shape and total number of classes present in CIFAR-10. There are 10 classes as we saw earlier. For the sake of example, we will print two example image from training set and test set. Output: Find the shape of input image then reshape it into input format for training and testing sets. After that change all datatypes into floats. Normalize the data between 0–1 by dividing train data and test data with 255 then convert all labels into one-hot vector with to_catagorical() function. Display the change for category label using one-hot encoding. Output: Original label 0 : [6]After conversion to categorical ( one-hot ) : [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] Now create our model. We will add up Convo layers followed by pooling layers. Then we will connect Dense(FC) layer to predict the classes. Input data fed to first Convo layer, output of that Convo layer acts as input for next Convo layer and so on. Finally data is fed to FC layer which try to predict the correct labels. Initialize all parameters and compile our model with rmsprops optimizer. There are many optimizers for example adam, SGD, GradientDescent, Adagrad, Adadelta and Adamax ,feel free to experiment with it. Here batch is 256 with 50 epochs. model.summary() is used to see all parameters and shapes in each layers in our models. You can observe that total parameters are 276, 138 and total trainable parameters are 276, 138. Non-trainable parameter is 0. Output: After compiling our model, we will train our model by fit() method, then evaluate it. Output: After training we got 83.86% accuracy and 75.48% validation accuracy. It is not actually bad at all. Congratulations! You have made Convolutional Neural Network in Keras by understanding its basic concepts. Feel free to experiment with it by changing its hyperparameters and let me know in the comment section. You can find all code in my Github CS231n Convolutional Neural NetworkKeras documentationDeep Learning Labdeeplearning.ai course on Convolutional Nneural Netowrks CS231n Convolutional Neural Network Keras documentation Deep Learning Lab deeplearning.ai course on Convolutional Nneural Netowrks
[ { "code": null, "e": 186, "s": 172, "text": "What is CNN ?" }, { "code": null, "e": 210, "s": 186, "text": "Why should we use CNN ?" }, { "code": null, "e": 226, "s": 210, "text": "Few Definitions" }, { "code": null, "e": 240, "s": 226, "text": "Layers in CNN" }, { "code": null, "e": 261, "s": 240, "text": "Keras Implementation" }, { "code": null, "e": 700, "s": 261, "text": "Computer vision is evolving rapidly day-by-day. Its one of the reason is deep learning. When we talk about computer vision, a term convolutional neural network( abbreviated as CNN) comes in our mind because CNN is heavily used here. Examples of CNN in computer vision are face recognition, image classification etc. It is similar to the basic neural network. CNN also have learnable parameter like neural network i.e, weights, biases etc." }, { "code": null, "e": 1671, "s": 700, "text": "Suppose you are working with MNIST dataset, you know each image in MNIST is 28 x 28 x 1(black & white image contains only 1 channel). Total number of neurons in input layer will 28 x 28 = 784, this can be manageable. What if the size of image is 1000 x 1000 which means you need 106 neurons in input layer. Oh! This seems a huge number of neurons are required for operation. It is computationally ineffective right. So here comes Convolutional Neural Network or CNN. In simple word what CNN does is, it extract the feature of image and convert it into lower dimension without loosing its characteristics. In the following example you can see that initial the size of the image is 224 x 224 x 3. If you proceed without convolution then you need 224 x 224 x 3 = 100, 352 numbers of neurons in input layer but after applying convolution you input tensor dimension is reduced to 1 x 1 x 1000. It means you only need 1000 neurons in first layer of feedforward neural network." }, { "code": null, "e": 1738, "s": 1671, "text": "There are few definitions you should know before understanding CNN" }, { "code": null, "e": 2094, "s": 1738, "text": "Thinking about images, its easy to understand that it has a height and width, so it would make sense to represent the information contained in it with a two dimensional structure (a matrix) until you remember that images have colors, and to add information about the colors, we need another dimension, and that is when Tensors become particularly helpful." }, { "code": null, "e": 2425, "s": 2094, "text": "Images are encoded into color channels, the image data is represented into each color intensity in a color channel at a given point, the most common one being RGB, which means Red, Blue and Green. The information contained into an image is the intensity of each channel color into the width and height of the image, just like this" }, { "code": null, "e": 2662, "s": 2425, "text": "So the intensity of the red channel at each point with width and height can be represented into a matrix, the same goes for the blue and green channels, so we end up having three matrices, and when these are combined they form a tensor." }, { "code": null, "e": 3163, "s": 2662, "text": "Every image has vertical and horizontal edges which actually combining to form a image. Convolution operation is used with some filters for detecting edges. Suppose you have gray scale image with dimension 6 x 6 and filter of dimension 3 x 3(say). When 6 x 6 grey scale image convolve with 3 x 3 filter, we get 4 x 4 image. First of all 3 x 3 filter matrix get multiplied with first 3 x 3 size of our grey scale image, then we shift one column right up to end , after that we shift one row and so on." }, { "code": null, "e": 3340, "s": 3163, "text": "The convolution operation can be visualized in the following way. Here our image dimension is 4 x 4 and filter is 3 x 3, hence we are getting output after convolution is 2 x 2." }, { "code": null, "e": 3428, "s": 3340, "text": "If we have N x N image size and F x F filter size then after convolution result will be" }, { "code": null, "e": 3491, "s": 3428, "text": "(N x N) * (F x F) = (N-F+1)x(N-F+1)(Apply this for above case)" }, { "code": null, "e": 3586, "s": 3491, "text": "Stride denotes how many steps we are moving in each steps in convolution.By default it is one." }, { "code": null, "e": 3911, "s": 3586, "text": "We can observe that the size of output is smaller that input. To maintain the dimension of output as in input , we use padding. Padding is a process of adding zeros to the input matrix symmetrically. In the following example,the extra grey blocks denote the padding. It is used to make the dimension of output same as input." }, { "code": null, "e": 3938, "s": 3911, "text": "Let say ‘p’ is the padding" }, { "code": null, "e": 3965, "s": 3938, "text": "Initially(without padding)" }, { "code": null, "e": 4007, "s": 3965, "text": "(N x N) * (F x F) = (N-F+1)x(N-F+1)---(1)" }, { "code": null, "e": 4030, "s": 4007, "text": "After applying padding" }, { "code": null, "e": 4289, "s": 4030, "text": "If we apply filter F x F in (N+2p) x (N+2p) input matrix with padding, then we will get output matrix dimension (N+2p-F+1) x (N+2p-F+1). As we know that after applying padding we will get the same dimension as original input dimension (N x N). Hence we have," }, { "code": null, "e": 4368, "s": 4289, "text": "(N+2p-F+1)x(N+2p-F+1) equivalent to NxN N+2p-F+1 = N ---(2) p = (F-1)/2 ---(3)" }, { "code": null, "e": 4448, "s": 4368, "text": "The equation (3) clearly shows that Padding depends on the dimension of filter." }, { "code": null, "e": 4487, "s": 4448, "text": "There are five different layers in CNN" }, { "code": null, "e": 4499, "s": 4487, "text": "Input layer" }, { "code": null, "e": 4526, "s": 4499, "text": "Convo layer (Convo + ReLU)" }, { "code": null, "e": 4540, "s": 4526, "text": "Pooling layer" }, { "code": null, "e": 4566, "s": 4540, "text": "Fully connected(FC) layer" }, { "code": null, "e": 4589, "s": 4566, "text": "Softmax/logistic layer" }, { "code": null, "e": 4602, "s": 4589, "text": "Output layer" }, { "code": null, "e": 4955, "s": 4602, "text": "Input layer in CNN should contain image data. Image data is represented by three dimensional matrix as we saw earlier. You need to reshape it into a single column. Suppose you have image of dimension 28 x 28 =784, you need to convert it into 784 x 1 before feeding into input. If you have “m” training examples then dimension of input will be (784, m)." }, { "code": null, "e": 5663, "s": 4955, "text": "Convo layer is sometimes called feature extractor layer because features of the image are get extracted within this layer. First of all, a part of image is connected to Convo layer to perform convolution operation as we saw earlier and calculating the dot product between receptive field(it is a local region of the input image that has the same size as that of filter) and the filter. Result of the operation is single integer of the output volume. Then we slide the filter over the next receptive field of the same input image by a Stride and do the same operation again. We will repeat the same process again and again until we go through the whole image. The output will be the input for the next layer." }, { "code": null, "e": 5741, "s": 5663, "text": "Convo layer also contains ReLU activation to make all negative value to zero." }, { "code": null, "e": 6245, "s": 5741, "text": "Pooling layer is used to reduce the spatial volume of input image after convolution. It is used between two convolution layer. If we apply FC after Convo layer without applying pooling or max pooling, then it will be computationally expensive and we don’t want it. So, the max pooling is only way to reduce the spatial volume of input image. In the above example, we have applied max pooling in single depth slice with Stride of 2. You can observe the 4 x 4 dimension input is reduce to 2 x 2 dimension." }, { "code": null, "e": 6342, "s": 6245, "text": "There is no parameter in pooling layer but it has two hyperparameters — Filter(F) and Stride(S)." }, { "code": null, "e": 6400, "s": 6342, "text": "In general, if we have input dimension W1 x H1 x D1, then" }, { "code": null, "e": 6416, "s": 6400, "text": "W2 = (W1−F)/S+1" }, { "code": null, "e": 6432, "s": 6416, "text": "H2 = (H1−F)/S+1" }, { "code": null, "e": 6440, "s": 6432, "text": "D2 = D1" }, { "code": null, "e": 6503, "s": 6440, "text": "Where W2, H2 and D2 are the width, height and depth of output." }, { "code": null, "e": 6696, "s": 6503, "text": "Fully connected layer involves weights, biases, and neurons. It connects neurons in one layer to neurons in another layer. It is used to classify images between different category by training." }, { "code": null, "e": 6867, "s": 6696, "text": "Softmax or Logistic layer is the last layer of CNN. It resides at the end of FC layer. Logistic is used for binary classification and softmax is for multi-classification." }, { "code": null, "e": 6940, "s": 6867, "text": "Output layer contains the label which is in the form of one-hot encoded." }, { "code": null, "e": 7014, "s": 6940, "text": "Now you have a good understanding of CNN. Let’s implement a CNN in Keras." }, { "code": null, "e": 7117, "s": 7014, "text": "We will use CIFAR-10 dataset to build a CNN image classifier. CIFAR-10 dataset has 10 different labels" }, { "code": null, "e": 7126, "s": 7117, "text": "Airplane" }, { "code": null, "e": 7137, "s": 7126, "text": "Automobile" }, { "code": null, "e": 7142, "s": 7137, "text": "Bird" }, { "code": null, "e": 7146, "s": 7142, "text": "Cat" }, { "code": null, "e": 7151, "s": 7146, "text": "Deer" }, { "code": null, "e": 7155, "s": 7151, "text": "Dog" }, { "code": null, "e": 7160, "s": 7155, "text": "Frog" }, { "code": null, "e": 7166, "s": 7160, "text": "Horse" }, { "code": null, "e": 7171, "s": 7166, "text": "Ship" }, { "code": null, "e": 7177, "s": 7171, "text": "Truck" }, { "code": null, "e": 7304, "s": 7177, "text": "It has 50,000 training data and 10,000 testing image data. Image size in CIFAR-10 is 32 x 32 x 3. It comes with Keras library." }, { "code": null, "e": 7436, "s": 7304, "text": "If you are using google colaboratory, then make sure you are using GPU. To check whether your GPU is on or not. Try following code." }, { "code": null, "e": 7444, "s": 7436, "text": "Output:" }, { "code": null, "e": 7472, "s": 7444, "text": "Found GPU at: /device:GPU:0" }, { "code": null, "e": 7530, "s": 7472, "text": "First of all, import all necessary modules and libraries." }, { "code": null, "e": 7591, "s": 7530, "text": "Then load the dataset and split it into train and test sets." }, { "code": null, "e": 7824, "s": 7591, "text": "We will print training sample shape, test sample shape and total number of classes present in CIFAR-10. There are 10 classes as we saw earlier. For the sake of example, we will print two example image from training set and test set." }, { "code": null, "e": 7832, "s": 7824, "text": "Output:" }, { "code": null, "e": 7972, "s": 7832, "text": "Find the shape of input image then reshape it into input format for training and testing sets. After that change all datatypes into floats." }, { "code": null, "e": 8125, "s": 7972, "text": "Normalize the data between 0–1 by dividing train data and test data with 255 then convert all labels into one-hot vector with to_catagorical() function." }, { "code": null, "e": 8187, "s": 8125, "text": "Display the change for category label using one-hot encoding." }, { "code": null, "e": 8195, "s": 8187, "text": "Output:" }, { "code": null, "e": 8297, "s": 8195, "text": "Original label 0 : [6]After conversion to categorical ( one-hot ) : [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]" }, { "code": null, "e": 8619, "s": 8297, "text": "Now create our model. We will add up Convo layers followed by pooling layers. Then we will connect Dense(FC) layer to predict the classes. Input data fed to first Convo layer, output of that Convo layer acts as input for next Convo layer and so on. Finally data is fed to FC layer which try to predict the correct labels." }, { "code": null, "e": 8855, "s": 8619, "text": "Initialize all parameters and compile our model with rmsprops optimizer. There are many optimizers for example adam, SGD, GradientDescent, Adagrad, Adadelta and Adamax ,feel free to experiment with it. Here batch is 256 with 50 epochs." }, { "code": null, "e": 9068, "s": 8855, "text": "model.summary() is used to see all parameters and shapes in each layers in our models. You can observe that total parameters are 276, 138 and total trainable parameters are 276, 138. Non-trainable parameter is 0." }, { "code": null, "e": 9076, "s": 9068, "text": "Output:" }, { "code": null, "e": 9162, "s": 9076, "text": "After compiling our model, we will train our model by fit() method, then evaluate it." }, { "code": null, "e": 9170, "s": 9162, "text": "Output:" }, { "code": null, "e": 9271, "s": 9170, "text": "After training we got 83.86% accuracy and 75.48% validation accuracy. It is not actually bad at all." }, { "code": null, "e": 9481, "s": 9271, "text": "Congratulations! You have made Convolutional Neural Network in Keras by understanding its basic concepts. Feel free to experiment with it by changing its hyperparameters and let me know in the comment section." }, { "code": null, "e": 9516, "s": 9481, "text": "You can find all code in my Github" }, { "code": null, "e": 9644, "s": 9516, "text": "CS231n Convolutional Neural NetworkKeras documentationDeep Learning Labdeeplearning.ai course on Convolutional Nneural Netowrks" }, { "code": null, "e": 9680, "s": 9644, "text": "CS231n Convolutional Neural Network" }, { "code": null, "e": 9700, "s": 9680, "text": "Keras documentation" }, { "code": null, "e": 9718, "s": 9700, "text": "Deep Learning Lab" } ]
Escape sequences in C
Many programming languages support a concept called Escape Sequence. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character − char ch = '\n'; Here, character n has been preceded by a backslash (\), it has special meaning which is a new line but keep in mind that backslash (\) has special meaning with a few characters only. The following statement will not convey any meaning in C programming and it will be assumed as an invalid statement − char ch = '\1'; The following table lists the escape sequences available in C programming language − #include <stdio.h> int main() { char ch1; char ch2; char ch3; char ch4; ch1 = '\t'; ch2 = '\n'; printf( "Test for tabspace %c and a newline %c will start here", ch1, ch2); } Test for tabspace and a newline will start here
[ { "code": null, "e": 1362, "s": 1062, "text": "Many programming languages support a concept called Escape Sequence. When a character is preceded by a backslash (\\), it is called an escape sequence and it has a special meaning to the compiler. For example, \\n in the following statement is a valid character and it is called a new line character −" }, { "code": null, "e": 1378, "s": 1362, "text": "char ch = '\\n';" }, { "code": null, "e": 1679, "s": 1378, "text": "Here, character n has been preceded by a backslash (\\), it has special meaning which is a new line but keep in mind that backslash (\\) has special meaning with a few characters only. The following statement will not convey any meaning in C programming and it will be assumed as an invalid statement −" }, { "code": null, "e": 1695, "s": 1679, "text": "char ch = '\\1';" }, { "code": null, "e": 1780, "s": 1695, "text": "The following table lists the escape sequences available in C programming language −" }, { "code": null, "e": 1975, "s": 1780, "text": "#include <stdio.h>\nint main() {\n char ch1;\n char ch2;\n char ch3;\n char ch4;\n ch1 = '\\t';\n ch2 = '\\n';\n printf( \"Test for tabspace %c and a newline %c will start here\", ch1, ch2);\n}" }, { "code": null, "e": 2023, "s": 1975, "text": "Test for tabspace and a newline\nwill start here" } ]
Create COVID-19 Map Animation with Python in 5 Minutes | by Joe T. Santhanavanich | Towards Data Science
In the fight against COVID-19, The GIS technologies have played an important role in many aspects, including the data integration, and geospatial visualization of epidemic information, spatial tracking of confirmed cases, prediction of regional transmission, and many more. These provide support information for government sectors to fight against the COVID-19 spreading. [1] To address this, JHU had provided such a nice dashboard created with ESRI ArcGIS operation dashboard: The dashboard gives a pretty nice overview of the total cumulative confirmed cases, active cases, incidence rate, case-fatality ratio, testing rate, and hospitalization rate. However, the feature for visualizing the change of data overtime on the map is missing! This article will introduce you to an easy way to create a dynamic map visualizing the spreading of COVID-19 overtime using the JHU COVID-19 dataset. The Python libraries we will use in this article are mainly Pandas, PyCountry, and Plotly Express. Most of you would already know the Plotly library, but if not, you may check over all of its features in this article. $ pip install pandas$ pip install pycountry$ pip install plotly The dataset we will here is the JHU CSSE COVID-19 dataset. You can download or fork the latest update version of it from the CSSE Github repo. You may check this article to check how to automatically update the datasource over time in your Python project with PythonGit. We will focus only on the time_series_covid19_confirmed_global.csv dataset in this article. Then, you can easily load the data to dataframe with import pandas as pddf_confirm = pd.read_csv('path_to_file') In order to visualize the time series dataset dynamically with Plotly Express, you need to have these requirements for your dataframe. Aggregate the dataset into the level of the country. Get the three-letter country codes defined in ISO 3166–1 for each country; for example, AFG for Afghanistan. You can do this by using PyCountry. Transform the dataset in a long format in which date value is representing in a single column You can do this easily starting by loading the dataset into the Pandas dataframe and then using melt in Pandas. You may follow these steps with this Python script: Overall the final clean dataframe would look like in the following image: After the dataset is ready, you can easily create a map animation with Plotly Express. For example, you can create an animated choropleth map from the dataframe from step 3 with the following script below, you may adjust each parameter as you like too. This example visualizes the confirmed COVID-19 case dataset, but you may try to apply this method for visualizing the COVID-19 death case and recovered case dataset as well. For more information about plotting the animation choropleth map with plotly, check the full documentation here. If you want to change the color scale, you can simply choose the built-in color scale from here. Apply better color symbology rule. Try to create other map types such as scatter maps or heat maps by checking from the Plotly map gallery here. Alternatively, you may check how to visualize COVID-19 data in Kepler.gl a geospatial analysis tool for the visualization of dynamic data through this article. This article introduces you to how to prepare datasets and create Map Animation with Plotly Express in an easy way. I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments. About me & Check out all my blog contents: Link Be Safe and Healthy! 💪 Thank you for Reading. 📚 [1] Zhou, C., Su, F., Pei, T., Zhang, A., Du, Y., Luo, B., Cao, Z., Wang, J., Yuan, W., Zhu, Y., Song, C., Chen, J., Xu, J., Li, F., Ma, T., Jiang, L., Yan, F., Yi, J., Hu, Y., ... Xiao, H. (2020). COVID-19: Challenges to GIS with Big Data. Geography and Sustainability, 1(1), 77–87. https://doi.org/10.1016/j.geosus.2020.03.005
[ { "code": null, "e": 650, "s": 172, "text": "In the fight against COVID-19, The GIS technologies have played an important role in many aspects, including the data integration, and geospatial visualization of epidemic information, spatial tracking of confirmed cases, prediction of regional transmission, and many more. These provide support information for government sectors to fight against the COVID-19 spreading. [1] To address this, JHU had provided such a nice dashboard created with ESRI ArcGIS operation dashboard:" }, { "code": null, "e": 913, "s": 650, "text": "The dashboard gives a pretty nice overview of the total cumulative confirmed cases, active cases, incidence rate, case-fatality ratio, testing rate, and hospitalization rate. However, the feature for visualizing the change of data overtime on the map is missing!" }, { "code": null, "e": 1063, "s": 913, "text": "This article will introduce you to an easy way to create a dynamic map visualizing the spreading of COVID-19 overtime using the JHU COVID-19 dataset." }, { "code": null, "e": 1281, "s": 1063, "text": "The Python libraries we will use in this article are mainly Pandas, PyCountry, and Plotly Express. Most of you would already know the Plotly library, but if not, you may check over all of its features in this article." }, { "code": null, "e": 1345, "s": 1281, "text": "$ pip install pandas$ pip install pycountry$ pip install plotly" }, { "code": null, "e": 1708, "s": 1345, "text": "The dataset we will here is the JHU CSSE COVID-19 dataset. You can download or fork the latest update version of it from the CSSE Github repo. You may check this article to check how to automatically update the datasource over time in your Python project with PythonGit. We will focus only on the time_series_covid19_confirmed_global.csv dataset in this article." }, { "code": null, "e": 1761, "s": 1708, "text": "Then, you can easily load the data to dataframe with" }, { "code": null, "e": 1821, "s": 1761, "text": "import pandas as pddf_confirm = pd.read_csv('path_to_file')" }, { "code": null, "e": 1956, "s": 1821, "text": "In order to visualize the time series dataset dynamically with Plotly Express, you need to have these requirements for your dataframe." }, { "code": null, "e": 2009, "s": 1956, "text": "Aggregate the dataset into the level of the country." }, { "code": null, "e": 2154, "s": 2009, "text": "Get the three-letter country codes defined in ISO 3166–1 for each country; for example, AFG for Afghanistan. You can do this by using PyCountry." }, { "code": null, "e": 2360, "s": 2154, "text": "Transform the dataset in a long format in which date value is representing in a single column You can do this easily starting by loading the dataset into the Pandas dataframe and then using melt in Pandas." }, { "code": null, "e": 2412, "s": 2360, "text": "You may follow these steps with this Python script:" }, { "code": null, "e": 2486, "s": 2412, "text": "Overall the final clean dataframe would look like in the following image:" }, { "code": null, "e": 2739, "s": 2486, "text": "After the dataset is ready, you can easily create a map animation with Plotly Express. For example, you can create an animated choropleth map from the dataframe from step 3 with the following script below, you may adjust each parameter as you like too." }, { "code": null, "e": 2913, "s": 2739, "text": "This example visualizes the confirmed COVID-19 case dataset, but you may try to apply this method for visualizing the COVID-19 death case and recovered case dataset as well." }, { "code": null, "e": 3268, "s": 2913, "text": "For more information about plotting the animation choropleth map with plotly, check the full documentation here. If you want to change the color scale, you can simply choose the built-in color scale from here. Apply better color symbology rule. Try to create other map types such as scatter maps or heat maps by checking from the Plotly map gallery here." }, { "code": null, "e": 3428, "s": 3268, "text": "Alternatively, you may check how to visualize COVID-19 data in Kepler.gl a geospatial analysis tool for the visualization of dynamic data through this article." }, { "code": null, "e": 3697, "s": 3428, "text": "This article introduces you to how to prepare datasets and create Map Animation with Plotly Express in an easy way. I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments." }, { "code": null, "e": 3745, "s": 3697, "text": "About me & Check out all my blog contents: Link" }, { "code": null, "e": 3768, "s": 3745, "text": "Be Safe and Healthy! 💪" }, { "code": null, "e": 3793, "s": 3768, "text": "Thank you for Reading. 📚" } ]
How to use handler in android?
This example demonstrate about How to use handler in android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "match_parent" android:layout_height = "match_parent"> <Button android:id = "@+id/my_button" android:layout_width = "100dp" android:layout_height = "wrap_content" android:layout_x = "0dp" android:layout_y = "0dp" android:text = "Yes" /> </LinearLayout> In the above code, we have taken button. Step 3 − Add the following code to src/MainActivity.java <?xml version = "1.0" encoding = "utf-8"?> import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.util.DisplayMetrics; import android.widget.Button; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends FragmentActivity { Handler handler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); final Button button = (Button) findViewById(R.id.my_button); final DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { Random R = new Random(); final float dx = R.nextFloat() * displaymetrics.widthPixels; final float dy = R.nextFloat() * displaymetrics.heightPixels; final Timer timer = new Timer(); button.animate() .x(dx) .y(dy) .setDuration(0) .start(); } }); } }, 0, 1000); } } 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 – Click here to download the project code
[ { "code": null, "e": 1123, "s": 1062, "text": "This example demonstrate about How to use handler in android" }, { "code": null, "e": 1252, "s": 1123, "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": 1317, "s": 1252, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1792, "s": 1317, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:orientation = \"vertical\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n <Button\n android:id = \"@+id/my_button\"\n android:layout_width = \"100dp\"\n android:layout_height = \"wrap_content\"\n android:layout_x = \"0dp\"\n android:layout_y = \"0dp\"\n android:text = \"Yes\" />\n</LinearLayout>" }, { "code": null, "e": 1833, "s": 1792, "text": "In the above code, we have taken button." }, { "code": null, "e": 1890, "s": 1833, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3340, "s": 1890, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.v4.app.FragmentActivity;\nimport android.util.DisplayMetrics;\nimport android.widget.Button;\nimport java.util.Random;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic class MainActivity extends FragmentActivity {\n Handler handler;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n handler = new Handler();\n final Button button = (Button) findViewById(R.id.my_button);\n final DisplayMetrics displaymetrics = new DisplayMetrics();\n getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);\n final Timer timer = new Timer();\n timer.schedule(new TimerTask() {\n @Override\n public void run() {\n handler.post(new Runnable() {\n @Override\n public void run() {\n Random R = new Random();\n final float dx = R.nextFloat() * displaymetrics.widthPixels;\n final float dy = R.nextFloat() * displaymetrics.heightPixels;\n final Timer timer = new Timer();\n button.animate()\n .x(dx)\n .y(dy)\n .setDuration(0)\n .start();\n }\n });\n }\n }, 0, 1000);\n }\n}" }, { "code": null, "e": 3687, "s": 3340, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3727, "s": 3687, "text": "Click here to download the project code" } ]
How can I convert Python dictionary to JavaScript hash table?
Python and javascript both have different representations for a dictionary. So you need an intermediate representation in order to pass data between them. The most commonly used intermediate representation is JSON, which is a simple lightweight data-interchange format. The dumps function converts the dict to a string. import json my_dict = { 'foo': 42,'bar': { 'baz': "Hello",'poo': 124.2 } } my_json = json.dumps(my_dict) print(my_json) This will give the output − '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}' The load's function converts the string back to a dict. import json my_str = '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}' my_dict = json.loads(my_str) print(my_dict['bar']['baz']) This will give the output − Hello On the JS side of things, you don't need to do anything. This is because JSON literally means JavaScript Object Notation. And JS implicitly constructs objects from JSON. If you get a string, you can convert it using JSON.parse().
[ { "code": null, "e": 1332, "s": 1062, "text": "Python and javascript both have different representations for a dictionary. So you need an intermediate representation in order to pass data between them. The most commonly used intermediate representation is JSON, which is a simple lightweight data-interchange format." }, { "code": null, "e": 1383, "s": 1332, "text": "The dumps function converts the dict to a string. " }, { "code": null, "e": 1515, "s": 1383, "text": "import json\nmy_dict = {\n 'foo': 42,'bar': {\n 'baz': \"Hello\",'poo': 124.2\n }\n}\nmy_json = json.dumps(my_dict)\nprint(my_json)" }, { "code": null, "e": 1543, "s": 1515, "text": "This will give the output −" }, { "code": null, "e": 1596, "s": 1543, "text": "'{\"foo\": 42, \"bar\": {\"baz\": \"Hello\", \"poo\": 124.2}}'" }, { "code": null, "e": 1653, "s": 1596, "text": "The load's function converts the string back to a dict. " }, { "code": null, "e": 1785, "s": 1653, "text": "import json\nmy_str = '{\"foo\": 42, \"bar\": {\"baz\": \"Hello\", \"poo\": 124.2}}'\nmy_dict = json.loads(my_str)\nprint(my_dict['bar']['baz'])" }, { "code": null, "e": 1813, "s": 1785, "text": "This will give the output −" }, { "code": null, "e": 1819, "s": 1813, "text": "Hello" }, { "code": null, "e": 2049, "s": 1819, "text": "On the JS side of things, you don't need to do anything. This is because JSON literally means JavaScript Object Notation. And JS implicitly constructs objects from JSON. If you get a string, you can convert it using JSON.parse()." } ]
Deep Convolutional GAN with Keras - GeeksforGeeks
28 Jan, 2022 Deep Convolutional GAN (DCGAN) was proposed by a researcher from MIT and Facebook AI research .It is widely used in many convolution based generation based techniques. The focus of this paper was to make training GANs stable . Hence, they proposed some architectural changes in computer vision problem. In this article we will be using DCGAN on fashion MNIST dataset to generate the images related to clothes. Architecture: The generator of the DCGAN architecture takes 100 uniform generated values using normal distribution as an input. First, it changes the dimension to 4x4x1024 and performed a fractionally strided convolution in 4 times with stride of 1/2 (this means every time when applied, it doubles the image dimension while reducing the number of output channels). The generated output has dimensions of (64, 64, 3). There are some architectural changes proposed in generator such as removal of all fully connected layer, use of Batch Normalization which helps in stabilizing training. In this paper, the authors use ReLU activation function in all layers of generator, except for the output layers. We will be implementing generator with similar guidelines but not completely same architecture. The role of the discriminator here is to determine that the image comes from either real dataset or generator. The discriminator can be simply designed similar to a convolution neural network that performs a image classification task. However, the authors of this paper suggested some changes in the discriminator architecture. Instead of fully connected layers, they used only strided-convolutions with LeakyReLU as activation function, the input of the generator is a single image from dataset or generated image and the output is a score that determines the image is real or generated. Implementation: In this section we will be discussing implementation of DCGAN in keras, since our dataset in Fashion MNIST dataset, this dataset contains images of size (28, 28) of 1 color channel instead of (64, 64) of 3 color channels. So, we needs to make some changes in the architecture , we will be discussing these changes as we go along. In first step, we need to import the necessary classes such as TensorFlow, keras , matplotlib etc. We will be using TensorFlow version 2. This version of tensorflow provides inbuilt support for Keras library as its default High level API. python3 # code % matplotlib inlineimport tensorflow as tffrom tensorflow import kerasimport numpy as npimport matplotlib.pyplot as pltfrom tqdm import tqdmfrom IPython import display # Check tensorflow versionprint('Tensorflow version:', tf.__version__) Now we load the fashion-MNIST dataset, the good thing is that dataset can be imported from tf.keras.datasets API. So, we don’t need to load datasets manually by copying files. This dateset contains 60k training images and 10k test images each of dimensions(28, 28, 1). Since the value of each pixel is in the range (0, 255), we divide these values by 255 to normalize it. python3 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()x_train = x_train.astype(np.float32) / 255.0x_test = x_test.astype(np.float32) / 255.0x_train.shape, x_test.shape ((60000, 28, 28), (10000, 28, 28)) Now in the next step, we will be visualizing some of the images from Fashion-MNIST dateset, we use matplotlib library for that. python3 # We plot first 25 images of training datasetplt.figure(figsize =(10, 10))for i in range(25): plt.subplot(5, 5, i + 1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(x_train[i], cmap = plt.cm.binary)plt.show() Original Fashion MNIST images Now, we define training parameters such as batch size and divides the dataset into batch size and fills those batch size by randomly sampling the training data. python3 # codebatch_size = 32# This dataset fills a buffer with buffer_size elements,# then randomly samples elements from this buffer,# replacing the selected elements with new elements.def create_batch(x_train): dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(1000) # Combines consecutive elements of this dataset into batches. dataset = dataset.batch(batch_size, drop_remainder = True).prefetch(1) # Creates a Dataset that prefetches elements from this dataset return dataset Now, we define the generator architecture, this generator architecture takes a vector of size 100 and first reshape that into (7, 7, 128) vector then applied transpose convolution in combination with batch normalization. The output of this generator is a trained an image of dimension (28, 28, 1). python3 # codenum_features = 100 generator = keras.models.Sequential([ keras.layers.Dense(7 * 7 * 128, input_shape =[num_features]), keras.layers.Reshape([7, 7, 128]), keras.layers.BatchNormalization(), keras.layers.Conv2DTranspose( 64, (5, 5), (2, 2), padding ="same", activation ="selu"), keras.layers.BatchNormalization(), keras.layers.Conv2DTranspose( 1, (5, 5), (2, 2), padding ="same", activation ="tanh"),])generator.summary() Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 6272) 633472 _________________________________________________________________ reshape (Reshape) (None, 7, 7, 128) 0 _________________________________________________________________ batch_normalization (BatchNo (None, 7, 7, 128) 512 _________________________________________________________________ conv2d_transpose (Conv2DTran (None, 14, 14, 64) 204864 _________________________________________________________________ batch_normalization_1 (Batch (None, 14, 14, 64) 256 _________________________________________________________________ conv2d_transpose_1 (Conv2DTr (None, 28, 28, 1) 1601 ================================================================= Total params: 840, 705 Trainable params: 840, 321 Non-trainable params: 384 _________________________________________________________________ Now, we define out discriminator architecture, the discriminator takes image of size 28*28 with 1 color channel and output a scalar value representing image from either dataset or generated image. python3 discriminator = keras.models.Sequential([ keras.layers.Conv2D(64, (5, 5), (2, 2), padding ="same", input_shape =[28, 28, 1]), keras.layers.LeakyReLU(0.2), keras.layers.Dropout(0.3), keras.layers.Conv2D(128, (5, 5), (2, 2), padding ="same"), keras.layers.LeakyReLU(0.2), keras.layers.Dropout(0.3), keras.layers.Flatten(), keras.layers.Dense(1, activation ='sigmoid')])discriminator.summary() Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 14, 14, 64) 1664 _________________________________________________________________ leaky_re_lu (LeakyReLU) (None, 14, 14, 64) 0 _________________________________________________________________ dropout (Dropout) (None, 14, 14, 64) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 7, 7, 128) 204928 _________________________________________________________________ leaky_re_lu_1 (LeakyReLU) (None, 7, 7, 128) 0 _________________________________________________________________ dropout_1 (Dropout) (None, 7, 7, 128) 0 _________________________________________________________________ flatten (Flatten) (None, 6272) 0 _________________________________________________________________ dense_1 (Dense) (None, 1) 6273 ================================================================= Total params: 212, 865 Trainable params: 212, 865 Non-trainable params: 0 _________________________________________________________________ Now we need to compile the our DCGAN model (combination of generator and discriminator), we will first compile discriminator and set its training to False, because we first want to train the generator. python3 # compile discriminator using binary cross entropy loss and adam optimizerdiscriminator.compile(loss ="binary_crossentropy", optimizer ="adam")# make discriminator no-trainable as of nowdiscriminator.trainable = False# Combine both generator and discriminatorgan = keras.models.Sequential([generator, discriminator])# compile generator using binary cross entropy loss and adam optimizer gan.compile(loss ="binary_crossentropy", optimizer ="adam") Now, we define the training procedure for this GAN model, we will be using tqdm package which we have imported earlier., this package help in visualizing training. python3 seed = tf.random.normal(shape =[batch_size, 100]) def train_dcgan(gan, dataset, batch_size, num_features, epochs = 5): generator, discriminator = gan.layers for epoch in tqdm(range(epochs)): print() print("Epoch {}/{}".format(epoch + 1, epochs)) for X_batch in dataset: # create a random noise of sizebatch_size * 100 # to passit into the generator noise = tf.random.normal(shape =[batch_size, num_features]) generated_images = generator(noise) # take batch of generated image and real image and # use them to train the discriminator X_fake_and_real = tf.concat([generated_images, X_batch], axis = 0) y1 = tf.constant([[0.]] * batch_size + [[1.]] * batch_size) discriminator.trainable = True discriminator.train_on_batch(X_fake_and_real, y1) # Here we will be training our GAN model, in this step # we pass noise that uses generatortogenerate the image # and pass it with labels as [1] So, it can fool the discriminator noise = tf.random.normal(shape =[batch_size, num_features]) y2 = tf.constant([[1.]] * batch_size) discriminator.trainable = False gan.train_on_batch(noise, y2) # generate images for the GIF as we go generate_and_save_images(generator, epoch + 1, seed) generate_and_save_images(generator, epochs, seed) Now we define a function that generate and save images from generator (during training). We will use these generated images to plot the GIF later. python3 # codedef generate_and_save_images(model, epoch, test_input): predictions = model(test_input, training = False) fig = plt.figure(figsize =(10, 10)) for i in range(25): plt.subplot(5, 5, i + 1) plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap ='binary') plt.axis('off') plt.savefig('image_epoch_{:04d}.png'.format(epoch)) Now, we need to train the model but before that we also need to create batches of training data and add a dimension that represents number of color maps. python3 # reshape to add a color mapx_train_dcgan = x_train.reshape(-1, 28, 28, 1) * 2. - 1.# create batchesdataset = create_batch(x_train_dcgan)# callthe training function with 10 epochs and record time %% timetrain_dcgan(gan, dataset, batch_size, num_features, epochs = 10) 0%| | 0/10 [00:00<?, ?it/s] Epoch 1/10 10%|? | 1/10 [01:04<09:39, 64.37s/it] Epoch 2/10 20%|?? | 2/10 [02:10<08:39, 64.99s/it] Epoch 3/10 30%|??? | 3/10 [03:14<07:33, 64.74s/it] Epoch 4/10 40%|???? | 4/10 [04:19<06:27, 64.62s/it] Epoch 5/10 50%|????? | 5/10 [05:23<05:22, 64.58s/it] Epoch 6/10 60%|?????? | 6/10 [06:27<04:17, 64.47s/it] Epoch 7/10 70%|??????? | 7/10 [07:32<03:13, 64.55s/it] Epoch 8/10 80%|???????? | 8/10 [08:37<02:08, 64.48s/it] Epoch 9/10 90%|????????? | 9/10 [09:41<01:04, 64.54s/it] Epoch 10/10 100%|??????????| 10/10 [10:46<00:00, 64.61s/it] CPU times: user 7min 4s, sys: 33.3 s, total: 7min 37s Wall time: 10min 46s Now we will define a function that takes the save images and convert into GIF. We use this function from here python3 import imageioimport glob anim_file = 'dcgan_results.gif' with imageio.get_writer(anim_file, mode ='I') as writer: filenames = glob.glob('image*.png') filenames = sorted(filenames) last = -1 for i, filename in enumerate(filenames): frame = 2*(i) if round(frame) > round(last): last = frame else: continue image = imageio.imread(filename) writer.append_data(image) image = imageio.imread(filename) writer.append_data(image)display.Image(filename = anim_file) Generated Images results Results and Conclusion: To evaluate the quality of the representations learned by DCGANs for supervised tasks, the authors train the model on ImageNet-1k and then use the discriminator’s convolution features from all layers, max pooling each layers representation to produce a 4 × 4 spatial grid. These features are then flattened and concatenated to form a 28672 dimensional vector and a regularized linear L2-SVM classifier is trained on top of them. This model is then evaluated on CIFAR-10 dataset but not trained don it. The model reported an accuracy of 82 % which also displays robustness of the model. On Street View Housing Number dataset, it achieved a validation loss of 22% which is the new state-of-the-art, even discriminator architecture when supervise trained as a CNN model has more validation loss than it. References: DCGAN paper simmytarika5 surinderdawra388 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree Python | Decision tree implementation ML | Underfitting and Overfitting Reinforcement learning Decision Tree Introduction with example Adding new column to existing DataFrame in Pandas Read JSON file using Python Python map() function Python Dictionary Taking input in Python
[ { "code": null, "e": 24656, "s": 24628, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25066, "s": 24656, "text": "Deep Convolutional GAN (DCGAN) was proposed by a researcher from MIT and Facebook AI research .It is widely used in many convolution based generation based techniques. The focus of this paper was to make training GANs stable . Hence, they proposed some architectural changes in computer vision problem. In this article we will be using DCGAN on fashion MNIST dataset to generate the images related to clothes." }, { "code": null, "e": 25080, "s": 25066, "text": "Architecture:" }, { "code": null, "e": 25865, "s": 25080, "text": "The generator of the DCGAN architecture takes 100 uniform generated values using normal distribution as an input. First, it changes the dimension to 4x4x1024 and performed a fractionally strided convolution in 4 times with stride of 1/2 (this means every time when applied, it doubles the image dimension while reducing the number of output channels). The generated output has dimensions of (64, 64, 3). There are some architectural changes proposed in generator such as removal of all fully connected layer, use of Batch Normalization which helps in stabilizing training. In this paper, the authors use ReLU activation function in all layers of generator, except for the output layers. We will be implementing generator with similar guidelines but not completely same architecture." }, { "code": null, "e": 26456, "s": 25865, "text": "The role of the discriminator here is to determine that the image comes from either real dataset or generator. The discriminator can be simply designed similar to a convolution neural network that performs a image classification task. However, the authors of this paper suggested some changes in the discriminator architecture. Instead of fully connected layers, they used only strided-convolutions with LeakyReLU as activation function, the input of the generator is a single image from dataset or generated image and the output is a score that determines the image is real or generated." }, { "code": null, "e": 26472, "s": 26456, "text": "Implementation:" }, { "code": null, "e": 26807, "s": 26472, "text": "In this section we will be discussing implementation of DCGAN in keras, since our dataset in Fashion MNIST dataset, this dataset contains images of size (28, 28) of 1 color channel instead of (64, 64) of 3 color channels. So, we needs to make some changes in the architecture , we will be discussing these changes as we go along." }, { "code": null, "e": 27049, "s": 26807, "text": "In first step, we need to import the necessary classes such as TensorFlow, keras , matplotlib etc. We will be using TensorFlow version 2. This version of tensorflow provides inbuilt support for Keras library as its default High level API." }, { "code": null, "e": 27057, "s": 27049, "text": "python3" }, { "code": "# code % matplotlib inlineimport tensorflow as tffrom tensorflow import kerasimport numpy as npimport matplotlib.pyplot as pltfrom tqdm import tqdmfrom IPython import display # Check tensorflow versionprint('Tensorflow version:', tf.__version__)", "e": 27303, "s": 27057, "text": null }, { "code": null, "e": 27676, "s": 27303, "text": "Now we load the fashion-MNIST dataset, the good thing is that dataset can be imported from tf.keras.datasets API. So, we don’t need to load datasets manually by copying files. This dateset contains 60k training images and 10k test images each of dimensions(28, 28, 1). Since the value of each pixel is in the range (0, 255), we divide these values by 255 to normalize it." }, { "code": null, "e": 27684, "s": 27676, "text": "python3" }, { "code": "(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()x_train = x_train.astype(np.float32) / 255.0x_test = x_test.astype(np.float32) / 255.0x_train.shape, x_test.shape", "e": 27880, "s": 27684, "text": null }, { "code": null, "e": 27915, "s": 27880, "text": "((60000, 28, 28), (10000, 28, 28))" }, { "code": null, "e": 28044, "s": 27915, "text": "Now in the next step, we will be visualizing some of the images from Fashion-MNIST dateset, we use matplotlib library for that." }, { "code": null, "e": 28052, "s": 28044, "text": "python3" }, { "code": "# We plot first 25 images of training datasetplt.figure(figsize =(10, 10))for i in range(25): plt.subplot(5, 5, i + 1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(x_train[i], cmap = plt.cm.binary)plt.show()", "e": 28287, "s": 28052, "text": null }, { "code": null, "e": 28317, "s": 28287, "text": "Original Fashion MNIST images" }, { "code": null, "e": 28478, "s": 28317, "text": "Now, we define training parameters such as batch size and divides the dataset into batch size and fills those batch size by randomly sampling the training data." }, { "code": null, "e": 28486, "s": 28478, "text": "python3" }, { "code": "# codebatch_size = 32# This dataset fills a buffer with buffer_size elements,# then randomly samples elements from this buffer,# replacing the selected elements with new elements.def create_batch(x_train): dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(1000) # Combines consecutive elements of this dataset into batches. dataset = dataset.batch(batch_size, drop_remainder = True).prefetch(1) # Creates a Dataset that prefetches elements from this dataset return dataset", "e": 28977, "s": 28486, "text": null }, { "code": null, "e": 29275, "s": 28977, "text": "Now, we define the generator architecture, this generator architecture takes a vector of size 100 and first reshape that into (7, 7, 128) vector then applied transpose convolution in combination with batch normalization. The output of this generator is a trained an image of dimension (28, 28, 1)." }, { "code": null, "e": 29283, "s": 29275, "text": "python3" }, { "code": "# codenum_features = 100 generator = keras.models.Sequential([ keras.layers.Dense(7 * 7 * 128, input_shape =[num_features]), keras.layers.Reshape([7, 7, 128]), keras.layers.BatchNormalization(), keras.layers.Conv2DTranspose( 64, (5, 5), (2, 2), padding =\"same\", activation =\"selu\"), keras.layers.BatchNormalization(), keras.layers.Conv2DTranspose( 1, (5, 5), (2, 2), padding =\"same\", activation =\"tanh\"),])generator.summary()", "e": 29741, "s": 29283, "text": null }, { "code": null, "e": 30893, "s": 29741, "text": "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 6272) 633472 \n_________________________________________________________________\nreshape (Reshape) (None, 7, 7, 128) 0 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 7, 7, 128) 512 \n_________________________________________________________________\nconv2d_transpose (Conv2DTran (None, 14, 14, 64) 204864 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 14, 14, 64) 256 \n_________________________________________________________________\nconv2d_transpose_1 (Conv2DTr (None, 28, 28, 1) 1601 \n=================================================================\nTotal params: 840, 705\nTrainable params: 840, 321\nNon-trainable params: 384\n_________________________________________________________________" }, { "code": null, "e": 31091, "s": 30893, "text": "Now, we define out discriminator architecture, the discriminator takes image of size 28*28 with 1 color channel and output a scalar value representing image from either dataset or generated image." }, { "code": null, "e": 31099, "s": 31091, "text": "python3" }, { "code": "discriminator = keras.models.Sequential([ keras.layers.Conv2D(64, (5, 5), (2, 2), padding =\"same\", input_shape =[28, 28, 1]), keras.layers.LeakyReLU(0.2), keras.layers.Dropout(0.3), keras.layers.Conv2D(128, (5, 5), (2, 2), padding =\"same\"), keras.layers.LeakyReLU(0.2), keras.layers.Dropout(0.3), keras.layers.Flatten(), keras.layers.Dense(1, activation ='sigmoid')])discriminator.summary()", "e": 31514, "s": 31099, "text": null }, { "code": null, "e": 32930, "s": 31514, "text": "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 14, 14, 64) 1664 \n_________________________________________________________________\nleaky_re_lu (LeakyReLU) (None, 14, 14, 64) 0 \n_________________________________________________________________\ndropout (Dropout) (None, 14, 14, 64) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 7, 7, 128) 204928 \n_________________________________________________________________\nleaky_re_lu_1 (LeakyReLU) (None, 7, 7, 128) 0 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 7, 7, 128) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 6272) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 6273 \n=================================================================\nTotal params: 212, 865\nTrainable params: 212, 865\nNon-trainable params: 0\n_________________________________________________________________" }, { "code": null, "e": 33133, "s": 32930, "text": "Now we need to compile the our DCGAN model (combination of generator and discriminator), we will first compile discriminator and set its training to False, because we first want to train the generator." }, { "code": null, "e": 33141, "s": 33133, "text": "python3" }, { "code": "# compile discriminator using binary cross entropy loss and adam optimizerdiscriminator.compile(loss =\"binary_crossentropy\", optimizer =\"adam\")# make discriminator no-trainable as of nowdiscriminator.trainable = False# Combine both generator and discriminatorgan = keras.models.Sequential([generator, discriminator])# compile generator using binary cross entropy loss and adam optimizer gan.compile(loss =\"binary_crossentropy\", optimizer =\"adam\")", "e": 33590, "s": 33141, "text": null }, { "code": null, "e": 33754, "s": 33590, "text": "Now, we define the training procedure for this GAN model, we will be using tqdm package which we have imported earlier., this package help in visualizing training." }, { "code": null, "e": 33762, "s": 33754, "text": "python3" }, { "code": "seed = tf.random.normal(shape =[batch_size, 100]) def train_dcgan(gan, dataset, batch_size, num_features, epochs = 5): generator, discriminator = gan.layers for epoch in tqdm(range(epochs)): print() print(\"Epoch {}/{}\".format(epoch + 1, epochs)) for X_batch in dataset: # create a random noise of sizebatch_size * 100 # to passit into the generator noise = tf.random.normal(shape =[batch_size, num_features]) generated_images = generator(noise) # take batch of generated image and real image and # use them to train the discriminator X_fake_and_real = tf.concat([generated_images, X_batch], axis = 0) y1 = tf.constant([[0.]] * batch_size + [[1.]] * batch_size) discriminator.trainable = True discriminator.train_on_batch(X_fake_and_real, y1) # Here we will be training our GAN model, in this step # we pass noise that uses generatortogenerate the image # and pass it with labels as [1] So, it can fool the discriminator noise = tf.random.normal(shape =[batch_size, num_features]) y2 = tf.constant([[1.]] * batch_size) discriminator.trainable = False gan.train_on_batch(noise, y2) # generate images for the GIF as we go generate_and_save_images(generator, epoch + 1, seed) generate_and_save_images(generator, epochs, seed)", "e": 35232, "s": 33762, "text": null }, { "code": null, "e": 35379, "s": 35232, "text": "Now we define a function that generate and save images from generator (during training). We will use these generated images to plot the GIF later." }, { "code": null, "e": 35387, "s": 35379, "text": "python3" }, { "code": "# codedef generate_and_save_images(model, epoch, test_input): predictions = model(test_input, training = False) fig = plt.figure(figsize =(10, 10)) for i in range(25): plt.subplot(5, 5, i + 1) plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap ='binary') plt.axis('off') plt.savefig('image_epoch_{:04d}.png'.format(epoch))", "e": 35738, "s": 35387, "text": null }, { "code": null, "e": 35893, "s": 35738, "text": "Now, we need to train the model but before that we also need to create batches of training data and add a dimension that represents number of color maps." }, { "code": null, "e": 35901, "s": 35893, "text": "python3" }, { "code": "# reshape to add a color mapx_train_dcgan = x_train.reshape(-1, 28, 28, 1) * 2. - 1.# create batchesdataset = create_batch(x_train_dcgan)# callthe training function with 10 epochs and record time %% timetrain_dcgan(gan, dataset, batch_size, num_features, epochs = 10)", "e": 36169, "s": 35901, "text": null }, { "code": null, "e": 36873, "s": 36169, "text": "0%| | 0/10 [00:00<?, ?it/s]\nEpoch 1/10\n\n 10%|? | 1/10 [01:04<09:39, 64.37s/it]\nEpoch 2/10\n\n 20%|?? | 2/10 [02:10<08:39, 64.99s/it]\nEpoch 3/10\n\n 30%|??? | 3/10 [03:14<07:33, 64.74s/it]\nEpoch 4/10\n\n 40%|???? | 4/10 [04:19<06:27, 64.62s/it]\nEpoch 5/10\n\n 50%|????? | 5/10 [05:23<05:22, 64.58s/it]\nEpoch 6/10\n\n 60%|?????? | 6/10 [06:27<04:17, 64.47s/it]\nEpoch 7/10\n\n 70%|??????? | 7/10 [07:32<03:13, 64.55s/it]\nEpoch 8/10\n\n 80%|???????? | 8/10 [08:37<02:08, 64.48s/it]\nEpoch 9/10\n\n 90%|????????? | 9/10 [09:41<01:04, 64.54s/it]\nEpoch 10/10\n\n100%|??????????| 10/10 [10:46<00:00, 64.61s/it]\nCPU times: user 7min 4s, sys: 33.3 s, total: 7min 37s\nWall time: 10min 46s" }, { "code": null, "e": 36985, "s": 36873, "text": "Now we will define a function that takes the save images and convert into GIF. We use this function from here" }, { "code": null, "e": 36993, "s": 36985, "text": "python3" }, { "code": "import imageioimport glob anim_file = 'dcgan_results.gif' with imageio.get_writer(anim_file, mode ='I') as writer: filenames = glob.glob('image*.png') filenames = sorted(filenames) last = -1 for i, filename in enumerate(filenames): frame = 2*(i) if round(frame) > round(last): last = frame else: continue image = imageio.imread(filename) writer.append_data(image) image = imageio.imread(filename) writer.append_data(image)display.Image(filename = anim_file)", "e": 37482, "s": 36993, "text": null }, { "code": null, "e": 37507, "s": 37482, "text": "Generated Images results" }, { "code": null, "e": 37531, "s": 37507, "text": "Results and Conclusion:" }, { "code": null, "e": 38118, "s": 37531, "text": "To evaluate the quality of the representations learned by DCGANs for supervised tasks, the authors train the model on ImageNet-1k and then use the discriminator’s convolution features from all layers, max pooling each layers representation to produce a 4 × 4 spatial grid. These features are then flattened and concatenated to form a 28672 dimensional vector and a regularized linear L2-SVM classifier is trained on top of them. This model is then evaluated on CIFAR-10 dataset but not trained don it. The model reported an accuracy of 82 % which also displays robustness of the model." }, { "code": null, "e": 38333, "s": 38118, "text": "On Street View Housing Number dataset, it achieved a validation loss of 22% which is the new state-of-the-art, even discriminator architecture when supervise trained as a CNN model has more validation loss than it." }, { "code": null, "e": 38345, "s": 38333, "text": "References:" }, { "code": null, "e": 38357, "s": 38345, "text": "DCGAN paper" }, { "code": null, "e": 38370, "s": 38357, "text": "simmytarika5" }, { "code": null, "e": 38387, "s": 38370, "text": "surinderdawra388" }, { "code": null, "e": 38404, "s": 38387, "text": "Machine Learning" }, { "code": null, "e": 38411, "s": 38404, "text": "Python" }, { "code": null, "e": 38428, "s": 38411, "text": "Machine Learning" }, { "code": null, "e": 38526, "s": 38428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38535, "s": 38526, "text": "Comments" }, { "code": null, "e": 38548, "s": 38535, "text": "Old Comments" }, { "code": null, "e": 38562, "s": 38548, "text": "Decision Tree" }, { "code": null, "e": 38600, "s": 38562, "text": "Python | Decision tree implementation" }, { "code": null, "e": 38634, "s": 38600, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 38657, "s": 38634, "text": "Reinforcement learning" }, { "code": null, "e": 38697, "s": 38657, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 38747, "s": 38697, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 38775, "s": 38747, "text": "Read JSON file using Python" }, { "code": null, "e": 38797, "s": 38775, "text": "Python map() function" }, { "code": null, "e": 38815, "s": 38797, "text": "Python Dictionary" } ]
Count occurrences of elements of list in Java - GeeksforGeeks
11 Dec, 2018 Suppose we have an elements in ArrayList, we can count the occurrences of elements present in a number of ways. This data structure uses hash function to map similar values, known as keys to their associated values. Map values can be retrieved using key as it contains key-value pairs. // Java program to count frequencies of elements// using HashMap.import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.*; class GFG { public static void countFrequencies(ArrayList<String> list) { // hashmap to store the frequency of element Map<String, Integer> hm = new HashMap<String, Integer>(); for (String i : list) { Integer j = hm.get(i); hm.put(i, (j == null) ? 1 : j + 1); } // displaying the occurrence of elements in the arraylist for (Map.Entry<String, Integer> val : hm.entrySet()) { System.out.println("Element " + val.getKey() + " " + "occurs" + ": " + val.getValue() + " times"); } } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("for"); list.add("Geeks"); countFrequencies(list); }} Element Geeks occurs: 2 times Element for occurs: 1 times This data structure does not allow duplicate elements as it implements Set Interface. Objects are inserted based on their hash code. To count occurrences of elements of ArrayList, we create HashSet and add all the elements of ArrayList. We use Collections.frequency(Collection c, Object o) to count the occurrence of object o in the collection c. Below program illustrate the working of HashSet: Program to find occurrence of words // Java program to count frequencies of elements// using HashSet and Collections.frequency.import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.*; class GFG { public static void countFrequencies(ArrayList<String> list) { // hash set is created and elements of // arraylist are insertd into it Set<String> st = new HashSet<String>(list); for (String s : st) System.out.println(s + ": " + Collections.frequency(list, s)); } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("for"); list.add("Geeks"); countFrequencies(list); }} Geeks: 2 for: 1 This data structure stores unique elements in sorted order. It uses the concept of red-black-tree in the background to prevent duplicates. // Java program to count frequencies of elements// using HashMap.import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.*; class GFG { public static void countFrequencies(ArrayList<String> list) { TreeMap<String, Integer> tmap = new TreeMap<String, Integer>(); for (String t : list) { Integer c = tmap.get(t); tmap.put(t, (c == null) ? 1 : c + 1); } for (Map.Entry m : tmap.entrySet()) System.out.println("Frequency of " + m.getKey() + " is " + m.getValue()); } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("for"); list.add("Geeks"); countFrequencies(list); }} Frequency of Geeks is 2 Frequency of for is 1 Key Points: HashMap implements Map Interface while TreeMap implements SortedMap Interface. HashMap uses Hashing whereas TreeMap uses Red-Black Tree(Balanced BST). So HashMap based solutions are generally much faster than TreeMap based solutions. mike00 frequency-counting Java-HashMap java-hashset java-list Java-List-Programs Java-Map-Programs java-TreeMap Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24919, "s": 24891, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25031, "s": 24919, "text": "Suppose we have an elements in ArrayList, we can count the occurrences of elements present in a number of ways." }, { "code": null, "e": 25205, "s": 25031, "text": "This data structure uses hash function to map similar values, known as keys to their associated values. Map values can be retrieved using key as it contains key-value pairs." }, { "code": "// Java program to count frequencies of elements// using HashMap.import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.*; class GFG { public static void countFrequencies(ArrayList<String> list) { // hashmap to store the frequency of element Map<String, Integer> hm = new HashMap<String, Integer>(); for (String i : list) { Integer j = hm.get(i); hm.put(i, (j == null) ? 1 : j + 1); } // displaying the occurrence of elements in the arraylist for (Map.Entry<String, Integer> val : hm.entrySet()) { System.out.println(\"Element \" + val.getKey() + \" \" + \"occurs\" + \": \" + val.getValue() + \" times\"); } } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); countFrequencies(list); }}", "e": 26216, "s": 25205, "text": null }, { "code": null, "e": 26275, "s": 26216, "text": "Element Geeks occurs: 2 times\nElement for occurs: 1 times\n" }, { "code": null, "e": 26408, "s": 26275, "text": "This data structure does not allow duplicate elements as it implements Set Interface. Objects are inserted based on their hash code." }, { "code": null, "e": 26622, "s": 26408, "text": "To count occurrences of elements of ArrayList, we create HashSet and add all the elements of ArrayList. We use Collections.frequency(Collection c, Object o) to count the occurrence of object o in the collection c." }, { "code": null, "e": 26671, "s": 26622, "text": "Below program illustrate the working of HashSet:" }, { "code": null, "e": 26707, "s": 26671, "text": "Program to find occurrence of words" }, { "code": "// Java program to count frequencies of elements// using HashSet and Collections.frequency.import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.*; class GFG { public static void countFrequencies(ArrayList<String> list) { // hash set is created and elements of // arraylist are insertd into it Set<String> st = new HashSet<String>(list); for (String s : st) System.out.println(s + \": \" + Collections.frequency(list, s)); } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); countFrequencies(list); }}", "e": 27436, "s": 26707, "text": null }, { "code": null, "e": 27453, "s": 27436, "text": "Geeks: 2\nfor: 1\n" }, { "code": null, "e": 27592, "s": 27453, "text": "This data structure stores unique elements in sorted order. It uses the concept of red-black-tree in the background to prevent duplicates." }, { "code": "// Java program to count frequencies of elements// using HashMap.import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.*; class GFG { public static void countFrequencies(ArrayList<String> list) { TreeMap<String, Integer> tmap = new TreeMap<String, Integer>(); for (String t : list) { Integer c = tmap.get(t); tmap.put(t, (c == null) ? 1 : c + 1); } for (Map.Entry m : tmap.entrySet()) System.out.println(\"Frequency of \" + m.getKey() + \" is \" + m.getValue()); } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); countFrequencies(list); }}", "e": 28383, "s": 27592, "text": null }, { "code": null, "e": 28430, "s": 28383, "text": "Frequency of Geeks is 2\nFrequency of for is 1\n" }, { "code": null, "e": 28442, "s": 28430, "text": "Key Points:" }, { "code": null, "e": 28521, "s": 28442, "text": "HashMap implements Map Interface while TreeMap implements SortedMap Interface." }, { "code": null, "e": 28676, "s": 28521, "text": "HashMap uses Hashing whereas TreeMap uses Red-Black Tree(Balanced BST). So HashMap based solutions are generally much faster than TreeMap based solutions." }, { "code": null, "e": 28683, "s": 28676, "text": "mike00" }, { "code": null, "e": 28702, "s": 28683, "text": "frequency-counting" }, { "code": null, "e": 28715, "s": 28702, "text": "Java-HashMap" }, { "code": null, "e": 28728, "s": 28715, "text": "java-hashset" }, { "code": null, "e": 28738, "s": 28728, "text": "java-list" }, { "code": null, "e": 28757, "s": 28738, "text": "Java-List-Programs" }, { "code": null, "e": 28775, "s": 28757, "text": "Java-Map-Programs" }, { "code": null, "e": 28788, "s": 28775, "text": "java-TreeMap" }, { "code": null, "e": 28793, "s": 28788, "text": "Java" }, { "code": null, "e": 28807, "s": 28793, "text": "Java Programs" }, { "code": null, "e": 28812, "s": 28807, "text": "Java" }, { "code": null, "e": 28910, "s": 28812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28919, "s": 28910, "text": "Comments" }, { "code": null, "e": 28932, "s": 28919, "text": "Old Comments" }, { "code": null, "e": 28962, "s": 28932, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28993, "s": 28962, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29012, "s": 28993, "text": "Interfaces in Java" }, { "code": null, "e": 29044, "s": 29012, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29062, "s": 29044, "text": "ArrayList in Java" }, { "code": null, "e": 29106, "s": 29062, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 29134, "s": 29106, "text": "Initializing a List in Java" }, { "code": null, "e": 29160, "s": 29134, "text": "Java Programming Examples" }, { "code": null, "e": 29194, "s": 29160, "text": "Convert Double to Integer in Java" } ]
How to remove an object using filter() in JavaScript?
Let’s say, we have the following objects in JavaScript − ObjectValue =[ { "id": "101", "details": { Name:"John",subjectName:"JavaScript" }}, { "id": "102", "details": { Name:"David",subjectName:"MongoDB" }}, { "id": "103" } ] To remove an object using filter(), the code is as follows − ObjectValue =[ { "id": "101", "details": { Name:"John",subjectName:"JavaScript" }}, { "id": "102", "details": { Name:"David",subjectName:"MongoDB" }}, { "id": "103" } ] output=ObjectValue.filter(obj=>obj.details) console.log(output) To run the above program, you need to use the following command − node fileName.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo46.js [ { id: '101', details: { Name: 'John', subjectName: 'JavaScript' } }, { id: '102', details: { Name: 'David', subjectName: 'MongoDB' } } ]
[ { "code": null, "e": 1119, "s": 1062, "text": "Let’s say, we have the following objects in JavaScript −" }, { "code": null, "e": 1297, "s": 1119, "text": "ObjectValue =[\n { \"id\": \"101\", \"details\": { Name:\"John\",subjectName:\"JavaScript\" }},\n { \"id\": \"102\", \"details\": { Name:\"David\",subjectName:\"MongoDB\" }},\n { \"id\": \"103\" }\n]" }, { "code": null, "e": 1358, "s": 1297, "text": "To remove an object using filter(), the code is as follows −" }, { "code": null, "e": 1600, "s": 1358, "text": "ObjectValue =[\n { \"id\": \"101\", \"details\": { Name:\"John\",subjectName:\"JavaScript\" }},\n { \"id\": \"102\", \"details\": { Name:\"David\",subjectName:\"MongoDB\" }},\n { \"id\": \"103\" }\n]\noutput=ObjectValue.filter(obj=>obj.details)\nconsole.log(output)" }, { "code": null, "e": 1666, "s": 1600, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1684, "s": 1666, "text": "node fileName.js." }, { "code": null, "e": 1725, "s": 1684, "text": "This will produce the following output −" }, { "code": null, "e": 1919, "s": 1725, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo46.js\n[\n { id: '101', details: { Name: 'John', subjectName: 'JavaScript' } },\n { id: '102', details: { Name: 'David', subjectName: 'MongoDB' } }\n]" } ]
Explain about triggers and active databases in DBMS
A trigger is a procedure which is automatically invoked by the DBMS in response to changes to the database, and is specified by the database administrator (DBA). A database with a set of associated triggers is generally called an active database. A triggers description contains three parts, which are as follows − Event − An event is a change to the database which activates the trigger. Event − An event is a change to the database which activates the trigger. Condition − A query that is run when the trigger is activated is called as a condition. Condition − A query that is run when the trigger is activated is called as a condition. Action −A procedure which is executed when the trigger is activated and its condition is true. Action −A procedure which is executed when the trigger is activated and its condition is true. Triggers may be used for any of the following reasons − To implement any complex business rule, that cannot be implemented using integrity constraints. To implement any complex business rule, that cannot be implemented using integrity constraints. Triggers will be used to audit the process. For example, to keep track of changes made to a table. Triggers will be used to audit the process. For example, to keep track of changes made to a table. Trigger is used to perform automatic action when another concerned action takes place. Trigger is used to perform automatic action when another concerned action takes place. The different types of triggers are explained below − Statement level trigger − It is fired only once for DML statement irrespective of number of rows affected by statement. Statement-level triggers are the default type of trigger. Statement level trigger − It is fired only once for DML statement irrespective of number of rows affected by statement. Statement-level triggers are the default type of trigger. Before-triggers − At the time of defining a trigger we can specify whether the trigger is to be fired before a command like INSERT, DELETE, or UPDATE is executed or after the command is executed. Before triggers are automatically used to check the validity of data before the action is performed. For instance, we can use before trigger to prevent deletion of rows if deletion should not be allowed in a given case. Before-triggers − At the time of defining a trigger we can specify whether the trigger is to be fired before a command like INSERT, DELETE, or UPDATE is executed or after the command is executed. Before triggers are automatically used to check the validity of data before the action is performed. For instance, we can use before trigger to prevent deletion of rows if deletion should not be allowed in a given case. After-triggers − It is used after the triggering action is completed. For example, if the trigger is associated with the INSERT command then it is fired after the row is inserted into the table. After-triggers − It is used after the triggering action is completed. For example, if the trigger is associated with the INSERT command then it is fired after the row is inserted into the table. Row-level triggers − It is fired for each row that is affected by DML command. For example, if an UPDATE command updates 150 rows then a row-level trigger is fired 150 times whereas a statement-level trigger is fired only for once. Row-level triggers − It is fired for each row that is affected by DML command. For example, if an UPDATE command updates 150 rows then a row-level trigger is fired 150 times whereas a statement-level trigger is fired only for once. To create a database trigger, we use the CREATE TRIGGER command. The details to be given at the time of creating a trigger are as follows − Name of the trigger. Table to be associated with. When trigger is to be fired: before or after. Command that invokes the trigger- UPDATE, DELETE, or INSERT. Whether row-level triggers or not. Condition to filter rows. PL/SQL block is to be executed when trigger is fired. The syntax to create database trigger is as follows − CREATE [OR REPLACE] TRIGGER triggername {BEFORE|AFTER} {DELETE|INSERT|UPDATE[OF COLUMNS]} ON table [FOR EACH ROW {WHEN condition]] [REFERENCE [OLD AS old] [NEW AS new]] BEGIN PL/SQL BLOCK END.
[ { "code": null, "e": 1309, "s": 1062, "text": "A trigger is a procedure which is automatically invoked by the DBMS in response to changes to the database, and is specified by the database administrator (DBA). A database with a set of associated triggers is generally called an active database." }, { "code": null, "e": 1377, "s": 1309, "text": "A triggers description contains three parts, which are as follows −" }, { "code": null, "e": 1451, "s": 1377, "text": "Event − An event is a change to the database which activates the trigger." }, { "code": null, "e": 1525, "s": 1451, "text": "Event − An event is a change to the database which activates the trigger." }, { "code": null, "e": 1613, "s": 1525, "text": "Condition − A query that is run when the trigger is activated is called as a condition." }, { "code": null, "e": 1701, "s": 1613, "text": "Condition − A query that is run when the trigger is activated is called as a condition." }, { "code": null, "e": 1796, "s": 1701, "text": "Action −A procedure which is executed when the trigger is activated and its condition is true." }, { "code": null, "e": 1891, "s": 1796, "text": "Action −A procedure which is executed when the trigger is activated and its condition is true." }, { "code": null, "e": 1947, "s": 1891, "text": "Triggers may be used for any of the following reasons −" }, { "code": null, "e": 2043, "s": 1947, "text": "To implement any complex business rule, that cannot be implemented using integrity constraints." }, { "code": null, "e": 2139, "s": 2043, "text": "To implement any complex business rule, that cannot be implemented using integrity constraints." }, { "code": null, "e": 2238, "s": 2139, "text": "Triggers will be used to audit the process. For example, to keep track of changes made to a table." }, { "code": null, "e": 2337, "s": 2238, "text": "Triggers will be used to audit the process. For example, to keep track of changes made to a table." }, { "code": null, "e": 2424, "s": 2337, "text": "Trigger is used to perform automatic action when another concerned action takes place." }, { "code": null, "e": 2511, "s": 2424, "text": "Trigger is used to perform automatic action when another concerned action takes place." }, { "code": null, "e": 2565, "s": 2511, "text": "The different types of triggers are explained below −" }, { "code": null, "e": 2743, "s": 2565, "text": "Statement level trigger − It is fired only once for DML statement irrespective of number of rows affected by statement. Statement-level triggers are the default type of trigger." }, { "code": null, "e": 2921, "s": 2743, "text": "Statement level trigger − It is fired only once for DML statement irrespective of number of rows affected by statement. Statement-level triggers are the default type of trigger." }, { "code": null, "e": 3337, "s": 2921, "text": "Before-triggers − At the time of defining a trigger we can specify whether the trigger is to be fired before a command like INSERT, DELETE, or UPDATE is executed or after the command is executed. Before triggers are automatically used to check the validity of data before the action is performed. For instance, we can use before trigger to prevent deletion of rows if deletion should not be allowed in a given case." }, { "code": null, "e": 3753, "s": 3337, "text": "Before-triggers − At the time of defining a trigger we can specify whether the trigger is to be fired before a command like INSERT, DELETE, or UPDATE is executed or after the command is executed. Before triggers are automatically used to check the validity of data before the action is performed. For instance, we can use before trigger to prevent deletion of rows if deletion should not be allowed in a given case." }, { "code": null, "e": 3948, "s": 3753, "text": "After-triggers − It is used after the triggering action is completed. For example, if the trigger is associated with the INSERT command then it is fired after the row is inserted into the table." }, { "code": null, "e": 4143, "s": 3948, "text": "After-triggers − It is used after the triggering action is completed. For example, if the trigger is associated with the INSERT command then it is fired after the row is inserted into the table." }, { "code": null, "e": 4375, "s": 4143, "text": "Row-level triggers − It is fired for each row that is affected by DML command. For example, if an UPDATE command updates 150 rows then a row-level trigger is fired 150 times whereas a statement-level trigger is fired only for once." }, { "code": null, "e": 4607, "s": 4375, "text": "Row-level triggers − It is fired for each row that is affected by DML command. For example, if an UPDATE command updates 150 rows then a row-level trigger is fired 150 times whereas a statement-level trigger is fired only for once." }, { "code": null, "e": 4747, "s": 4607, "text": "To create a database trigger, we use the CREATE TRIGGER command. The details to be given at the time of creating a trigger are as follows −" }, { "code": null, "e": 4768, "s": 4747, "text": "Name of the trigger." }, { "code": null, "e": 4797, "s": 4768, "text": "Table to be associated with." }, { "code": null, "e": 4843, "s": 4797, "text": "When trigger is to be fired: before or after." }, { "code": null, "e": 4904, "s": 4843, "text": "Command that invokes the trigger- UPDATE, DELETE, or INSERT." }, { "code": null, "e": 4939, "s": 4904, "text": "Whether row-level triggers or not." }, { "code": null, "e": 4965, "s": 4939, "text": "Condition to filter rows." }, { "code": null, "e": 5019, "s": 4965, "text": "PL/SQL block is to be executed when trigger is fired." }, { "code": null, "e": 5073, "s": 5019, "text": "The syntax to create database trigger is as follows −" }, { "code": null, "e": 5266, "s": 5073, "text": "CREATE [OR REPLACE] TRIGGER triggername\n{BEFORE|AFTER}\n{DELETE|INSERT|UPDATE[OF COLUMNS]} ON table\n[FOR EACH ROW {WHEN condition]]\n[REFERENCE [OLD AS old] [NEW AS new]]\nBEGIN\nPL/SQL BLOCK\nEND." } ]
What are required arguments of a function in python?
Required arguments are the mandatory arguments of a function. These argument values must be passed in correct number and order during function call. If you run the given code you get the following output Hi 15 Traceback (most recent call last): File "requiredarg1.py", line 4, in <module> requiredArg('Hello') TypeError: requiredArg() takes exactly 2 arguments (1 given) EXPLANATION In the output above for the first function call with two required arguments we get the output as Hi 15. But for the second function call with only one argument, we get a TypeError saying the function takes exactly 2 arguments. This shows the importance of required arguments and their mandatory nature
[ { "code": null, "e": 1212, "s": 1062, "text": "Required arguments are the mandatory arguments of a function. These argument values must be passed in correct number and order during function call. " }, { "code": null, "e": 1267, "s": 1212, "text": "If you run the given code you get the following output" }, { "code": null, "e": 1440, "s": 1267, "text": "Hi 15\nTraceback (most recent call last):\n File \"requiredarg1.py\", line 4, in <module>\n requiredArg('Hello')\nTypeError: requiredArg() takes exactly 2 arguments (1 given)" }, { "code": null, "e": 1452, "s": 1440, "text": "EXPLANATION" }, { "code": null, "e": 1754, "s": 1452, "text": "In the output above for the first function call with two required arguments we get the output as Hi 15. But for the second function call with only one argument, we get a TypeError saying the function takes exactly 2 arguments. This shows the importance of required arguments and their mandatory nature" } ]
All combinations of sums for array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n as the second argument. The number n will always be less than or equal to the length of the array. Our function should return an array of the sum of all elements of all the possible subarrays of length n from the original array. For example, If the input is − const arr = [2, 6, 4]; const n = 2; Then the output should be − const output = [8, 10, 6]; The code for this will be − const arr = [2, 6, 4]; const n = 2; const buildCombinations = (arr, num) => { const res = []; let temp, i, j, max = 1 << arr.length; for(i = 0; i < max; i++){ temp = []; for(j = 0; j < arr.length; j++){ if (i & 1 << j){ temp.push(arr[j]); }; }; if(temp.length === num){ res.push(temp.reduce(function (a, b) { return a + b; })); }; }; return res; } console.log(buildCombinations(arr, n)); The output in the console − [ 8, 6, 10 ]
[ { "code": null, "e": 1284, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of Numbers as the first\nargument and a number, say n as the second argument. The number n will always be less than or equal to the length of the array." }, { "code": null, "e": 1414, "s": 1284, "text": "Our function should return an array of the sum of all elements of all the possible subarrays of length n from the original array." }, { "code": null, "e": 1445, "s": 1414, "text": "For example, If the input is −" }, { "code": null, "e": 1481, "s": 1445, "text": "const arr = [2, 6, 4];\nconst n = 2;" }, { "code": null, "e": 1509, "s": 1481, "text": "Then the output should be −" }, { "code": null, "e": 1536, "s": 1509, "text": "const output = [8, 10, 6];" }, { "code": null, "e": 1564, "s": 1536, "text": "The code for this will be −" }, { "code": null, "e": 2036, "s": 1564, "text": "const arr = [2, 6, 4];\nconst n = 2;\nconst buildCombinations = (arr, num) => {\n const res = [];\n let temp, i, j, max = 1 << arr.length;\n for(i = 0; i < max; i++){\n temp = [];\n for(j = 0; j < arr.length; j++){\n if (i & 1 << j){\n temp.push(arr[j]);\n };\n };\n if(temp.length === num){\n res.push(temp.reduce(function (a, b) { return a + b; }));\n };\n };\n return res;\n}\nconsole.log(buildCombinations(arr, n));" }, { "code": null, "e": 2064, "s": 2036, "text": "The output in the console −" }, { "code": null, "e": 2077, "s": 2064, "text": "[ 8, 6, 10 ]" } ]
Create your own Python package and publish it into PyPI | by Wendy Navarrete | Towards Data Science
I am assuming most of the people, who are reading this article, have already run the command below. But, what happens behind the scenes? pip install pandas At the moment you run the command pip install you are accessing the PyPI site to download a package. The site https://pypi.org/ is a repository of software for the Python programming language. As an example, I am going to use a couple of programs to be converted into a Python package. This code is an easy game able to “guess” the number into the player’s mind. You can see the code in my GitHub repository. Create a file named __init__.py and save it into the same folder your code is. This file tells Python that the folder contains a Python package. The code inside the __init__.py file gets run whenever you import a package inside a Python program. In this case, my __init__.py file is importing GuessMyNumber class from the numberGuesserGame module. Now, I have three files in my folder: Go up one level in the directory and create the setup.py file. This important file contains information about the package. Every time you run the command pip, it will automatically look for the setup.py file. It basically consists of a call to the setup function, which receives arguments to specify details of how the project is defined, for example, name, author, version, description, etc. After you completed steps 1 and 2, everything is ready to install your Python package locally. First, open a terminal and go to the folder containing your package and type the command below. The dot indicates to look for a setup.py file in the current folder and install the package in there. pip install . Now, you can stay in that folder or move to a different one to run Python and use your package. Let's see the example: Come back to the directory containing your package and create two more files: License.txt will tell users the terms and conditions under which they can use your package. I copied and pasted into my file the MIT license README.md will simply tell users what your package is about Your folder should look like the image below, your package, and 4 additional files: Once you have all the needed files, use the following command to install the latest version of the setuptools package (we used in the setup.py file). python -m pip install --user --upgrade setuptools Make sure you are at the same directory where setup.py is located and run this command: python setup.py sdist You will see there is a new folder dist containing the tar.gz file that provides metadata and the essential source files needed for installing by pip. You will also see a ProjectName.egg-info folder, it contains files and metadata needed to be moved to a specific location on a target system. Don’t worry about it, you can ignore it, remove it or learn more about it here. Go to PyPI test and PyPI sites and create your accounts, it’s important to remember your passwords, those will be retyped into the command line very soon. The next step is to install twine, this utility will help you to upload your package to the PyPI repository or other repositories. Once you have installed twine, you won’t need to repeat this step. pip install twine Open a terminal and type the command below in your command line, it will ask you to provide the user and password you created previously on step 6. twine upload --repository-url https://test.pypi.org/legacy/ dist/* Login to the Test PyPI repository and verify that your package is in there. If so, copy the command that is under the package’s name, run it in your command line and, read in your screen the message saying that your package was successfully installed. pip install -i https://test.pypi.org/simple/ guesser-game Finally, this is the last command you have to run to share your package with the worldwide community of Python developers. Make sure you are at the same directory where the setup.py file is located. twine upload dist/* Now, the package is in the PyPI repository! It is important to know how to upload your Python package but in my opinion, it is equal or more important to be willing to share your knowledge, collaborate with the community, create a learning culture and find different ways to do things. For more reference material, you can review packaging.python.org.
[ { "code": null, "e": 309, "s": 172, "text": "I am assuming most of the people, who are reading this article, have already run the command below. But, what happens behind the scenes?" }, { "code": null, "e": 328, "s": 309, "text": "pip install pandas" }, { "code": null, "e": 521, "s": 328, "text": "At the moment you run the command pip install you are accessing the PyPI site to download a package. The site https://pypi.org/ is a repository of software for the Python programming language." }, { "code": null, "e": 737, "s": 521, "text": "As an example, I am going to use a couple of programs to be converted into a Python package. This code is an easy game able to “guess” the number into the player’s mind. You can see the code in my GitHub repository." }, { "code": null, "e": 1085, "s": 737, "text": "Create a file named __init__.py and save it into the same folder your code is. This file tells Python that the folder contains a Python package. The code inside the __init__.py file gets run whenever you import a package inside a Python program. In this case, my __init__.py file is importing GuessMyNumber class from the numberGuesserGame module." }, { "code": null, "e": 1123, "s": 1085, "text": "Now, I have three files in my folder:" }, { "code": null, "e": 1186, "s": 1123, "text": "Go up one level in the directory and create the setup.py file." }, { "code": null, "e": 1332, "s": 1186, "text": "This important file contains information about the package. Every time you run the command pip, it will automatically look for the setup.py file." }, { "code": null, "e": 1516, "s": 1332, "text": "It basically consists of a call to the setup function, which receives arguments to specify details of how the project is defined, for example, name, author, version, description, etc." }, { "code": null, "e": 1809, "s": 1516, "text": "After you completed steps 1 and 2, everything is ready to install your Python package locally. First, open a terminal and go to the folder containing your package and type the command below. The dot indicates to look for a setup.py file in the current folder and install the package in there." }, { "code": null, "e": 1823, "s": 1809, "text": "pip install ." }, { "code": null, "e": 1942, "s": 1823, "text": "Now, you can stay in that folder or move to a different one to run Python and use your package. Let's see the example:" }, { "code": null, "e": 2020, "s": 1942, "text": "Come back to the directory containing your package and create two more files:" }, { "code": null, "e": 2161, "s": 2020, "text": "License.txt will tell users the terms and conditions under which they can use your package. I copied and pasted into my file the MIT license" }, { "code": null, "e": 2221, "s": 2161, "text": "README.md will simply tell users what your package is about" }, { "code": null, "e": 2305, "s": 2221, "text": "Your folder should look like the image below, your package, and 4 additional files:" }, { "code": null, "e": 2455, "s": 2305, "text": "Once you have all the needed files, use the following command to install the latest version of the setuptools package (we used in the setup.py file)." }, { "code": null, "e": 2505, "s": 2455, "text": "python -m pip install --user --upgrade setuptools" }, { "code": null, "e": 2593, "s": 2505, "text": "Make sure you are at the same directory where setup.py is located and run this command:" }, { "code": null, "e": 2615, "s": 2593, "text": "python setup.py sdist" }, { "code": null, "e": 2766, "s": 2615, "text": "You will see there is a new folder dist containing the tar.gz file that provides metadata and the essential source files needed for installing by pip." }, { "code": null, "e": 2988, "s": 2766, "text": "You will also see a ProjectName.egg-info folder, it contains files and metadata needed to be moved to a specific location on a target system. Don’t worry about it, you can ignore it, remove it or learn more about it here." }, { "code": null, "e": 3143, "s": 2988, "text": "Go to PyPI test and PyPI sites and create your accounts, it’s important to remember your passwords, those will be retyped into the command line very soon." }, { "code": null, "e": 3341, "s": 3143, "text": "The next step is to install twine, this utility will help you to upload your package to the PyPI repository or other repositories. Once you have installed twine, you won’t need to repeat this step." }, { "code": null, "e": 3359, "s": 3341, "text": "pip install twine" }, { "code": null, "e": 3507, "s": 3359, "text": "Open a terminal and type the command below in your command line, it will ask you to provide the user and password you created previously on step 6." }, { "code": null, "e": 3574, "s": 3507, "text": "twine upload --repository-url https://test.pypi.org/legacy/ dist/*" }, { "code": null, "e": 3826, "s": 3574, "text": "Login to the Test PyPI repository and verify that your package is in there. If so, copy the command that is under the package’s name, run it in your command line and, read in your screen the message saying that your package was successfully installed." }, { "code": null, "e": 3884, "s": 3826, "text": "pip install -i https://test.pypi.org/simple/ guesser-game" }, { "code": null, "e": 4083, "s": 3884, "text": "Finally, this is the last command you have to run to share your package with the worldwide community of Python developers. Make sure you are at the same directory where the setup.py file is located." }, { "code": null, "e": 4103, "s": 4083, "text": "twine upload dist/*" }, { "code": null, "e": 4147, "s": 4103, "text": "Now, the package is in the PyPI repository!" }, { "code": null, "e": 4389, "s": 4147, "text": "It is important to know how to upload your Python package but in my opinion, it is equal or more important to be willing to share your knowledge, collaborate with the community, create a learning culture and find different ways to do things." } ]
Python Keywords - GeeksforGeeks
12 Oct, 2021 Python Keywords: Introduction Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier. We can also get all the keyword names using the below code. Python3 # Python code to demonstrate working of iskeyword() # importing "keyword" for keyword operationsimport keyword # printing all keywords at once using "kwlist()"print("The list of keywords is : ")print(keyword.kwlist) Output: The list of keywords is : [‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’] Let’s discuss each keyword in detail with the help of good examples. True: This keyword is used to represent a boolean true. If a statement is true, “True” is printed. False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed. None: This is a special constant used to denote a null value or a void. It’s important to remember, 0, any empty container(e.g empty list) does not compute to None. It is an object of its datatype – NoneType. It is not possible to create multiple None objects and can assign them to variables. Python3 print(False == 0)print(True == 1) print(True + True + True)print(True + False + False) print(None == 0)print(None == []) True True 3 1 False False and: This a logical operator in python. “and” Return the first false value. If not found return last. The truth table for “and” is depicted below. 3 and 0 returns 0 3 and 10 returns 10 10 or 20 or 30 or 10 or 70 returns 10 The above statements might be a bit confusing to a programmer coming from a language like C where the logical operators always return boolean values(0 or 1). Following lines are straight from the python docs explaining this: The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not ‘foo’ produces False rather than ”.) or: This a logical operator in python. “or” Return the first True value.if not found return last. The truth table for “or” is depicted below. 3 or 0 returns 3 3 or 10 returns 3 0 or 0 or 3 or 10 or 0 returns 3 not: This logical operator inverts the truth value. The truth table for “not” is depicted below. in: This keyword is used to check if a container contains a value. This keyword is also used to loop through the container. is: This keyword is used to test object identity, i.e to check if both the objects take the same memory location or not. Python # showing logical operation# or (returns True)print(True or False) # showing logical operation# and (returns False)print(False and True) # showing logical operation# not (returns False)print(not True) # using "in" to checkif 's' in 'geeksforgeeks': print("s is part of geeksforgeeks")else: print("s is not part of geeksforgeeks") # using "in" to loop throughfor i in 'geeksforgeeks': print(i, end=" ") print("\r") # using is to check object identity# string is immutable( cannot be changed once allocated)# hence occupy same memory locationprint(' ' is ' ') # using is to check object identity# dictionary is mutable( can be changed once allocated)# hence occupy different memory locationprint({} is {}) Output: True False False s is part of geeksforgeeks g e e k s f o r g e e k s True False for: This keyword is used to control flow and for looping. while: Has a similar working like “for”, used to control flow and for looping. break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to the statement following immediately after loop. continue: “continue” is also used to control the flow of code. The keyword skips the current iteration of the loop but does not end the loop. Python3 # Using for loopfor i in range(10): print(i, end = " ") # break the loop as soon it sees 6 if i == 6: break print() # loop from 1 to 10i = 0while i <10: # If i is equals to 6, # continue to next iteration # without printing if i == 6: i+= 1 continue else: # otherwise print the value # of i print(i, end = " ") i += 1 0 1 2 3 4 5 6 0 1 2 3 4 5 7 8 9 if : It is a control statement for decision making. Truth expression forces control to go in “if” statement block. else : It is a control statement for decision making. False expression forces control to go in “else” statement block. elif : It is a control statement for decision making. It is short for “else if“ Python3 # Python program to illustrate if-elif-else ladder#!/usr/bin/python i = 20if (i == 10): print ("i is 10")elif (i == 20): print ("i is 20")else: print ("i is not present") i is 20 Note: For more information, refer to out Python if else Tutorial. def keyword is used to declare user defined functions. Python3 # def keyworddef fun(): print("Inside Function") fun() Inside Function return : This keyword is used to return from the function. yield : This keyword is used like return statement but is used to return a generator. Python3 # Return keyworddef fun(): S = 0 for i in range(10): S += i return S print(fun()) # Yield Keyworddef fun(): S = 0 for i in range(10): S += i yield S for i in fun(): print(i) 45 0 1 3 6 10 15 21 28 36 45 class keyword is used to declare user defined classes. Python3 # Python3 program to# demonstrate instantiating# a class class Dog: # A simple class # attribute attr1 = "mammal" attr2 = "dog" # A sample method def fun(self): print("I'm a", self.attr1) print("I'm a", self.attr2) # Driver code# Object instantiationRodger = Dog() # Accessing class attributes# and method through objectsprint(Rodger.attr1)Rodger.fun() mammal I'm a mammal I'm a dog Note: For more information, refer to our Python Classes and Objects Tutorial . with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming. Python3 # using with statementwith open('file_path', 'w') as file: file.write('hello world !') as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath. Python3 import math as gfg print(gfg.factorial(5)) 120 pass is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and used as a placeholder. Python3 n = 10for i in range(n): # pass can be used as placeholder# when code is to added laterpass Lambda keyword is used to make inline returning functions with no statements allowed internally. Python3 # Lambda keywordg = lambda x: x*x*x print(g(7)) 343 import : This statement is used to include a particular module into current program. from : Generally used with import, from is used to import particular functionality from the module imported. Python3 # import keywordimport mathprint(math.factorial(10)) # from keywordfrom math import factorialprint(factorial(10)) 3628800 3628800 try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in “try” block is checked, if there is any type of error, except block is executed. except : As explained above, this works together with “try” to catch exceptions. finally : No matter what is result of the “try” block, block termed “finally” is always executed. raise: We can raise an exception explicitly with the raise keyword assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to be true, nothing happens, but when it is false, “AssertionError” is raised. One can also print a message with the error, separated by a comma. Python3 # initializing numbera = 4b = 0 # No exception Exception raised in try blocktry: k = a//b # raises divide by zero exception. print(k) # handles zerodivision exceptionexcept ZeroDivisionError: print("Can't divide by zero") finally: # this block is always executed # regardless of exception generation. print('This is always executed') # assert Keyword # using assert to check for 0print ("The value of a / b is : ")assert b != 0, "Divide by 0 error"print (a / b) Output Can't divide by zero This is always executed The value of a / b is : AssertionError: Divide by 0 error Note: For more information refer to our tutorial Exception Handling Tutorial in Python. del is used to delete a reference to an object. Any variable or list value can be deleted using del. Python3 my_variable1 = 20my_variable2 = "GeeksForGeeks" # check if my_variable1 and my_variable2 existsprint(my_variable1)print(my_variable2) # delete both the variablesdel my_variable1del my_variable2 # check if my_variable1 and my_variable2 existsprint(my_variable1)print(my_variable2) Output 20 GeeksForGeeks NameError: name 'my_variable1' is not defined global: This keyword is used to define a variable inside the function to be of a global scope. non-local : This keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable of outside enclosing function, in case of nested functions. Python3 # global variablea = 15b = 10 # function to perform additiondef add(): c = a + b print(c) # calling a functionadd() # nonlocal keyworddef fun(): var1 = 10 def gun(): # tell python explicitly that it # has to access var1 initialized # in fun on line 2 # using the keyword nonlocal nonlocal var1 var1 = var1 + 10 print(var1) gun()fun() 25 20 Note: For more information, refer to our Global and local variables tutorial in Python. This article is contributed by Manjeet Singh(S. Nandini). 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. VamsiKrishnaMeda raviteja jammulapati pradeepyrl alifyakhan nikhilaggarwal3 kumaripunam984122 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 41658, "s": 41630, "text": "\n12 Oct, 2021" }, { "code": null, "e": 41688, "s": 41658, "text": "Python Keywords: Introduction" }, { "code": null, "e": 41807, "s": 41688, "text": "Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier." }, { "code": null, "e": 41867, "s": 41807, "text": "We can also get all the keyword names using the below code." }, { "code": null, "e": 41875, "s": 41867, "text": "Python3" }, { "code": "# Python code to demonstrate working of iskeyword() # importing \"keyword\" for keyword operationsimport keyword # printing all keywords at once using \"kwlist()\"print(\"The list of keywords is : \")print(keyword.kwlist)", "e": 42093, "s": 41875, "text": null }, { "code": null, "e": 42101, "s": 42093, "text": "Output:" }, { "code": null, "e": 42128, "s": 42101, "text": "The list of keywords is : " }, { "code": null, "e": 42424, "s": 42128, "text": "[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]" }, { "code": null, "e": 42493, "s": 42424, "text": "Let’s discuss each keyword in detail with the help of good examples." }, { "code": null, "e": 42592, "s": 42493, "text": "True: This keyword is used to represent a boolean true. If a statement is true, “True” is printed." }, { "code": null, "e": 42696, "s": 42592, "text": "False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed. " }, { "code": null, "e": 42990, "s": 42696, "text": "None: This is a special constant used to denote a null value or a void. It’s important to remember, 0, any empty container(e.g empty list) does not compute to None. It is an object of its datatype – NoneType. It is not possible to create multiple None objects and can assign them to variables." }, { "code": null, "e": 42998, "s": 42990, "text": "Python3" }, { "code": "print(False == 0)print(True == 1) print(True + True + True)print(True + False + False) print(None == 0)print(None == [])", "e": 43121, "s": 42998, "text": null }, { "code": null, "e": 43148, "s": 43121, "text": "True\nTrue\n3\n1\nFalse\nFalse\n" }, { "code": null, "e": 43296, "s": 43148, "text": "and: This a logical operator in python. “and” Return the first false value. If not found return last. The truth table for “and” is depicted below. " }, { "code": null, "e": 43315, "s": 43296, "text": "3 and 0 returns 0 " }, { "code": null, "e": 43336, "s": 43315, "text": "3 and 10 returns 10 " }, { "code": null, "e": 43375, "s": 43336, "text": "10 or 20 or 30 or 10 or 70 returns 10 " }, { "code": null, "e": 43600, "s": 43375, "text": "The above statements might be a bit confusing to a programmer coming from a language like C where the logical operators always return boolean values(0 or 1). Following lines are straight from the python docs explaining this:" }, { "code": null, "e": 43743, "s": 43600, "text": "The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned." }, { "code": null, "e": 43884, "s": 43743, "text": "The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned." }, { "code": null, "e": 44339, "s": 43884, "text": "Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not ‘foo’ produces False rather than ”.)" }, { "code": null, "e": 44483, "s": 44339, "text": "or: This a logical operator in python. “or” Return the first True value.if not found return last. The truth table for “or” is depicted below. " }, { "code": null, "e": 44501, "s": 44483, "text": "3 or 0 returns 3 " }, { "code": null, "e": 44520, "s": 44501, "text": "3 or 10 returns 3 " }, { "code": null, "e": 44554, "s": 44520, "text": "0 or 0 or 3 or 10 or 0 returns 3 " }, { "code": null, "e": 44652, "s": 44554, "text": "not: This logical operator inverts the truth value. The truth table for “not” is depicted below. " }, { "code": null, "e": 44776, "s": 44652, "text": "in: This keyword is used to check if a container contains a value. This keyword is also used to loop through the container." }, { "code": null, "e": 44898, "s": 44776, "text": "is: This keyword is used to test object identity, i.e to check if both the objects take the same memory location or not. " }, { "code": null, "e": 44905, "s": 44898, "text": "Python" }, { "code": "# showing logical operation# or (returns True)print(True or False) # showing logical operation# and (returns False)print(False and True) # showing logical operation# not (returns False)print(not True) # using \"in\" to checkif 's' in 'geeksforgeeks': print(\"s is part of geeksforgeeks\")else: print(\"s is not part of geeksforgeeks\") # using \"in\" to loop throughfor i in 'geeksforgeeks': print(i, end=\" \") print(\"\\r\") # using is to check object identity# string is immutable( cannot be changed once allocated)# hence occupy same memory locationprint(' ' is ' ') # using is to check object identity# dictionary is mutable( can be changed once allocated)# hence occupy different memory locationprint({} is {})", "e": 45625, "s": 44905, "text": null }, { "code": null, "e": 45634, "s": 45625, "text": "Output: " }, { "code": null, "e": 45716, "s": 45634, "text": "True\nFalse\nFalse\ns is part of geeksforgeeks\ng e e k s f o r g e e k s \nTrue\nFalse" }, { "code": null, "e": 45775, "s": 45716, "text": "for: This keyword is used to control flow and for looping." }, { "code": null, "e": 45854, "s": 45775, "text": "while: Has a similar working like “for”, used to control flow and for looping." }, { "code": null, "e": 46031, "s": 45854, "text": "break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to the statement following immediately after loop." }, { "code": null, "e": 46173, "s": 46031, "text": "continue: “continue” is also used to control the flow of code. The keyword skips the current iteration of the loop but does not end the loop." }, { "code": null, "e": 46181, "s": 46173, "text": "Python3" }, { "code": "# Using for loopfor i in range(10): print(i, end = \" \") # break the loop as soon it sees 6 if i == 6: break print() # loop from 1 to 10i = 0while i <10: # If i is equals to 6, # continue to next iteration # without printing if i == 6: i+= 1 continue else: # otherwise print the value # of i print(i, end = \" \") i += 1", "e": 46602, "s": 46181, "text": null }, { "code": null, "e": 46636, "s": 46602, "text": "0 1 2 3 4 5 6 \n0 1 2 3 4 5 7 8 9 " }, { "code": null, "e": 46751, "s": 46636, "text": "if : It is a control statement for decision making. Truth expression forces control to go in “if” statement block." }, { "code": null, "e": 46870, "s": 46751, "text": "else : It is a control statement for decision making. False expression forces control to go in “else” statement block." }, { "code": null, "e": 46950, "s": 46870, "text": "elif : It is a control statement for decision making. It is short for “else if“" }, { "code": null, "e": 46958, "s": 46950, "text": "Python3" }, { "code": "# Python program to illustrate if-elif-else ladder#!/usr/bin/python i = 20if (i == 10): print (\"i is 10\")elif (i == 20): print (\"i is 20\")else: print (\"i is not present\")", "e": 47139, "s": 46958, "text": null }, { "code": null, "e": 47148, "s": 47139, "text": "i is 20\n" }, { "code": null, "e": 47214, "s": 47148, "text": "Note: For more information, refer to out Python if else Tutorial." }, { "code": null, "e": 47269, "s": 47214, "text": "def keyword is used to declare user defined functions." }, { "code": null, "e": 47277, "s": 47269, "text": "Python3" }, { "code": "# def keyworddef fun(): print(\"Inside Function\") fun()", "e": 47340, "s": 47277, "text": null }, { "code": null, "e": 47357, "s": 47340, "text": "Inside Function\n" }, { "code": null, "e": 47416, "s": 47357, "text": "return : This keyword is used to return from the function." }, { "code": null, "e": 47502, "s": 47416, "text": "yield : This keyword is used like return statement but is used to return a generator." }, { "code": null, "e": 47510, "s": 47502, "text": "Python3" }, { "code": "# Return keyworddef fun(): S = 0 for i in range(10): S += i return S print(fun()) # Yield Keyworddef fun(): S = 0 for i in range(10): S += i yield S for i in fun(): print(i)", "e": 47738, "s": 47510, "text": null }, { "code": null, "e": 47768, "s": 47738, "text": "45\n0\n1\n3\n6\n10\n15\n21\n28\n36\n45\n" }, { "code": null, "e": 47823, "s": 47768, "text": "class keyword is used to declare user defined classes." }, { "code": null, "e": 47831, "s": 47823, "text": "Python3" }, { "code": "# Python3 program to# demonstrate instantiating# a class class Dog: # A simple class # attribute attr1 = \"mammal\" attr2 = \"dog\" # A sample method def fun(self): print(\"I'm a\", self.attr1) print(\"I'm a\", self.attr2) # Driver code# Object instantiationRodger = Dog() # Accessing class attributes# and method through objectsprint(Rodger.attr1)Rodger.fun()", "e": 48229, "s": 47831, "text": null }, { "code": null, "e": 48260, "s": 48229, "text": "mammal\nI'm a mammal\nI'm a dog\n" }, { "code": null, "e": 48339, "s": 48260, "text": "Note: For more information, refer to our Python Classes and Objects Tutorial ." }, { "code": null, "e": 48499, "s": 48339, "text": "with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming." }, { "code": null, "e": 48507, "s": 48499, "text": "Python3" }, { "code": "# using with statementwith open('file_path', 'w') as file: file.write('hello world !')", "e": 48597, "s": 48507, "text": null }, { "code": null, "e": 48734, "s": 48597, "text": "as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath." }, { "code": null, "e": 48742, "s": 48734, "text": "Python3" }, { "code": "import math as gfg print(gfg.factorial(5))", "e": 48786, "s": 48742, "text": null }, { "code": null, "e": 48791, "s": 48786, "text": "120\n" }, { "code": null, "e": 48941, "s": 48791, "text": "pass is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and used as a placeholder." }, { "code": null, "e": 48949, "s": 48941, "text": "Python3" }, { "code": "n = 10for i in range(n): # pass can be used as placeholder# when code is to added laterpass", "e": 49046, "s": 48949, "text": null }, { "code": null, "e": 49144, "s": 49046, "text": "Lambda keyword is used to make inline returning functions with no statements allowed internally. " }, { "code": null, "e": 49152, "s": 49144, "text": "Python3" }, { "code": "# Lambda keywordg = lambda x: x*x*x print(g(7))", "e": 49201, "s": 49152, "text": null }, { "code": null, "e": 49206, "s": 49201, "text": "343\n" }, { "code": null, "e": 49291, "s": 49206, "text": "import : This statement is used to include a particular module into current program." }, { "code": null, "e": 49400, "s": 49291, "text": "from : Generally used with import, from is used to import particular functionality from the module imported." }, { "code": null, "e": 49408, "s": 49400, "text": "Python3" }, { "code": "# import keywordimport mathprint(math.factorial(10)) # from keywordfrom math import factorialprint(factorial(10))", "e": 49523, "s": 49408, "text": null }, { "code": null, "e": 49540, "s": 49523, "text": "3628800\n3628800\n" }, { "code": null, "e": 49743, "s": 49540, "text": "try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in “try” block is checked, if there is any type of error, except block is executed." }, { "code": null, "e": 49824, "s": 49743, "text": "except : As explained above, this works together with “try” to catch exceptions." }, { "code": null, "e": 49922, "s": 49824, "text": "finally : No matter what is result of the “try” block, block termed “finally” is always executed." }, { "code": null, "e": 49989, "s": 49922, "text": "raise: We can raise an exception explicitly with the raise keyword" }, { "code": null, "e": 50264, "s": 49989, "text": "assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to be true, nothing happens, but when it is false, “AssertionError” is raised. One can also print a message with the error, separated by a comma." }, { "code": null, "e": 50272, "s": 50264, "text": "Python3" }, { "code": "# initializing numbera = 4b = 0 # No exception Exception raised in try blocktry: k = a//b # raises divide by zero exception. print(k) # handles zerodivision exceptionexcept ZeroDivisionError: print(\"Can't divide by zero\") finally: # this block is always executed # regardless of exception generation. print('This is always executed') # assert Keyword # using assert to check for 0print (\"The value of a / b is : \")assert b != 0, \"Divide by 0 error\"print (a / b)", "e": 50757, "s": 50272, "text": null }, { "code": null, "e": 50764, "s": 50757, "text": "Output" }, { "code": null, "e": 50867, "s": 50764, "text": "Can't divide by zero\nThis is always executed\nThe value of a / b is :\nAssertionError: Divide by 0 error" }, { "code": null, "e": 50955, "s": 50867, "text": "Note: For more information refer to our tutorial Exception Handling Tutorial in Python." }, { "code": null, "e": 51056, "s": 50955, "text": "del is used to delete a reference to an object. Any variable or list value can be deleted using del." }, { "code": null, "e": 51064, "s": 51056, "text": "Python3" }, { "code": "my_variable1 = 20my_variable2 = \"GeeksForGeeks\" # check if my_variable1 and my_variable2 existsprint(my_variable1)print(my_variable2) # delete both the variablesdel my_variable1del my_variable2 # check if my_variable1 and my_variable2 existsprint(my_variable1)print(my_variable2)", "e": 51347, "s": 51064, "text": null }, { "code": null, "e": 51354, "s": 51347, "text": "Output" }, { "code": null, "e": 51417, "s": 51354, "text": "20\nGeeksForGeeks\nNameError: name 'my_variable1' is not defined" }, { "code": null, "e": 51512, "s": 51417, "text": "global: This keyword is used to define a variable inside the function to be of a global scope." }, { "code": null, "e": 51704, "s": 51512, "text": "non-local : This keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable of outside enclosing function, in case of nested functions." }, { "code": null, "e": 51712, "s": 51704, "text": "Python3" }, { "code": "# global variablea = 15b = 10 # function to perform additiondef add(): c = a + b print(c) # calling a functionadd() # nonlocal keyworddef fun(): var1 = 10 def gun(): # tell python explicitly that it # has to access var1 initialized # in fun on line 2 # using the keyword nonlocal nonlocal var1 var1 = var1 + 10 print(var1) gun()fun()", "e": 52127, "s": 51712, "text": null }, { "code": null, "e": 52134, "s": 52127, "text": "25\n20\n" }, { "code": null, "e": 52222, "s": 52134, "text": "Note: For more information, refer to our Global and local variables tutorial in Python." }, { "code": null, "e": 52655, "s": 52222, "text": "This article is contributed by Manjeet Singh(S. Nandini). 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": 52672, "s": 52655, "text": "VamsiKrishnaMeda" }, { "code": null, "e": 52693, "s": 52672, "text": "raviteja jammulapati" }, { "code": null, "e": 52704, "s": 52693, "text": "pradeepyrl" }, { "code": null, "e": 52715, "s": 52704, "text": "alifyakhan" }, { "code": null, "e": 52731, "s": 52715, "text": "nikhilaggarwal3" }, { "code": null, "e": 52749, "s": 52731, "text": "kumaripunam984122" }, { "code": null, "e": 52756, "s": 52749, "text": "Python" }, { "code": null, "e": 52854, "s": 52756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52882, "s": 52854, "text": "Read JSON file using Python" }, { "code": null, "e": 52932, "s": 52882, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 52954, "s": 52932, "text": "Python map() function" }, { "code": null, "e": 52998, "s": 52954, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 53033, "s": 52998, "text": "Read a file line by line in Python" }, { "code": null, "e": 53065, "s": 53033, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 53087, "s": 53065, "text": "Enumerate() in Python" }, { "code": null, "e": 53129, "s": 53087, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 53159, "s": 53129, "text": "Iterate over a list in Python" } ]
Calculate the absolute value in R programming - abs() method - GeeksforGeeks
10 May, 2020 abs() method in R programming is used to get the absolute value that is positive value doesn’t change and negative value converted into positive value. Syntax: abs(value) Return: Returns the absolute value. Example 1: # R program to calculate absolute value # Using abs() methodanswer1 <- abs(-12)answer2 <- abs(21)answer3 <- abs(-2) print(answer1)print(answer2)print(answer3) Output: [1] 12 [2] 21 [3] 2 Example 2: # R program to calculate absolute value # Using abs() methodanswer1 <- abs(c(1, 2, 3, 4))answer2 <- abs(c(1, -2, 3, -4)) print(answer1)print(answer2) Output: [1] 1 2 3 4 [2] 1 2 3 4 R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? R Programming Language - Introduction K-Means Clustering in R Programming Replace Specific Characters in String in R
[ { "code": null, "e": 26205, "s": 26177, "text": "\n10 May, 2020" }, { "code": null, "e": 26357, "s": 26205, "text": "abs() method in R programming is used to get the absolute value that is positive value doesn’t change and negative value converted into positive value." }, { "code": null, "e": 26376, "s": 26357, "text": "Syntax: abs(value)" }, { "code": null, "e": 26412, "s": 26376, "text": "Return: Returns the absolute value." }, { "code": null, "e": 26423, "s": 26412, "text": "Example 1:" }, { "code": "# R program to calculate absolute value # Using abs() methodanswer1 <- abs(-12)answer2 <- abs(21)answer3 <- abs(-2) print(answer1)print(answer2)print(answer3)", "e": 26584, "s": 26423, "text": null }, { "code": null, "e": 26592, "s": 26584, "text": "Output:" }, { "code": null, "e": 26613, "s": 26592, "text": "[1] 12\n[2] 21\n[3] 2\n" }, { "code": null, "e": 26624, "s": 26613, "text": "Example 2:" }, { "code": "# R program to calculate absolute value # Using abs() methodanswer1 <- abs(c(1, 2, 3, 4))answer2 <- abs(c(1, -2, 3, -4)) print(answer1)print(answer2)", "e": 26776, "s": 26624, "text": null }, { "code": null, "e": 26784, "s": 26776, "text": "Output:" }, { "code": null, "e": 26809, "s": 26784, "text": "[1] 1 2 3 4\n[2] 1 2 3 4\n" }, { "code": null, "e": 26820, "s": 26809, "text": "R Language" }, { "code": null, "e": 26918, "s": 26820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26970, "s": 26918, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27002, "s": 26970, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27046, "s": 27002, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27098, "s": 27046, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27133, "s": 27098, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27171, "s": 27133, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27229, "s": 27171, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27267, "s": 27229, "text": "R Programming Language - Introduction" }, { "code": null, "e": 27303, "s": 27267, "text": "K-Means Clustering in R Programming" } ]
How to create warning notification alerts in Bootstrap ? - GeeksforGeeks
24 Aug, 2021 Before or after performing an action, we frequently encounter specific notifications on some websites. These alert messages are highlighted text that should be taken into account when executing a task. Using preset classes in Bootstrap, these alert messages can be displayed on the website. Approach: The .alert class followed by contextual classes are used to display the alert message on website. The alert classes are: .alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light and .alert-dark. We can use .alert-warning to create warning notification alerts in bootstrap. Below is the procedure to implement a simple warning alert in Bootstrap. Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> Step 2: Add the .alert and the warning alert contextual classes (e.g., .alert-warning). <div class="alert alert-warning" role="alert"> A simple warning alert—check it out! </div> Example 1: In this example, we will see types of alerts in bootstrap. Users can use any type of warning alert. index.html <!DOCTYPE html><html> <head> <title>Warning Alerts</title> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"> </script> </head> <body> <div class="container py-5"> <h4 class="text-center text-uppercase"> GeeksForGeeks Bootstrap 5 warning messages </h4> <h6>Basic Warning alert</h6> <div class="alert alert-warning"> <strong>Warning!</strong> There was a problem with connection. </div> <h6>Warning alert with link</h6> <div class="alert alert-warning"> <strong>Warning!</strong> There was a problem with wifi connection<a href="#" class="alert-link"> Contact us</a>. </div> <h6>Warning alert with close button</h6> <div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert"> × </button> <strong>Warning!</strong> There was a problem with wifi connection. </div> <h6>Warning alert with close button and fade animation</h6> <div class="alert alert-warning alert-dismissible fade show"> <button type="button" class="close" data-dismiss="alert"> × </button> <strong>Warning!</strong> There was a problem with internet connection. </div> <h6>Warning alert with heading</h6> <div class="alert alert-warning alert-dismissible fade show"> <button type="button" class="close" data-dismiss="alert"> × </button> <h5 class="alert-heading">Warning!</h5> Wrong credentials. </div> </div> </body></html> Output: Warning Alert Types in Bootstrap Example 2: In this example, we will use the warning alerts using the button click. When the user clicks the button, a warning alert will be generated. index.html <!DOCTYPE html><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Buttons and alerts</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/js/bootstrap-alert.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { $('#success').click(function (e) { e.preventDefault() $('#message').html(` <div class="alert alert-success fade in"> <button type="button class="close close-alert" data-dismiss="alert" aria-hidden="true"> × </button>This is a success message </div>`); }) $('#warning').click(function (e) { e.preventDefault() $('#message').html(` <div class="alert alert-warning fade in"> <button type="button" class="close close-alert" data-dismiss="alert" aria-hidden="true"> × </button> This is a warning message </div>`); }); }); </script></head> <body> <div class="container"> <h2>GeeksForGeeks</h2> <p class="lead"> Warning Alert message using bootstrap </p> <p> <form method="post"> <button type="button" class="btn btn-success" id="success"> Success </button> <button type="button" class="btn btn-warning" id="warning"> Warning </button> </form> </p> <div id="message"></div> </div></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. Bootstrap-Questions HTML-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25562, "s": 25534, "text": "\n24 Aug, 2021" }, { "code": null, "e": 25853, "s": 25562, "text": "Before or after performing an action, we frequently encounter specific notifications on some websites. These alert messages are highlighted text that should be taken into account when executing a task. Using preset classes in Bootstrap, these alert messages can be displayed on the website." }, { "code": null, "e": 26186, "s": 25853, "text": "Approach: The .alert class followed by contextual classes are used to display the alert message on website. The alert classes are: .alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light and .alert-dark. We can use .alert-warning to create warning notification alerts in bootstrap." }, { "code": null, "e": 26259, "s": 26186, "text": "Below is the procedure to implement a simple warning alert in Bootstrap." }, { "code": null, "e": 26366, "s": 26259, "text": "Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 26745, "s": 26368, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>" }, { "code": null, "e": 26833, "s": 26745, "text": "Step 2: Add the .alert and the warning alert contextual classes (e.g., .alert-warning)." }, { "code": null, "e": 26926, "s": 26833, "text": "<div class=\"alert alert-warning\" role=\"alert\">\n A simple warning alert—check it out!\n</div>" }, { "code": null, "e": 27037, "s": 26926, "text": "Example 1: In this example, we will see types of alerts in bootstrap. Users can use any type of warning alert." }, { "code": null, "e": 27048, "s": 27037, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <head> <title>Warning Alerts</title> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container py-5\"> <h4 class=\"text-center text-uppercase\"> GeeksForGeeks Bootstrap 5 warning messages </h4> <h6>Basic Warning alert</h6> <div class=\"alert alert-warning\"> <strong>Warning!</strong> There was a problem with connection. </div> <h6>Warning alert with link</h6> <div class=\"alert alert-warning\"> <strong>Warning!</strong> There was a problem with wifi connection<a href=\"#\" class=\"alert-link\"> Contact us</a>. </div> <h6>Warning alert with close button</h6> <div class=\"alert alert-warning\"> <button type=\"button\" class=\"close\" data-dismiss=\"alert\"> × </button> <strong>Warning!</strong> There was a problem with wifi connection. </div> <h6>Warning alert with close button and fade animation</h6> <div class=\"alert alert-warning alert-dismissible fade show\"> <button type=\"button\" class=\"close\" data-dismiss=\"alert\"> × </button> <strong>Warning!</strong> There was a problem with internet connection. </div> <h6>Warning alert with heading</h6> <div class=\"alert alert-warning alert-dismissible fade show\"> <button type=\"button\" class=\"close\" data-dismiss=\"alert\"> × </button> <h5 class=\"alert-heading\">Warning!</h5> Wrong credentials. </div> </div> </body></html>", "e": 29018, "s": 27048, "text": null }, { "code": null, "e": 29026, "s": 29018, "text": "Output:" }, { "code": null, "e": 29059, "s": 29026, "text": "Warning Alert Types in Bootstrap" }, { "code": null, "e": 29211, "s": 29059, "text": "Example 2: In this example, we will use the warning alerts using the button click. When the user clicks the button, a warning alert will be generated. " }, { "code": null, "e": 29222, "s": 29211, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>Buttons and alerts</title> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\" rel=\"stylesheet\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"> </script> <script src=\"https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/js/bootstrap-alert.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function () { $('#success').click(function (e) { e.preventDefault() $('#message').html(` <div class=\"alert alert-success fade in\"> <button type=\"button class=\"close close-alert\" data-dismiss=\"alert\" aria-hidden=\"true\"> × </button>This is a success message </div>`); }) $('#warning').click(function (e) { e.preventDefault() $('#message').html(` <div class=\"alert alert-warning fade in\"> <button type=\"button\" class=\"close close-alert\" data-dismiss=\"alert\" aria-hidden=\"true\"> × </button> This is a warning message </div>`); }); }); </script></head> <body> <div class=\"container\"> <h2>GeeksForGeeks</h2> <p class=\"lead\"> Warning Alert message using bootstrap </p> <p> <form method=\"post\"> <button type=\"button\" class=\"btn btn-success\" id=\"success\"> Success </button> <button type=\"button\" class=\"btn btn-warning\" id=\"warning\"> Warning </button> </form> </p> <div id=\"message\"></div> </div></body> </html>", "e": 31292, "s": 29222, "text": null }, { "code": null, "e": 31300, "s": 31292, "text": "Output:" }, { "code": null, "e": 31437, "s": 31300, "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": 31457, "s": 31437, "text": "Bootstrap-Questions" }, { "code": null, "e": 31472, "s": 31457, "text": "HTML-Questions" }, { "code": null, "e": 31479, "s": 31472, "text": "Picked" }, { "code": null, "e": 31489, "s": 31479, "text": "Bootstrap" }, { "code": null, "e": 31494, "s": 31489, "text": "HTML" }, { "code": null, "e": 31511, "s": 31494, "text": "Web Technologies" }, { "code": null, "e": 31516, "s": 31511, "text": "HTML" }, { "code": null, "e": 31614, "s": 31516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31623, "s": 31614, "text": "Comments" }, { "code": null, "e": 31636, "s": 31623, "text": "Old Comments" }, { "code": null, "e": 31699, "s": 31636, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 31740, "s": 31699, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 31773, "s": 31740, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 31799, "s": 31773, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 31848, "s": 31799, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 31910, "s": 31848, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31960, "s": 31910, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32020, "s": 31960, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32068, "s": 32020, "text": "How to update Node.js and NPM to next version ?" } ]
MySQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column. Below is a selection from the "Products" table in the Northwind sample database: The following SQL statement finds the price of the cheapest product: The following SQL statement finds the price of the most expensive product: Use the MIN function to select the record with the smallest value of the Price column. SELECT FROM Products; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 70, "s": 0, "text": "The MIN() function returns the smallest value of the selected column." }, { "code": null, "e": 139, "s": 70, "text": "The MAX() function returns the largest value of the selected column." }, { "code": null, "e": 220, "s": 139, "text": "Below is a selection from the \"Products\" table in the Northwind sample database:" }, { "code": null, "e": 289, "s": 220, "text": "The following SQL statement finds the price of the cheapest product:" }, { "code": null, "e": 364, "s": 289, "text": "The following SQL statement finds the price of the most expensive product:" }, { "code": null, "e": 451, "s": 364, "text": "Use the MIN function to select the record with the smallest value of the Price column." }, { "code": null, "e": 475, "s": 451, "text": "SELECT \nFROM Products;\n" }, { "code": null, "e": 494, "s": 475, "text": "Start the Exercise" }, { "code": null, "e": 527, "s": 494, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 569, "s": 527, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 676, "s": 569, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 695, "s": 676, "text": "[email protected]" } ]
Find max in struct array - GeeksforGeeks
06 Jun, 2018 Given a struct array of type Height, find max struct Height{ int feet; int inches; } Question source : Microsoft Interview Experience Set 127 | (On-Campus for IDC) The idea is simple, traverse the array, and keep track of max valuevalue of array element(in inches) = 12*feet + inches // CPP program to return max// in struct array#include <iostream>#include <climits>using namespace std; // struct Height// 1 feet = 12 inchesstruct Height { int feet; int inches;}; // return max of the arrayint findMax(Height arr[], int n){ int mx = INT_MIN; for (int i = 0; i < n; i++) { int temp = 12 * (arr[i].feet) + arr[i].inches; mx = max(mx, temp); } return mx;} // driver programint main(){ // initialize the array Height arr[] = { { 1, 3 }, { 10, 5 }, { 6, 8 }, { 3, 7 }, { 5, 9 } }; int res = findMax(arr, 5); cout << "max :: " << res << endl; return 0;} Output: max :: 125 This article is contributed by Mandeep Singh. 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. ASAJ RAWAT Microsoft Arrays Microsoft Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Building Heap from Array Move all negative numbers to beginning and positive to end with constant extra space Program to find sum of elements in a given array Find duplicates in O(n) time and O(1) extra space | Set 1 Count pairs with given sum Next Greater Element Remove duplicates from sorted array
[ { "code": null, "e": 24820, "s": 24792, "text": "\n06 Jun, 2018" }, { "code": null, "e": 24866, "s": 24820, "text": "Given a struct array of type Height, find max" }, { "code": null, "e": 24910, "s": 24866, "text": "struct Height{\n int feet;\n int inches;\n}\n" }, { "code": null, "e": 24989, "s": 24910, "text": "Question source : Microsoft Interview Experience Set 127 | (On-Campus for IDC)" }, { "code": null, "e": 25109, "s": 24989, "text": "The idea is simple, traverse the array, and keep track of max valuevalue of array element(in inches) = 12*feet + inches" }, { "code": "// CPP program to return max// in struct array#include <iostream>#include <climits>using namespace std; // struct Height// 1 feet = 12 inchesstruct Height { int feet; int inches;}; // return max of the arrayint findMax(Height arr[], int n){ int mx = INT_MIN; for (int i = 0; i < n; i++) { int temp = 12 * (arr[i].feet) + arr[i].inches; mx = max(mx, temp); } return mx;} // driver programint main(){ // initialize the array Height arr[] = { { 1, 3 }, { 10, 5 }, { 6, 8 }, { 3, 7 }, { 5, 9 } }; int res = findMax(arr, 5); cout << \"max :: \" << res << endl; return 0;}", "e": 25783, "s": 25109, "text": null }, { "code": null, "e": 25791, "s": 25783, "text": "Output:" }, { "code": null, "e": 25803, "s": 25791, "text": "max :: 125\n" }, { "code": null, "e": 26100, "s": 25803, "text": "This article is contributed by Mandeep Singh. 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." }, { "code": null, "e": 26225, "s": 26100, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26236, "s": 26225, "text": "ASAJ RAWAT" }, { "code": null, "e": 26246, "s": 26236, "text": "Microsoft" }, { "code": null, "e": 26253, "s": 26246, "text": "Arrays" }, { "code": null, "e": 26263, "s": 26253, "text": "Microsoft" }, { "code": null, "e": 26270, "s": 26263, "text": "Arrays" }, { "code": null, "e": 26368, "s": 26270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26393, "s": 26368, "text": "Window Sliding Technique" }, { "code": null, "e": 26413, "s": 26393, "text": "Trapping Rain Water" }, { "code": null, "e": 26451, "s": 26413, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 26476, "s": 26451, "text": "Building Heap from Array" }, { "code": null, "e": 26561, "s": 26476, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 26610, "s": 26561, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 26668, "s": 26610, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 26695, "s": 26668, "text": "Count pairs with given sum" }, { "code": null, "e": 26716, "s": 26695, "text": "Next Greater Element" } ]
Crime Location Analysis and Prediction Using Python and Machine Learning | by Will Keefe | Towards Data Science
The author of this article is a proud West Virginia University Mountaineer and spent four years in Morgantown, West Virginia. Morgantown is a beautiful city in the Mountain State, and the campus of WVU is very safe. That being said, like in all cities safety incidents do occur, and the University Police Department reports these events daily in a crime log. With analysis via coding packages in Python, these events can be better visualized geographically to assess trends in location, type of incident, the likelihood of incidents based on time of day, and trends during unordinary events such as a football weekend, where the population of the town temporarily doubles. At the end of 2019, the author analyzed the safety event log in detail for the prior fall semester and created a dataset in JSON schema for the preceding four months as follows. {"case": casenumber (Integer),"crime": text (String),"occurred": date and time (String),"comments": text (String),"building": place (String),"address": place (String),"disposition": disposition (String),}, A total of approximately 1500 unique events occurred during this time, and the events are saved within a JSON file. To begin our project we will first need to import the packages below. # Basic Analysis and Visualizationimport pandas as pdimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltimport mathfrom datetime import timedelta# Mappingimport geopandasimport geopyfrom geopy.geocoders import Nominatimimport foliumfrom geopy.extra.rate_limiter import RateLimiterfrom folium import pluginsfrom folium.plugins import MarkerCluster# Statistical OLS Regression Analysis%matplotlib inlineimport statsmodels.api as smfrom statsmodels.compat import lzipfrom statsmodels.formula.api import ols#Scipy sklearn Predictionsfrom sklearn.ensemble import GradientBoostingRegressor Next, we import all of the events to our program from the file. # Pull in JSON and set index as case number (unique key)df = pd.read_json("MC.json",orient="records")df = df.set_index("case")df We should also convert our occurrence column to fit new date, time, and day of week columns with date-time schema. We should also remove any unfounded events from our dataset as well. # Convert time objectsdf['occurred'] = pd.to_datetime(df['occurred'])df['date'] = [d.date() for d in df['occurred']]df['time'] = [d.time() for d in df['occurred']]df['day'] = df['occurred'].dt.day_name()# Find Fractions of Daydf['timeint'] = (df['occurred']-df['occurred'].dt.normalize()).dt.total_seconds()/timedelta(days=1).total_seconds()# Remove unfounded eventsdf = df[df['disposition'] != 'Unfounded'] Let’s now get geographical data for our dataset as well. Abdishakur has a great article here we can follow along with to collect this data, implemented below. locator = Nominatim(user_agent='myGeocoder')location = locator.geocode('Morgantown, West Virginia')# 1 - conveneint function to delay between geocoding callsgeocode = RateLimiter(locator.geocode, min_delay_seconds=0.5)# 2- - create location columndf['location'] = df['address'].apply(geocode)# 3 - create longitude, latitude and altitude from location column (returns tuple)df['point'] = df['location'].apply(lambda loc: tuple(loc.point) if loc else None)# 4 - split point column into latitude, longitude and altitude columns and remove empty pointsdf = df[df['point'].notnull()]df[['latitude', 'longitude', 'altitude']] = pd.DataFrame(df['point'].tolist(), index=df.index)df.head() Assessing our now-complete dataset at a glance, we can start to notice some trends. df.groupby("crime")["crime"].count().sort_values() Most of the recorded incidences here are the result of poor decision-making under the influence of alcohol, destruction of university property in dorm rooms, or parking in illegal parking areas such as reserved lots. VEHICLE ACCIDENT 28ALARM CONDITION 30LARCENY 32FIRE ALARM 43DESTRUCTION OF PROPERTY 55DRUG INCIDENT 69TALK WITH OFFICER 74ABCC VIOLATION 84ASSIST EMS POLICE 86BACK TICKET TOW 99 The most frequently visited locations for these incidences also reflect the challenging transition to maturity and adulthood, with most occurring within the dormitories. df.groupby("building")["building"].count().sort_values()BLUE LOT 21WVU MOUNTAINLAIR 23WVU BOREMAN SOUTH 23COLLEGE PARK 23WVU SENECA HALL 25WVU POLICE DEPARTMENT 28WVU SUMMIT HALL 28WVU BROOKE TOWER 29HEALTH SCIENCE CENTER 55WVU DADISMAN HALL 56 Finally, we can also note that some of the days with the most safety events reported were days with unordinary events, such as football game days. df.groupby("date")["date"].count().sort_values()2019-11-01 21 # WVU vs Baylor2019-10-05 27 # WVU vs Texas2019-11-09 31 # WVU vs Texas Tech Having analyzed the data frames, let’s now visualize the data on maps using Folium. The below code plots points on Open Street Map with indicators for the type of event that occurred. # Mark events with names on mapm = folium.Map([39.645,-79.96], zoom_start=14)for index, row in df.iterrows(): folium.CircleMarker([row['latitude'], row['longitude']], radius=3, popup=row['crime'], fill_color="#3db7e4", # divvy color ).add_to(m)m While these indicators are useful and we can zoom in on the map to see them in detail, an additional heat map would improve the visibility of high-frequency areas where multiple indicators may overlap. # convert to (n, 2) nd-array format for heatmapdfmatrix = df[['latitude', 'longitude']].values# plot heatmapm.add_child(plugins.HeatMap(dfmatrix, radius=15))m From the rendered heatmap of safety incidences we can see areas of high-frequency on the Evansdale campus near the densely-populated Towers dormitories and football tailgating lots, and on the Downtown campus near Frat Row and High Street where a lot of nightlife occurs, not surprising for a college town. Earlier we had noted that the days with the most safety incidences happened to be football game days. Our data can help assess optimal locations to stage emergency services for future gamedays. The most active game was that against Texas Tech, on November 9, 2019. We can filter our dataset for just day with the code below. incidents_on_nov09 = df[df['date'] == pd.datetime(2019,11,9).date()] Let’s now visualize these filtered events reusing a script from earlier. # Map points of eventsm2 = folium.Map([39.645,-79.96], zoom_start=14)for index, row in incidents_on_nov09.iterrows(): folium.CircleMarker([row['latitude'], row['longitude']], radius=5, popup=row['crime'], fill_color="#3db7e4", # divvy color ).add_to(m2)# convert to (n, 2) nd-array format for heatmapdfmatrix = incidents_on_nov09[['latitude', 'longitude']].values# plot heatmapm2.add_child(plugins.HeatMap(dfmatrix, radius=15))m2 We can see that the events happened all over town. Using the latitude and longitude of these events, we can find a centroid for optimal resource allocation. If we have one ambulance available, it would be most efficient to place it in the middle of every point weighted by frequency on standby throughout the day for quickest average response time. We can find the centroid with this code. lat = []long = []for index, row in incidents_on_nov09.iterrows(): lat.append(row["latitude"]) long.append(row["longitude"])lat1=sum(lat)/len(lat)lat2=sum(long)/len(long)folium.CircleMarker([lat1,lat2], radius=5, popup="CENTER LOCATION", color='black', fill_color="#3db7e4", # divvy color ).add_to(m2)m2 The black circle in the map above shows the centroid the incidences on November 9th. If we were to stage emergency services on a future gameday, it would be worthwhile to stage them between Univeristy Avenue and Jones Avenue for fastest average response. What if we want to change our time frame? What would the centroid be for the evening on the day of a game after the game? after9PM = incidents_on_nov09[incidents_on_nov09['time'] >= pd.datetime(2019,11,9,21,0,0).time()]lat = []long = []for index, row in after9PM.iterrows(): lat.append(row["latitude"]) long.append(row["longitude"])lat1=sum(lat)/len(lat)lat2=sum(long)/len(long)folium.CircleMarker([lat1,lat2], radius=5, popup="LATE HOURS LOCATION", color='red', fill_color="#3db7e4", # divvy color ).add_to(m2)m2 Notice now the optimal staging location shifted further downtown, towards 1st Street and the Life Sciences Building. Can we use time series data and machine learning to predict locations of next incidences? To explore this further we need to configure two prediction models — one for latitude and one for longitude. We will be using the “timeint” column, or time interval or fraction of day, and scikit for predicting using gradient boosting regression. The following code is inspired by this example, and it is developing a prediction model from our data. This tutorial is not meant to perfectly explain the math behind our predictions, scikitlearn does a decent job of that, but what is important is that we are using the data set to create a function with a 90% confidence interval derived from the mean squared error. #----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(df['timeint'].values).T# Observationsy = np.atleast_2d(df['latitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 913)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Latitude$')plt.ylim(39.6, 39.7)plt.legend(loc='upper right')plt.show()ypred2 = y_pred We can see that our data is almost bimodal on the Latitude axis, and that the time of day does not significantly predict a shift in direction neither North nor South. #----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(df['timeint'].values).T# Observationsy = np.atleast_2d(df['longitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 913)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Longitude$')plt.ylim(-80, -79.9)plt.legend(loc='upper right')plt.show()ypred1 = y_pred Similarly, we can see a near-absence of trend for Longitude East and West, however the data is not nearly as split and has more evenly distributed points. If we were to try and predict subsequent events for the end of the day, we would also expect to notice a lack of a trend, and expect predicted safety incidences near the centroid, or the means of both latitude and longitude. # Map points of eventsm5 = folium.Map([39.645,-79.96], zoom_start=14)for i in range(len(ypred1)): folium.CircleMarker([ypred2[i], ypred1[i]], radius=4, popup=str(i), fill_color="#3db7e4", # divvy color ).add_to(m5)m5 Evaluating “predicted” timeseries for our data presented no clear conclusion aside from confirming the lack of causality between safety incident time of occurrence and location in town on average. While this could vary from day to day or with extraordinary circumstances, we did notice our trends in Latitude show bimodality, or a partial distinction between North and South Morgantown. If we assess these two areas separately, perhaps we can gather new areas of focus for resource allocation, such as a northern standby location and southern standby location. dfDowntown = df[df['latitude']<=39.6425] We can first separate our data on the approximate function line from the last dataset. Then, we will complete our model regression a second time on just the downtown data. #----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(dfDowntown['timeint'].values).T# Observationsy = np.atleast_2d(dfDowntown['latitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 535)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Latitude$')plt.ylim(39.6, 39.7)plt.legend(loc='upper right')plt.show()ypred2 = y_pred #----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(dfDowntown['timeint'].values).T# Observationsy = np.atleast_2d(dfDowntown['longitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 535)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Longitude$')plt.ylim(-80, -79.9)plt.legend(loc='upper right')plt.show()ypred1 = y_pred We can notice now a tighter, more responsive prediction and prediction interval. Mapped out, we also see areas of focus where we could potentially want to assess focusing safety response availability. # Map points of eventsm7 = folium.Map([39.645,-79.96], zoom_start=14)for i in range(len(ypred2)): folium.CircleMarker([ypred2[i], ypred1[i]], radius=4, popup=str(i), fill_color="#3db7e4", # divvy color ).add_to(m7)# convert to (n, 2) nd-array format for heatmapmatrix = np.column_stack((ypred2,ypred1))# plot heatmapm7.add_child(plugins.HeatMap(matrix, radius=15))m7 The same can now be done for Evansdale. dfEvansdale = df[df['latitude']>39.6425] From this data, we can see a good location for staging safety services on the Evansdale Campus is near the Towers dormitories and recreation centers near the football stadium. It can be very challenging to model machine learning based on timeseries data, and it is much easier to implement with clear causality. Future steps for this project could be to search for more indicators of causality or to filter data further, such as on game days or weekends specifically, or even by nature of event. The purpose of this data is not to perfectly predict where and when a near random event will occur, but to have a better understanding of how to prepare for an event and finding good locations for staging rapid service of events. This application can be applied to multiple other sources as well, such as event data in other universities or even cities if the API or data reporting is available. For further learning please check out some of my other articles and forecasting tools for financial data! Please follow me and let me know what you think!
[ { "code": null, "e": 720, "s": 47, "text": "The author of this article is a proud West Virginia University Mountaineer and spent four years in Morgantown, West Virginia. Morgantown is a beautiful city in the Mountain State, and the campus of WVU is very safe. That being said, like in all cities safety incidents do occur, and the University Police Department reports these events daily in a crime log. With analysis via coding packages in Python, these events can be better visualized geographically to assess trends in location, type of incident, the likelihood of incidents based on time of day, and trends during unordinary events such as a football weekend, where the population of the town temporarily doubles." }, { "code": null, "e": 898, "s": 720, "text": "At the end of 2019, the author analyzed the safety event log in detail for the prior fall semester and created a dataset in JSON schema for the preceding four months as follows." }, { "code": null, "e": 1104, "s": 898, "text": "{\"case\": casenumber (Integer),\"crime\": text (String),\"occurred\": date and time (String),\"comments\": text (String),\"building\": place (String),\"address\": place (String),\"disposition\": disposition (String),}," }, { "code": null, "e": 1220, "s": 1104, "text": "A total of approximately 1500 unique events occurred during this time, and the events are saved within a JSON file." }, { "code": null, "e": 1290, "s": 1220, "text": "To begin our project we will first need to import the packages below." }, { "code": null, "e": 1896, "s": 1290, "text": "# Basic Analysis and Visualizationimport pandas as pdimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltimport mathfrom datetime import timedelta# Mappingimport geopandasimport geopyfrom geopy.geocoders import Nominatimimport foliumfrom geopy.extra.rate_limiter import RateLimiterfrom folium import pluginsfrom folium.plugins import MarkerCluster# Statistical OLS Regression Analysis%matplotlib inlineimport statsmodels.api as smfrom statsmodels.compat import lzipfrom statsmodels.formula.api import ols#Scipy sklearn Predictionsfrom sklearn.ensemble import GradientBoostingRegressor" }, { "code": null, "e": 1960, "s": 1896, "text": "Next, we import all of the events to our program from the file." }, { "code": null, "e": 2089, "s": 1960, "text": "# Pull in JSON and set index as case number (unique key)df = pd.read_json(\"MC.json\",orient=\"records\")df = df.set_index(\"case\")df" }, { "code": null, "e": 2273, "s": 2089, "text": "We should also convert our occurrence column to fit new date, time, and day of week columns with date-time schema. We should also remove any unfounded events from our dataset as well." }, { "code": null, "e": 2681, "s": 2273, "text": "# Convert time objectsdf['occurred'] = pd.to_datetime(df['occurred'])df['date'] = [d.date() for d in df['occurred']]df['time'] = [d.time() for d in df['occurred']]df['day'] = df['occurred'].dt.day_name()# Find Fractions of Daydf['timeint'] = (df['occurred']-df['occurred'].dt.normalize()).dt.total_seconds()/timedelta(days=1).total_seconds()# Remove unfounded eventsdf = df[df['disposition'] != 'Unfounded']" }, { "code": null, "e": 2840, "s": 2681, "text": "Let’s now get geographical data for our dataset as well. Abdishakur has a great article here we can follow along with to collect this data, implemented below." }, { "code": null, "e": 3523, "s": 2840, "text": "locator = Nominatim(user_agent='myGeocoder')location = locator.geocode('Morgantown, West Virginia')# 1 - conveneint function to delay between geocoding callsgeocode = RateLimiter(locator.geocode, min_delay_seconds=0.5)# 2- - create location columndf['location'] = df['address'].apply(geocode)# 3 - create longitude, latitude and altitude from location column (returns tuple)df['point'] = df['location'].apply(lambda loc: tuple(loc.point) if loc else None)# 4 - split point column into latitude, longitude and altitude columns and remove empty pointsdf = df[df['point'].notnull()]df[['latitude', 'longitude', 'altitude']] = pd.DataFrame(df['point'].tolist(), index=df.index)df.head()" }, { "code": null, "e": 3607, "s": 3523, "text": "Assessing our now-complete dataset at a glance, we can start to notice some trends." }, { "code": null, "e": 3658, "s": 3607, "text": "df.groupby(\"crime\")[\"crime\"].count().sort_values()" }, { "code": null, "e": 3875, "s": 3658, "text": "Most of the recorded incidences here are the result of poor decision-making under the influence of alcohol, destruction of university property in dorm rooms, or parking in illegal parking areas such as reserved lots." }, { "code": null, "e": 4166, "s": 3875, "text": "VEHICLE ACCIDENT 28ALARM CONDITION 30LARCENY 32FIRE ALARM 43DESTRUCTION OF PROPERTY 55DRUG INCIDENT 69TALK WITH OFFICER 74ABCC VIOLATION 84ASSIST EMS POLICE 86BACK TICKET TOW 99" }, { "code": null, "e": 4336, "s": 4166, "text": "The most frequently visited locations for these incidences also reflect the challenging transition to maturity and adulthood, with most occurring within the dormitories." }, { "code": null, "e": 4863, "s": 4336, "text": "df.groupby(\"building\")[\"building\"].count().sort_values()BLUE LOT 21WVU MOUNTAINLAIR 23WVU BOREMAN SOUTH 23COLLEGE PARK 23WVU SENECA HALL 25WVU POLICE DEPARTMENT 28WVU SUMMIT HALL 28WVU BROOKE TOWER 29HEALTH SCIENCE CENTER 55WVU DADISMAN HALL 56" }, { "code": null, "e": 5010, "s": 4863, "text": "Finally, we can also note that some of the days with the most safety events reported were days with unordinary events, such as football game days." }, { "code": null, "e": 5158, "s": 5010, "text": "df.groupby(\"date\")[\"date\"].count().sort_values()2019-11-01 21 # WVU vs Baylor2019-10-05 27 # WVU vs Texas2019-11-09 31 # WVU vs Texas Tech" }, { "code": null, "e": 5342, "s": 5158, "text": "Having analyzed the data frames, let’s now visualize the data on maps using Folium. The below code plots points on Open Street Map with indicators for the type of event that occurred." }, { "code": null, "e": 5682, "s": 5342, "text": "# Mark events with names on mapm = folium.Map([39.645,-79.96], zoom_start=14)for index, row in df.iterrows(): folium.CircleMarker([row['latitude'], row['longitude']], radius=3, popup=row['crime'], fill_color=\"#3db7e4\", # divvy color ).add_to(m)m" }, { "code": null, "e": 5884, "s": 5682, "text": "While these indicators are useful and we can zoom in on the map to see them in detail, an additional heat map would improve the visibility of high-frequency areas where multiple indicators may overlap." }, { "code": null, "e": 6043, "s": 5884, "text": "# convert to (n, 2) nd-array format for heatmapdfmatrix = df[['latitude', 'longitude']].values# plot heatmapm.add_child(plugins.HeatMap(dfmatrix, radius=15))m" }, { "code": null, "e": 6350, "s": 6043, "text": "From the rendered heatmap of safety incidences we can see areas of high-frequency on the Evansdale campus near the densely-populated Towers dormitories and football tailgating lots, and on the Downtown campus near Frat Row and High Street where a lot of nightlife occurs, not surprising for a college town." }, { "code": null, "e": 6675, "s": 6350, "text": "Earlier we had noted that the days with the most safety incidences happened to be football game days. Our data can help assess optimal locations to stage emergency services for future gamedays. The most active game was that against Texas Tech, on November 9, 2019. We can filter our dataset for just day with the code below." }, { "code": null, "e": 6744, "s": 6675, "text": "incidents_on_nov09 = df[df['date'] == pd.datetime(2019,11,9).date()]" }, { "code": null, "e": 6817, "s": 6744, "text": "Let’s now visualize these filtered events reusing a script from earlier." }, { "code": null, "e": 7341, "s": 6817, "text": "# Map points of eventsm2 = folium.Map([39.645,-79.96], zoom_start=14)for index, row in incidents_on_nov09.iterrows(): folium.CircleMarker([row['latitude'], row['longitude']], radius=5, popup=row['crime'], fill_color=\"#3db7e4\", # divvy color ).add_to(m2)# convert to (n, 2) nd-array format for heatmapdfmatrix = incidents_on_nov09[['latitude', 'longitude']].values# plot heatmapm2.add_child(plugins.HeatMap(dfmatrix, radius=15))m2" }, { "code": null, "e": 7731, "s": 7341, "text": "We can see that the events happened all over town. Using the latitude and longitude of these events, we can find a centroid for optimal resource allocation. If we have one ambulance available, it would be most efficient to place it in the middle of every point weighted by frequency on standby throughout the day for quickest average response time. We can find the centroid with this code." }, { "code": null, "e": 8150, "s": 7731, "text": "lat = []long = []for index, row in incidents_on_nov09.iterrows(): lat.append(row[\"latitude\"]) long.append(row[\"longitude\"])lat1=sum(lat)/len(lat)lat2=sum(long)/len(long)folium.CircleMarker([lat1,lat2], radius=5, popup=\"CENTER LOCATION\", color='black', fill_color=\"#3db7e4\", # divvy color ).add_to(m2)m2" }, { "code": null, "e": 8405, "s": 8150, "text": "The black circle in the map above shows the centroid the incidences on November 9th. If we were to stage emergency services on a future gameday, it would be worthwhile to stage them between Univeristy Avenue and Jones Avenue for fastest average response." }, { "code": null, "e": 8527, "s": 8405, "text": "What if we want to change our time frame? What would the centroid be for the evening on the day of a game after the game?" }, { "code": null, "e": 9035, "s": 8527, "text": "after9PM = incidents_on_nov09[incidents_on_nov09['time'] >= pd.datetime(2019,11,9,21,0,0).time()]lat = []long = []for index, row in after9PM.iterrows(): lat.append(row[\"latitude\"]) long.append(row[\"longitude\"])lat1=sum(lat)/len(lat)lat2=sum(long)/len(long)folium.CircleMarker([lat1,lat2], radius=5, popup=\"LATE HOURS LOCATION\", color='red', fill_color=\"#3db7e4\", # divvy color ).add_to(m2)m2" }, { "code": null, "e": 9152, "s": 9035, "text": "Notice now the optimal staging location shifted further downtown, towards 1st Street and the Life Sciences Building." }, { "code": null, "e": 9857, "s": 9152, "text": "Can we use time series data and machine learning to predict locations of next incidences? To explore this further we need to configure two prediction models — one for latitude and one for longitude. We will be using the “timeint” column, or time interval or fraction of day, and scikit for predicting using gradient boosting regression. The following code is inspired by this example, and it is developing a prediction model from our data. This tutorial is not meant to perfectly explain the math behind our predictions, scikitlearn does a decent job of that, but what is important is that we are using the data set to create a function with a 90% confidence interval derived from the mean squared error." }, { "code": null, "e": 11350, "s": 9857, "text": "#----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(df['timeint'].values).T# Observationsy = np.atleast_2d(df['latitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 913)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Latitude$')plt.ylim(39.6, 39.7)plt.legend(loc='upper right')plt.show()ypred2 = y_pred" }, { "code": null, "e": 11517, "s": 11350, "text": "We can see that our data is almost bimodal on the Latitude axis, and that the time of day does not significantly predict a shift in direction neither North nor South." }, { "code": null, "e": 13012, "s": 11517, "text": "#----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(df['timeint'].values).T# Observationsy = np.atleast_2d(df['longitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 913)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Longitude$')plt.ylim(-80, -79.9)plt.legend(loc='upper right')plt.show()ypred1 = y_pred" }, { "code": null, "e": 13392, "s": 13012, "text": "Similarly, we can see a near-absence of trend for Longitude East and West, however the data is not nearly as split and has more evenly distributed points. If we were to try and predict subsequent events for the end of the day, we would also expect to notice a lack of a trend, and expect predicted safety incidences near the centroid, or the means of both latitude and longitude." }, { "code": null, "e": 13703, "s": 13392, "text": "# Map points of eventsm5 = folium.Map([39.645,-79.96], zoom_start=14)for i in range(len(ypred1)): folium.CircleMarker([ypred2[i], ypred1[i]], radius=4, popup=str(i), fill_color=\"#3db7e4\", # divvy color ).add_to(m5)m5" }, { "code": null, "e": 14264, "s": 13703, "text": "Evaluating “predicted” timeseries for our data presented no clear conclusion aside from confirming the lack of causality between safety incident time of occurrence and location in town on average. While this could vary from day to day or with extraordinary circumstances, we did notice our trends in Latitude show bimodality, or a partial distinction between North and South Morgantown. If we assess these two areas separately, perhaps we can gather new areas of focus for resource allocation, such as a northern standby location and southern standby location." }, { "code": null, "e": 14305, "s": 14264, "text": "dfDowntown = df[df['latitude']<=39.6425]" }, { "code": null, "e": 14477, "s": 14305, "text": "We can first separate our data on the approximate function line from the last dataset. Then, we will complete our model regression a second time on just the downtown data." }, { "code": null, "e": 15986, "s": 14477, "text": "#----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(dfDowntown['timeint'].values).T# Observationsy = np.atleast_2d(dfDowntown['latitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 535)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Latitude$')plt.ylim(39.6, 39.7)plt.legend(loc='upper right')plt.show()ypred2 = y_pred" }, { "code": null, "e": 17497, "s": 15986, "text": "#----------------------------------------------------------------------# First the noiseless caseX = np.atleast_2d(dfDowntown['timeint'].values).T# Observationsy = np.atleast_2d(dfDowntown['longitude'].values).T# Mesh the input space for evaluations of the real function, the prediction and# its MSExx = np.atleast_2d(np.linspace(0, 1, 535)).Txx = xx.astype(np.float32)alpha = 0.95clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, learning_rate=.1, min_samples_leaf=9, min_samples_split=9)clf.fit(X, y)# Make the prediction on the meshed x-axisy_upper = clf.predict(xx)clf.set_params(alpha=1.0 - alpha)clf.fit(X, y)# Make the prediction on the meshed x-axisy_lower = clf.predict(xx)clf.set_params(loss='ls')clf.fit(X, y)# Make the prediction on the meshed x-axisy_pred = clf.predict(xx)# Plot the function, the prediction and the 90% confidence interval based on# the MSEfig = plt.figure()plt.figure(figsize=(20,10))plt.plot(X, y, 'b.', markersize=10, label=u'Observations')plt.plot(xx, y_pred, 'r-', label=u'Prediction')plt.plot(xx, y_upper, 'k-')plt.plot(xx, y_lower, 'k-')plt.fill(np.concatenate([xx, xx[::-1]]), np.concatenate([y_upper, y_lower[::-1]]), alpha=.5, fc='b', ec='None', label='90% prediction interval')plt.xlabel('$Time of Day by Fraction$')plt.ylabel('$Longitude$')plt.ylim(-80, -79.9)plt.legend(loc='upper right')plt.show()ypred1 = y_pred" }, { "code": null, "e": 17698, "s": 17497, "text": "We can notice now a tighter, more responsive prediction and prediction interval. Mapped out, we also see areas of focus where we could potentially want to assess focusing safety response availability." }, { "code": null, "e": 18159, "s": 17698, "text": "# Map points of eventsm7 = folium.Map([39.645,-79.96], zoom_start=14)for i in range(len(ypred2)): folium.CircleMarker([ypred2[i], ypred1[i]], radius=4, popup=str(i), fill_color=\"#3db7e4\", # divvy color ).add_to(m7)# convert to (n, 2) nd-array format for heatmapmatrix = np.column_stack((ypred2,ypred1))# plot heatmapm7.add_child(plugins.HeatMap(matrix, radius=15))m7" }, { "code": null, "e": 18199, "s": 18159, "text": "The same can now be done for Evansdale." }, { "code": null, "e": 18240, "s": 18199, "text": "dfEvansdale = df[df['latitude']>39.6425]" }, { "code": null, "e": 18416, "s": 18240, "text": "From this data, we can see a good location for staging safety services on the Evansdale Campus is near the Towers dormitories and recreation centers near the football stadium." }, { "code": null, "e": 19132, "s": 18416, "text": "It can be very challenging to model machine learning based on timeseries data, and it is much easier to implement with clear causality. Future steps for this project could be to search for more indicators of causality or to filter data further, such as on game days or weekends specifically, or even by nature of event. The purpose of this data is not to perfectly predict where and when a near random event will occur, but to have a better understanding of how to prepare for an event and finding good locations for staging rapid service of events. This application can be applied to multiple other sources as well, such as event data in other universities or even cities if the API or data reporting is available." } ]
Program to sort each diagonal elements in ascending order of a matrix in C++
Suppose we have n x m matrix Mat, we have to sort this Mat diagonally in increasing order from top-left to the bottom right, so that all elements in the diagonals are sorted. So if the input matrix is like − The output matrix will be − To solve this, we will follow these steps − Define a method called solve(), this will take si, sj and matrix mat Define a method called solve(), this will take si, sj and matrix mat n := number of rows and m := number of columns n := number of rows and m := number of columns make an array called temp make an array called temp i:= si and j := sj, and index := 0 i:= si and j := sj, and index := 0 while i < n and j < m, doinsert m[i, j] into temp, then increase i and j by 1 while i < n and j < m, do insert m[i, j] into temp, then increase i and j by 1 insert m[i, j] into temp, then increase i and j by 1 sort temp array sort temp array set index := 0, i := si and j := sj set index := 0, i := si and j := sj while i < n and j < mmat[i, j] := temp[index]increase i, j and index by 1 while i < n and j < m mat[i, j] := temp[index] mat[i, j] := temp[index] increase i, j and index by 1 increase i, j and index by 1 from the main method, do the following − from the main method, do the following − n := number of rows and m := number of columns n := number of rows and m := number of columns for i in range 0 to n – 1, dosolve(i, 0, mat) for i in range 0 to n – 1, do solve(i, 0, mat) solve(i, 0, mat) for j in range 1 to m – 1, dosolve(0, j, mat) for j in range 1 to m – 1, do solve(0, j, mat) solve(0, j, mat) return mat return mat Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<auto> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: void solve(int si, int sj, vector < vector <int> > &mat){ int n = mat.size(); int m = mat[0].size(); vector <int> temp; int i = si; int j = sj; int idx = 0; while(i < n && j < m){ temp.push_back(mat[i][j]); i++; j++; } sort(temp.begin(), temp.end()); idx = 0; i = si; j = sj; while(i < n && j < m){ mat[i][j] = temp[idx]; i++; j++; idx++; } } vector<vector<int>> diagonalSort(vector<vector<int>>& mat) { int n = mat.size(); int m = mat[0].size(); for(int i = 0; i <n; i++){ solve(i, 0, mat); } for(int j = 1; j < m; j++){ solve(0, j, mat); } return mat; } }; main(){ vector<vector<int>> v = {{3,3,1,1},{2,2,1,2},{1,1,1,2}}; Solution ob; print_vector(ob.diagonalSort(v)); } {{3,3,1,1},{2,2,1,2},{1,1,1,2}} [[1, 1, 1, 1, ], [1, 2, 2, 2, ], [1, 2, 3, 3, ],]
[ { "code": null, "e": 1270, "s": 1062, "text": "Suppose we have n x m matrix Mat, we have to sort this Mat diagonally in increasing order from top-left to the bottom right, so that all elements in the diagonals are sorted. So if the input matrix is like −" }, { "code": null, "e": 1298, "s": 1270, "text": "The output matrix will be −" }, { "code": null, "e": 1342, "s": 1298, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1411, "s": 1342, "text": "Define a method called solve(), this will take si, sj and matrix mat" }, { "code": null, "e": 1480, "s": 1411, "text": "Define a method called solve(), this will take si, sj and matrix mat" }, { "code": null, "e": 1527, "s": 1480, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 1574, "s": 1527, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 1600, "s": 1574, "text": "make an array called temp" }, { "code": null, "e": 1626, "s": 1600, "text": "make an array called temp" }, { "code": null, "e": 1661, "s": 1626, "text": "i:= si and j := sj, and index := 0" }, { "code": null, "e": 1696, "s": 1661, "text": "i:= si and j := sj, and index := 0" }, { "code": null, "e": 1774, "s": 1696, "text": "while i < n and j < m, doinsert m[i, j] into temp, then increase i and j by 1" }, { "code": null, "e": 1800, "s": 1774, "text": "while i < n and j < m, do" }, { "code": null, "e": 1853, "s": 1800, "text": "insert m[i, j] into temp, then increase i and j by 1" }, { "code": null, "e": 1906, "s": 1853, "text": "insert m[i, j] into temp, then increase i and j by 1" }, { "code": null, "e": 1922, "s": 1906, "text": "sort temp array" }, { "code": null, "e": 1938, "s": 1922, "text": "sort temp array" }, { "code": null, "e": 1974, "s": 1938, "text": "set index := 0, i := si and j := sj" }, { "code": null, "e": 2010, "s": 1974, "text": "set index := 0, i := si and j := sj" }, { "code": null, "e": 2084, "s": 2010, "text": "while i < n and j < mmat[i, j] := temp[index]increase i, j and index by 1" }, { "code": null, "e": 2106, "s": 2084, "text": "while i < n and j < m" }, { "code": null, "e": 2131, "s": 2106, "text": "mat[i, j] := temp[index]" }, { "code": null, "e": 2156, "s": 2131, "text": "mat[i, j] := temp[index]" }, { "code": null, "e": 2185, "s": 2156, "text": "increase i, j and index by 1" }, { "code": null, "e": 2214, "s": 2185, "text": "increase i, j and index by 1" }, { "code": null, "e": 2255, "s": 2214, "text": "from the main method, do the following −" }, { "code": null, "e": 2296, "s": 2255, "text": "from the main method, do the following −" }, { "code": null, "e": 2343, "s": 2296, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 2390, "s": 2343, "text": "n := number of rows and m := number of columns" }, { "code": null, "e": 2436, "s": 2390, "text": "for i in range 0 to n – 1, dosolve(i, 0, mat)" }, { "code": null, "e": 2466, "s": 2436, "text": "for i in range 0 to n – 1, do" }, { "code": null, "e": 2483, "s": 2466, "text": "solve(i, 0, mat)" }, { "code": null, "e": 2500, "s": 2483, "text": "solve(i, 0, mat)" }, { "code": null, "e": 2546, "s": 2500, "text": "for j in range 1 to m – 1, dosolve(0, j, mat)" }, { "code": null, "e": 2576, "s": 2546, "text": "for j in range 1 to m – 1, do" }, { "code": null, "e": 2593, "s": 2576, "text": "solve(0, j, mat)" }, { "code": null, "e": 2610, "s": 2593, "text": "solve(0, j, mat)" }, { "code": null, "e": 2621, "s": 2610, "text": "return mat" }, { "code": null, "e": 2632, "s": 2621, "text": "return mat" }, { "code": null, "e": 2702, "s": 2632, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2713, "s": 2702, "text": " Live Demo" }, { "code": null, "e": 3937, "s": 2713, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<vector<auto> > v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << \"[\";\n for(int j = 0; j <v[i].size(); j++){\n cout << v[i][j] << \", \";\n }\n cout << \"],\";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n void solve(int si, int sj, vector < vector <int> > &mat){\n int n = mat.size();\n int m = mat[0].size();\n vector <int> temp;\n int i = si;\n int j = sj;\n int idx = 0;\n while(i < n && j < m){\n temp.push_back(mat[i][j]);\n i++;\n j++;\n }\n sort(temp.begin(), temp.end());\n idx = 0;\n i = si;\n j = sj;\n while(i < n && j < m){\n mat[i][j] = temp[idx];\n i++;\n j++;\n idx++;\n }\n }\n vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {\n int n = mat.size();\n int m = mat[0].size();\n for(int i = 0; i <n; i++){\n solve(i, 0, mat);\n }\n for(int j = 1; j < m; j++){\n solve(0, j, mat);\n }\n return mat;\n }\n};\nmain(){\n vector<vector<int>> v = {{3,3,1,1},{2,2,1,2},{1,1,1,2}};\n Solution ob;\n print_vector(ob.diagonalSort(v));\n}" }, { "code": null, "e": 3969, "s": 3937, "text": "{{3,3,1,1},{2,2,1,2},{1,1,1,2}}" }, { "code": null, "e": 4019, "s": 3969, "text": "[[1, 1, 1, 1, ], [1, 2, 2, 2, ], [1, 2, 3, 3, ],]" } ]
A Practical Guide to Implementing a Random Forest Classifier in Python | by Eden Molina | Towards Data Science
Random forest is a supervised learning method, meaning there are labels for and mappings between our input and outputs. It can be used for classification tasks like determining the species of a flower based on measurements like petal length and color, or it can used for regression tasks like predicting tomorrow’s weather forecast based on historical weather data. A random forest—as the name suggests—consists of multiple decision trees each of which outputs a prediction. When performing a classification task, each decision tree in the random forest votes for one of the classes to which the input belongs. For example, if we had a dataset on flowers and we wanted to determine the species of a flower, the decision trees in a random forest will each cast a vote for which species it thinks a flower belongs. Once all the trees have come to a conclusion, the random forest will count which class (species) had the most populous vote and this class will be what the random forest outputs as a prediction. In the case of regression, instead of determining the most populous vote the random forest will average the results of each decision tree. Because random forests utilize the results of multiple learners (decisions trees), random forests are a type of ensemble machine learning algorithm. Ensemble learning methods reduce variance and improve performance over their constituent learning models. As mentioned above, random forests consists of multiple decision trees. Decision trees split data into small groups of data based on the features of the data. For example in the flower dataset, the features would be petal length and color. The decision trees will continue to split the data into groups until a small set of data under one label ( a classification ) exist. A concrete example would be choosing a place to eat. One might peruse Yelp and find a place to eat based on key decisions like: is the place open right now, how popular is this place, what is the average rating for this place, and do I need a reservation. If the place is open, then the decision tree will continue on to the next feature if not the decision ends and the model outputs “no don’t eat here”. Now at the following feature, the model will determine if a place is popular, if the location is popular the model will move on to the next feature if not the model will output “no don’t eat here”—same procedure as before. Essentially one can think of a decision tree as a flowchart mapping out decisions once can take based on data until a final conclusion is made. The decision tree determines where to split the features based on a purity measure that measures information gain. In the case of classification it makes that decision based on the Gini index or entropy and in the case of regression, the residual sum of squares. However, the mathematics of this is beyond the scope of this blog post. In essence what these metics measure is Information Gain, the measure of how much information we’re able to gather from a piece of data. The random forest algorithm can be described as follows: Say the number of observations is N. These N observations will be sampled at random with replacement.Say there are M features or input variables. A number m, where m < M, will be selected at random at each node from the total number of features, M. The best split on these m variables are used to split the node and this value remains constant as the forest grows.Each decision tree in the forest is grown to its largest extent.The forest will output a prediction based on the aggregated predictions of the trees in the forest. (Either majority vote or average) Say the number of observations is N. These N observations will be sampled at random with replacement. Say there are M features or input variables. A number m, where m < M, will be selected at random at each node from the total number of features, M. The best split on these m variables are used to split the node and this value remains constant as the forest grows. Each decision tree in the forest is grown to its largest extent. The forest will output a prediction based on the aggregated predictions of the trees in the forest. (Either majority vote or average) In this post we will be utilizing a random forest to predict the cupping scores of coffees. Coffee beans are rated, professionally, on a 0–100 scale. This dataset contains the total cupping points of coffee beans as well as other characteristics of the beans such as country of origin, variety, flavor, aroma etc. Some of these features will be used to train a random forest classifier to predict the quality of a particular bean based on the total cupping points it received. The data in this demo comes from the TidyTuesday Repository and below is a preview of what the data looks like. To keep the model safe we will subset this dataset to contain columns that are attributes of the coffee which are, but not limited to: species, country of origin, acidity, body, and sweetness. Furthermore, we will drop any rows that contain nan (not a number/missing) values. coffee_df = coffee_ratings[['total_cup_points', 'species', 'country_of_origin', 'variety', 'aroma', 'aftertaste', 'acidity', 'body', 'balance', 'sweetness', 'altitude_mean_meters', 'moisture']]coffee_df = coffee_df.dropna() From above we can see the data contains not only numeric values but categorical values as well like species, country of origin, and variety. We can map these out to numeric values by using the OrginalEncoder function provided by the sklearn package. For example there are two species of coffee: Arabica and Robusta. The code will assign numerical values to these such that Arabica maps to 0, and Robusta maps to 1. A similar logic will follow for the other variables. from sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder()coffee_df["species"] = ord_enc.fit_transform(coffee_df[["species"]])coffee_df["country_of_origin"] = ord_enc.fit_transform(coffee_df[["country_of_origin"]])coffee_df["variety"] = ord_enc.fit_transform(coffee_df[["variety"]]) Now that all the data is numeric we can generate charts to observe the relations between the different features. A useful chart to make is a pairplot which shows the marginal and joint distributions of the features. We drop the import seabornseaborn.pairplot(coffee_df.drop('total_cup_points', axis = 1)) We can see the distributions are quite difficult to see especially. In some cases the distributions are quite binary such as speciies, or very skewed like average altitude. Furthermore, some numerical variables such as aroma and acidity contain one value each at 0, which are outliers in the data we will filter these out and replot the paitplot. coffee_df = coffee_df[coffee_df['aroma']>0]coffee_df = coffee_df[coffee_df['acidity']>0]seaborn.pairplot(coffee_df) Below we can see a clearer view of the joint distributions. The first column of plots represents how the features relate to the target variable total_cupping_points . We can see features from aroma to balance appear to have a strong relation to the total_cupping_points received. Furthermore, the marginal distributions, which we see on the diagonal of the pairplot appear to be, for the most part, normally distributed. Another plot we can generate for exploratory data analysis (EDA) is a correlation matrix which will display the correlations between the features. We can also accomplish this with the package seaborn. seaborn.heatmap(coffee_df.corr(), xticklabels=coffee_df.columns, yticklabels=coffee_df.columns) We can see, a positive correlation between features from aroma to sweetness, and negative correlations with species to variety as well as altitude_mean_meters and moisture. If we look at the distribution of total cupping ratings we can see the values are continuous and not discrete—as for example star ratings for restaurants, one star, two star, etc. In this project I will bin together the cupping ratings into three categories: low, average, and good. This can be accomplished by setting thresholds based on the distribution we see below. Anything within a certain threshold will be labeled as bad, average, or good. To be more precise, I will define anything below the 75th percentile to be labeled as ‘low’, anything between the 75th and 90th percentile as ‘average’, and the top 10 percentile as ‘good’. Of course, in the dataset, these labels will be numerical. Bad will be labeled as 1, average labeled as 2, and good labeled as 3. This is how the thresholds will be computed. We will call the percentile function from numpy and input a list containing the percentiles represenitng the cutoff points. rating_pctile = np.percentile(coffee_df['total_cup_points'], [75, 90])# The percentile thresholds arearray([83.58, 84.58]) We then use these thresholds to create a new column in the dataframe called n_rating representing the rating of the coffee using the new labeling system based on the percentile system defined above. coffee_df['n_rating'] = 0coffee_df['n_rating'] = np.where(coffee_df['total_cup_points'] < rating_pctile[0], 1, coffee_df['n_rating'])coffee_df['n_rating'] = np.where((coffee_df['total_cup_points'] >= rating_pctile[0]) & (coffee_df['total_cup_points'] <= rating_pctile[1]), 2, coffee_df['n_rating'])coffee_df['n_rating'] = np.where(coffee_df['total_cup_points'] > rating_pctile[1], 3, coffee_df['n_rating']) Below we can observe the new distribution of ratings given by out thresholds. The majority of coffee ratings are in the ‘low’ category (75% the data to be precise), and only a few coffees have a ‘good’. At this point the data is nearly ready for modeling. We now need to split the data into training and testing sets. The training set will be used to train the random forest classifier, while the testing set will be used to evaluate the model’s performance—as this is data it has not seen before in training. Here 75% the data is used for training and 25% of the data is used for testing. X = coffee_df.drop(['total_cup_points', 'n_rating', 'sweetness', 'species', 'altitude_mean_meters'], axis = 1)y = coffee_df['n_rating']training, testing, training_labels, testing_labels = train_test_split(X, y, test_size = .25, random_state = 42) Next we will scale the data, this will being all our features to the same scale, this helps ensure attributes with larger values do not over influence the model. The StandardScaler in sklearn essentially computes the z score of each feature which ensures each feature in the dataset has a mean of 0 and variance of 1. # Normalize the datasc = StandardScaler()normed_train_data = pd.DataFrame(sc.fit_transform(training), columns = X.columns)normed_test_data = pd.DataFrame(sc.fit_transform(testing), columns = X.columns) For posterity we can plot another pairplot to see if normalizing accentuates the relations between the features. After normalizing the data, the relations of the coffee attributes from aroma to balance are clearer. Because of the elliptical joint distributions, there appears to be string relations between these vairables. Now the data is prepped, we can begin to code up the random forest. We can instantiate it and train it in just two lines. clf=RandomForestClassifier()clf.fit(training, training_labels) Then make predictions. preds = clf.predict(testing) Then quickly evaluate it’s performance. print (clf.score(training, training_labels))print(clf.score(testing, testing_labels))1.00.8674698795180723 The score method gives us an insight to the mean accuracy of the random forest on the given data. In the first call we evaluate it’s performance on the training data, then on the testing data. The model scores 100% accuracy on the training data and a lower 86.75% on the testing data. Since the training accuracy is so high and the testing is not as close, it’s safe to say the model is overfitting—the model is modeling the training data too well and not generalizing what it’s learning. Think of it as memorizing answers to a test instead of actually learning the concepts for that test. We will discuss how to to mitigate this issue later. Another tool we can use to evaluate the performance of the model is by a confusion matrix. A confusion matrix shows the combination of the actual and predicted classes. Each row of the matrix represents the instances in a predicted class, while each column represents the instances in an actual class. It is a good measure of whether models can account for the overlap in class properties and understand which classes are most easily confused. metrics.confusion_matrix(testing_labels, preds, labels = [1, 2, 3]) The first column represents the coffees with a ‘low’ rating, the second column represents the coffees with an ‘average’ rating, and the third column represents the coffee with a ‘good’ rating. The numbers on the diagonal of the matrix, 183, 19, and 14 represent the number of coffees the model has accurately classified. The off diagonal values represent the misclassidied data. For example, 11 coffees which were supposed to be marked as ‘low’ scoring coffees were marked ‘average’. Another interesting insight we can gain from a random forest is to explore what features the model ‘thinks’ are most important in determining the total cupping points. pd.DataFrame(clf.feature_importances_, index=training.columns).sort_values(by=0, ascending=False) We can see balance , aftertaste, and acidity appear to heavily contribute to the total cupping points a coffee receives. When instantiating a random forest as we did above clf=RandomForestClassifier() parameters such as the number of trees in the forest, the metric used to split the features, and so on took on the default values set in sklearn. However, these default values more often than not are not the most optimal and must be tuned for each use case. The parameters to be tuned can be found in the sklearn documentation. One way to tune these parameters is to perform a random grid search. We define a range of values from which the code can randomly pick and choose until it finds a set that performs the best. To begin we define values the search algorithm will search through. # Number of trees in random forestn_estimators = np.linspace(100, 3000, int((3000-100)/200) + 1, dtype=int)# Number of features to consider at every splitmax_features = ['auto', 'sqrt']# Maximum number of levels in treemax_depth = [1, 5, 10, 20, 50, 75, 100, 150, 200]# Minimum number of samples required to split a node# min_samples_split = [int(x) for x in np.linspace(start = 2, stop = 10, num = 9)]min_samples_split = [1, 2, 5, 10, 15, 20, 30]# Minimum number of samples required at each leaf nodemin_samples_leaf = [1, 2, 3, 4]# Method of selecting samples for training each treebootstrap = [True, False]# Criterioncriterion=['gini', 'entropy']random_grid = {'n_estimators': n_estimators,# 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap, 'criterion': criterion} What this essentially creates is a dictionary of values to choose from: {'n_estimators': array([ 100, 307, 514, 721, 928, 1135, 1342, 1550, 1757, 1964, 2171, 2378, 2585, 2792, 3000]), 'max_depth': [1, 5, 10, 20, 50, 75, 100, 150, 200], 'min_samples_split': [1, 2, 5, 10, 15, 20, 30], 'min_samples_leaf': [1, 2, 3, 4], 'bootstrap': [True, False], 'criterion': ['gini', 'entropy']} Next we can begin the search and then fit a new random forest classifier on the parameters found from the random search. rf_base = RandomForestClassifier()rf_random = RandomizedSearchCV(estimator = rf_base, param_distributions = random_grid, n_iter = 30, cv = 5, verbose=2, random_state=42, n_jobs = 4)rf_random.fit(training, training_labels) We can also view the parameter values the random search found: rf_random.best_params_{'n_estimators': 2171, 'min_samples_split': 2, 'min_samples_leaf': 2, 'max_depth': 200, 'criterion': 'entropy', 'bootstrap': True} From here we can again evaluate the model print (rf_random.score(training, training_labels))print(rf_random.score(testing, testing_labels))0.98259705488621150.8714859437751004 We now see the training score is less than 100%, and the testing score is 87.25%. The model doesn’t appear to be overfitting as much as before. Now that we have parameter values from the randomized grid search, we can use these as a starting point for a grid search. A grid search works, in principle, similarly to the randomized grid search as it will search through the parameter space we define. However, instead of searching random values it will search every value possible in the parameter space. This computation can be expensive because the search grows very fast as more parameters and search values for those parameters increasess. This is why we performed the random grid search first. We save on compute power and only perform a fine methodological search once we have a good starting point. Instantiating a grid search is also similar to instantiating the random grid search. param_grid = { 'n_estimators': np.linspace(2100, 2300, 5, dtype = int), 'max_depth': [170, 180, 190, 200, 210, 220], 'min_samples_split': [2, 3, 4], 'min_samples_leaf': [2, 3, 4, 5]} We can then retrain yet another random forest. # Base modelrf_grid = RandomForestClassifier(criterion = 'entropy', bootstrap = True)# Instantiate the grid search modelgrid_rf_search = GridSearchCV(estimator = rf_grid, param_grid = param_grid, cv = 5, n_jobs = 8, verbose = 2)grid_rf_search.fit(training, training_labels) And view what it found to be the most optimal set of parameters best_rf_grid = grid_rf_search.best_estimator_grid_rf_search.best_params_{'max_depth': 170, 'min_samples_leaf': 2, 'min_samples_split': 2, 'n_estimators': 2100} We can see the results it found are not too far from what the random grid search found. Now we can evaluate this model to determine it’s accuracy and performance. print (grid_rf_search.score(training, training_labels))print(grid_rf_search.score(testing, testing_labels))0.98393574297188760.8714859437751004 We see it performs very similarly to the random search grid as it’s parameters did not stray too far from what we initially started with. Furthermore, we can also view the features the model thought were most importnact. Balance, aftertaste, and acidity are still the top 3 features with just slightly different weights. Lastly we can view the confusion matrix for this final model. It appears it’s the same as before. In this article, we performed some exploratory data analysis on the coffee dataset from TidyTuesday and built a Random Forest Classifier to classify coffees into three groups: low, average, good. These classes determine how many cupping points the coffee is expected to receive. Once we built an initial classifier we tuned it’s hyper-parameters to determine if we can further improve the performance of the mode.
[ { "code": null, "e": 1574, "s": 172, "text": "Random forest is a supervised learning method, meaning there are labels for and mappings between our input and outputs. It can be used for classification tasks like determining the species of a flower based on measurements like petal length and color, or it can used for regression tasks like predicting tomorrow’s weather forecast based on historical weather data. A random forest—as the name suggests—consists of multiple decision trees each of which outputs a prediction. When performing a classification task, each decision tree in the random forest votes for one of the classes to which the input belongs. For example, if we had a dataset on flowers and we wanted to determine the species of a flower, the decision trees in a random forest will each cast a vote for which species it thinks a flower belongs. Once all the trees have come to a conclusion, the random forest will count which class (species) had the most populous vote and this class will be what the random forest outputs as a prediction. In the case of regression, instead of determining the most populous vote the random forest will average the results of each decision tree. Because random forests utilize the results of multiple learners (decisions trees), random forests are a type of ensemble machine learning algorithm. Ensemble learning methods reduce variance and improve performance over their constituent learning models." }, { "code": null, "e": 3192, "s": 1574, "text": "As mentioned above, random forests consists of multiple decision trees. Decision trees split data into small groups of data based on the features of the data. For example in the flower dataset, the features would be petal length and color. The decision trees will continue to split the data into groups until a small set of data under one label ( a classification ) exist. A concrete example would be choosing a place to eat. One might peruse Yelp and find a place to eat based on key decisions like: is the place open right now, how popular is this place, what is the average rating for this place, and do I need a reservation. If the place is open, then the decision tree will continue on to the next feature if not the decision ends and the model outputs “no don’t eat here”. Now at the following feature, the model will determine if a place is popular, if the location is popular the model will move on to the next feature if not the model will output “no don’t eat here”—same procedure as before. Essentially one can think of a decision tree as a flowchart mapping out decisions once can take based on data until a final conclusion is made. The decision tree determines where to split the features based on a purity measure that measures information gain. In the case of classification it makes that decision based on the Gini index or entropy and in the case of regression, the residual sum of squares. However, the mathematics of this is beyond the scope of this blog post. In essence what these metics measure is Information Gain, the measure of how much information we’re able to gather from a piece of data." }, { "code": null, "e": 3249, "s": 3192, "text": "The random forest algorithm can be described as follows:" }, { "code": null, "e": 3811, "s": 3249, "text": "Say the number of observations is N. These N observations will be sampled at random with replacement.Say there are M features or input variables. A number m, where m < M, will be selected at random at each node from the total number of features, M. The best split on these m variables are used to split the node and this value remains constant as the forest grows.Each decision tree in the forest is grown to its largest extent.The forest will output a prediction based on the aggregated predictions of the trees in the forest. (Either majority vote or average)" }, { "code": null, "e": 3913, "s": 3811, "text": "Say the number of observations is N. These N observations will be sampled at random with replacement." }, { "code": null, "e": 4177, "s": 3913, "text": "Say there are M features or input variables. A number m, where m < M, will be selected at random at each node from the total number of features, M. The best split on these m variables are used to split the node and this value remains constant as the forest grows." }, { "code": null, "e": 4242, "s": 4177, "text": "Each decision tree in the forest is grown to its largest extent." }, { "code": null, "e": 4376, "s": 4242, "text": "The forest will output a prediction based on the aggregated predictions of the trees in the forest. (Either majority vote or average)" }, { "code": null, "e": 4965, "s": 4376, "text": "In this post we will be utilizing a random forest to predict the cupping scores of coffees. Coffee beans are rated, professionally, on a 0–100 scale. This dataset contains the total cupping points of coffee beans as well as other characteristics of the beans such as country of origin, variety, flavor, aroma etc. Some of these features will be used to train a random forest classifier to predict the quality of a particular bean based on the total cupping points it received. The data in this demo comes from the TidyTuesday Repository and below is a preview of what the data looks like." }, { "code": null, "e": 5241, "s": 4965, "text": "To keep the model safe we will subset this dataset to contain columns that are attributes of the coffee which are, but not limited to: species, country of origin, acidity, body, and sweetness. Furthermore, we will drop any rows that contain nan (not a number/missing) values." }, { "code": null, "e": 5762, "s": 5241, "text": "coffee_df = coffee_ratings[['total_cup_points', 'species', 'country_of_origin', 'variety', 'aroma', 'aftertaste', 'acidity', 'body', 'balance', 'sweetness', 'altitude_mean_meters', 'moisture']]coffee_df = coffee_df.dropna()" }, { "code": null, "e": 6230, "s": 5762, "text": "From above we can see the data contains not only numeric values but categorical values as well like species, country of origin, and variety. We can map these out to numeric values by using the OrginalEncoder function provided by the sklearn package. For example there are two species of coffee: Arabica and Robusta. The code will assign numerical values to these such that Arabica maps to 0, and Robusta maps to 1. A similar logic will follow for the other variables." }, { "code": null, "e": 6529, "s": 6230, "text": "from sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder()coffee_df[\"species\"] = ord_enc.fit_transform(coffee_df[[\"species\"]])coffee_df[\"country_of_origin\"] = ord_enc.fit_transform(coffee_df[[\"country_of_origin\"]])coffee_df[\"variety\"] = ord_enc.fit_transform(coffee_df[[\"variety\"]])" }, { "code": null, "e": 6757, "s": 6529, "text": "Now that all the data is numeric we can generate charts to observe the relations between the different features. A useful chart to make is a pairplot which shows the marginal and joint distributions of the features. We drop the" }, { "code": null, "e": 6834, "s": 6757, "text": "import seabornseaborn.pairplot(coffee_df.drop('total_cup_points', axis = 1))" }, { "code": null, "e": 7181, "s": 6834, "text": "We can see the distributions are quite difficult to see especially. In some cases the distributions are quite binary such as speciies, or very skewed like average altitude. Furthermore, some numerical variables such as aroma and acidity contain one value each at 0, which are outliers in the data we will filter these out and replot the paitplot." }, { "code": null, "e": 7297, "s": 7181, "text": "coffee_df = coffee_df[coffee_df['aroma']>0]coffee_df = coffee_df[coffee_df['acidity']>0]seaborn.pairplot(coffee_df)" }, { "code": null, "e": 7718, "s": 7297, "text": "Below we can see a clearer view of the joint distributions. The first column of plots represents how the features relate to the target variable total_cupping_points . We can see features from aroma to balance appear to have a strong relation to the total_cupping_points received. Furthermore, the marginal distributions, which we see on the diagonal of the pairplot appear to be, for the most part, normally distributed." }, { "code": null, "e": 7919, "s": 7718, "text": "Another plot we can generate for exploratory data analysis (EDA) is a correlation matrix which will display the correlations between the features. We can also accomplish this with the package seaborn." }, { "code": null, "e": 8045, "s": 7919, "text": "seaborn.heatmap(coffee_df.corr(), xticklabels=coffee_df.columns, yticklabels=coffee_df.columns)" }, { "code": null, "e": 8218, "s": 8045, "text": "We can see, a positive correlation between features from aroma to sweetness, and negative correlations with species to variety as well as altitude_mean_meters and moisture." }, { "code": null, "e": 8986, "s": 8218, "text": "If we look at the distribution of total cupping ratings we can see the values are continuous and not discrete—as for example star ratings for restaurants, one star, two star, etc. In this project I will bin together the cupping ratings into three categories: low, average, and good. This can be accomplished by setting thresholds based on the distribution we see below. Anything within a certain threshold will be labeled as bad, average, or good. To be more precise, I will define anything below the 75th percentile to be labeled as ‘low’, anything between the 75th and 90th percentile as ‘average’, and the top 10 percentile as ‘good’. Of course, in the dataset, these labels will be numerical. Bad will be labeled as 1, average labeled as 2, and good labeled as 3." }, { "code": null, "e": 9155, "s": 8986, "text": "This is how the thresholds will be computed. We will call the percentile function from numpy and input a list containing the percentiles represenitng the cutoff points." }, { "code": null, "e": 9278, "s": 9155, "text": "rating_pctile = np.percentile(coffee_df['total_cup_points'], [75, 90])# The percentile thresholds arearray([83.58, 84.58])" }, { "code": null, "e": 9477, "s": 9278, "text": "We then use these thresholds to create a new column in the dataframe called n_rating representing the rating of the coffee using the new labeling system based on the percentile system defined above." }, { "code": null, "e": 9884, "s": 9477, "text": "coffee_df['n_rating'] = 0coffee_df['n_rating'] = np.where(coffee_df['total_cup_points'] < rating_pctile[0], 1, coffee_df['n_rating'])coffee_df['n_rating'] = np.where((coffee_df['total_cup_points'] >= rating_pctile[0]) & (coffee_df['total_cup_points'] <= rating_pctile[1]), 2, coffee_df['n_rating'])coffee_df['n_rating'] = np.where(coffee_df['total_cup_points'] > rating_pctile[1], 3, coffee_df['n_rating'])" }, { "code": null, "e": 10087, "s": 9884, "text": "Below we can observe the new distribution of ratings given by out thresholds. The majority of coffee ratings are in the ‘low’ category (75% the data to be precise), and only a few coffees have a ‘good’." }, { "code": null, "e": 10474, "s": 10087, "text": "At this point the data is nearly ready for modeling. We now need to split the data into training and testing sets. The training set will be used to train the random forest classifier, while the testing set will be used to evaluate the model’s performance—as this is data it has not seen before in training. Here 75% the data is used for training and 25% of the data is used for testing." }, { "code": null, "e": 10721, "s": 10474, "text": "X = coffee_df.drop(['total_cup_points', 'n_rating', 'sweetness', 'species', 'altitude_mean_meters'], axis = 1)y = coffee_df['n_rating']training, testing, training_labels, testing_labels = train_test_split(X, y, test_size = .25, random_state = 42)" }, { "code": null, "e": 11039, "s": 10721, "text": "Next we will scale the data, this will being all our features to the same scale, this helps ensure attributes with larger values do not over influence the model. The StandardScaler in sklearn essentially computes the z score of each feature which ensures each feature in the dataset has a mean of 0 and variance of 1." }, { "code": null, "e": 11241, "s": 11039, "text": "# Normalize the datasc = StandardScaler()normed_train_data = pd.DataFrame(sc.fit_transform(training), columns = X.columns)normed_test_data = pd.DataFrame(sc.fit_transform(testing), columns = X.columns)" }, { "code": null, "e": 11565, "s": 11241, "text": "For posterity we can plot another pairplot to see if normalizing accentuates the relations between the features. After normalizing the data, the relations of the coffee attributes from aroma to balance are clearer. Because of the elliptical joint distributions, there appears to be string relations between these vairables." }, { "code": null, "e": 11687, "s": 11565, "text": "Now the data is prepped, we can begin to code up the random forest. We can instantiate it and train it in just two lines." }, { "code": null, "e": 11750, "s": 11687, "text": "clf=RandomForestClassifier()clf.fit(training, training_labels)" }, { "code": null, "e": 11773, "s": 11750, "text": "Then make predictions." }, { "code": null, "e": 11802, "s": 11773, "text": "preds = clf.predict(testing)" }, { "code": null, "e": 11842, "s": 11802, "text": "Then quickly evaluate it’s performance." }, { "code": null, "e": 11949, "s": 11842, "text": "print (clf.score(training, training_labels))print(clf.score(testing, testing_labels))1.00.8674698795180723" }, { "code": null, "e": 12592, "s": 11949, "text": "The score method gives us an insight to the mean accuracy of the random forest on the given data. In the first call we evaluate it’s performance on the training data, then on the testing data. The model scores 100% accuracy on the training data and a lower 86.75% on the testing data. Since the training accuracy is so high and the testing is not as close, it’s safe to say the model is overfitting—the model is modeling the training data too well and not generalizing what it’s learning. Think of it as memorizing answers to a test instead of actually learning the concepts for that test. We will discuss how to to mitigate this issue later." }, { "code": null, "e": 13036, "s": 12592, "text": "Another tool we can use to evaluate the performance of the model is by a confusion matrix. A confusion matrix shows the combination of the actual and predicted classes. Each row of the matrix represents the instances in a predicted class, while each column represents the instances in an actual class. It is a good measure of whether models can account for the overlap in class properties and understand which classes are most easily confused." }, { "code": null, "e": 13105, "s": 13036, "text": "metrics.confusion_matrix(testing_labels, preds, labels = [1, 2, 3])" }, { "code": null, "e": 13589, "s": 13105, "text": "The first column represents the coffees with a ‘low’ rating, the second column represents the coffees with an ‘average’ rating, and the third column represents the coffee with a ‘good’ rating. The numbers on the diagonal of the matrix, 183, 19, and 14 represent the number of coffees the model has accurately classified. The off diagonal values represent the misclassidied data. For example, 11 coffees which were supposed to be marked as ‘low’ scoring coffees were marked ‘average’." }, { "code": null, "e": 13757, "s": 13589, "text": "Another interesting insight we can gain from a random forest is to explore what features the model ‘thinks’ are most important in determining the total cupping points." }, { "code": null, "e": 13855, "s": 13757, "text": "pd.DataFrame(clf.feature_importances_, index=training.columns).sort_values(by=0, ascending=False)" }, { "code": null, "e": 13976, "s": 13855, "text": "We can see balance , aftertaste, and acidity appear to heavily contribute to the total cupping points a coffee receives." }, { "code": null, "e": 14643, "s": 13976, "text": "When instantiating a random forest as we did above clf=RandomForestClassifier() parameters such as the number of trees in the forest, the metric used to split the features, and so on took on the default values set in sklearn. However, these default values more often than not are not the most optimal and must be tuned for each use case. The parameters to be tuned can be found in the sklearn documentation. One way to tune these parameters is to perform a random grid search. We define a range of values from which the code can randomly pick and choose until it finds a set that performs the best. To begin we define values the search algorithm will search through." }, { "code": null, "e": 15603, "s": 14643, "text": "# Number of trees in random forestn_estimators = np.linspace(100, 3000, int((3000-100)/200) + 1, dtype=int)# Number of features to consider at every splitmax_features = ['auto', 'sqrt']# Maximum number of levels in treemax_depth = [1, 5, 10, 20, 50, 75, 100, 150, 200]# Minimum number of samples required to split a node# min_samples_split = [int(x) for x in np.linspace(start = 2, stop = 10, num = 9)]min_samples_split = [1, 2, 5, 10, 15, 20, 30]# Minimum number of samples required at each leaf nodemin_samples_leaf = [1, 2, 3, 4]# Method of selecting samples for training each treebootstrap = [True, False]# Criterioncriterion=['gini', 'entropy']random_grid = {'n_estimators': n_estimators,# 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap, 'criterion': criterion}" }, { "code": null, "e": 15675, "s": 15603, "text": "What this essentially creates is a dictionary of values to choose from:" }, { "code": null, "e": 15994, "s": 15675, "text": "{'n_estimators': array([ 100, 307, 514, 721, 928, 1135, 1342, 1550, 1757, 1964, 2171, 2378, 2585, 2792, 3000]), 'max_depth': [1, 5, 10, 20, 50, 75, 100, 150, 200], 'min_samples_split': [1, 2, 5, 10, 15, 20, 30], 'min_samples_leaf': [1, 2, 3, 4], 'bootstrap': [True, False], 'criterion': ['gini', 'entropy']}" }, { "code": null, "e": 16115, "s": 15994, "text": "Next we can begin the search and then fit a new random forest classifier on the parameters found from the random search." }, { "code": null, "e": 16457, "s": 16115, "text": "rf_base = RandomForestClassifier()rf_random = RandomizedSearchCV(estimator = rf_base, param_distributions = random_grid, n_iter = 30, cv = 5, verbose=2, random_state=42, n_jobs = 4)rf_random.fit(training, training_labels)" }, { "code": null, "e": 16520, "s": 16457, "text": "We can also view the parameter values the random search found:" }, { "code": null, "e": 16673, "s": 16520, "text": "rf_random.best_params_{'n_estimators': 2171, 'min_samples_split': 2, 'min_samples_leaf': 2, 'max_depth': 200, 'criterion': 'entropy', 'bootstrap': True}" }, { "code": null, "e": 16715, "s": 16673, "text": "From here we can again evaluate the model" }, { "code": null, "e": 16849, "s": 16715, "text": "print (rf_random.score(training, training_labels))print(rf_random.score(testing, testing_labels))0.98259705488621150.8714859437751004" }, { "code": null, "e": 16993, "s": 16849, "text": "We now see the training score is less than 100%, and the testing score is 87.25%. The model doesn’t appear to be overfitting as much as before." }, { "code": null, "e": 17738, "s": 16993, "text": "Now that we have parameter values from the randomized grid search, we can use these as a starting point for a grid search. A grid search works, in principle, similarly to the randomized grid search as it will search through the parameter space we define. However, instead of searching random values it will search every value possible in the parameter space. This computation can be expensive because the search grows very fast as more parameters and search values for those parameters increasess. This is why we performed the random grid search first. We save on compute power and only perform a fine methodological search once we have a good starting point. Instantiating a grid search is also similar to instantiating the random grid search." }, { "code": null, "e": 17933, "s": 17738, "text": "param_grid = { 'n_estimators': np.linspace(2100, 2300, 5, dtype = int), 'max_depth': [170, 180, 190, 200, 210, 220], 'min_samples_split': [2, 3, 4], 'min_samples_leaf': [2, 3, 4, 5]}" }, { "code": null, "e": 17980, "s": 17933, "text": "We can then retrain yet another random forest." }, { "code": null, "e": 18280, "s": 17980, "text": "# Base modelrf_grid = RandomForestClassifier(criterion = 'entropy', bootstrap = True)# Instantiate the grid search modelgrid_rf_search = GridSearchCV(estimator = rf_grid, param_grid = param_grid, cv = 5, n_jobs = 8, verbose = 2)grid_rf_search.fit(training, training_labels)" }, { "code": null, "e": 18344, "s": 18280, "text": "And view what it found to be the most optimal set of parameters" }, { "code": null, "e": 18504, "s": 18344, "text": "best_rf_grid = grid_rf_search.best_estimator_grid_rf_search.best_params_{'max_depth': 170, 'min_samples_leaf': 2, 'min_samples_split': 2, 'n_estimators': 2100}" }, { "code": null, "e": 18667, "s": 18504, "text": "We can see the results it found are not too far from what the random grid search found. Now we can evaluate this model to determine it’s accuracy and performance." }, { "code": null, "e": 18811, "s": 18667, "text": "print (grid_rf_search.score(training, training_labels))print(grid_rf_search.score(testing, testing_labels))0.98393574297188760.8714859437751004" }, { "code": null, "e": 18949, "s": 18811, "text": "We see it performs very similarly to the random search grid as it’s parameters did not stray too far from what we initially started with." }, { "code": null, "e": 19132, "s": 18949, "text": "Furthermore, we can also view the features the model thought were most importnact. Balance, aftertaste, and acidity are still the top 3 features with just slightly different weights." }, { "code": null, "e": 19230, "s": 19132, "text": "Lastly we can view the confusion matrix for this final model. It appears it’s the same as before." } ]
How to create a ToolBar in JavaFX?
A toolbar is used to display UI elements such as buttons, toggle buttons, and separators, etc.. You cannot add any other nodes to a toolbar. The contents of a toolbar can be arranged either horizontally or vertically. You can create a toolbar by instantiating the javafx.scene.control.ToolBar class. The following Example demonstrates the creation of a ToolBar. import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Separator; import javafx.scene.control.ToolBar; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class ToolBarExample extends Application { public void start(Stage stage) { Button bt1 = new Button("Java"); Button bt2 = new Button("JavaFX"); Separator sep1 = new Separator(); Button bt3 = new Button("Neo4J"); Button bt4 = new Button("MongoDB"); Separator sep2 = new Separator(); Button bt5 = new Button("Python"); Button bt6 = new Button("C++"); //Creating a tool bar ToolBar toolBar = new ToolBar(); //Retrieving the items list of the toolbar ObservableList list = toolBar.getItems(); list.addAll(bt1, bt2, sep1, bt3, bt4, sep2, bt5, bt6); //Creating a vbox to hold the pagination VBox vbox = new VBox(); vbox.setSpacing(15); vbox.setPadding(new Insets(50, 50, 50, 100)); vbox.getChildren().addAll(toolBar); //Setting the stage Scene scene = new Scene(new Group(vbox), 595, 150, Color.BEIGE); stage.setTitle("Tool Bar"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1362, "s": 1062, "text": "A toolbar is used to display UI elements such as buttons, toggle buttons, and separators, etc.. You cannot add any other nodes to a toolbar. The contents of a toolbar can be arranged either horizontally or vertically. You can create a toolbar by instantiating the javafx.scene.control.ToolBar class." }, { "code": null, "e": 1424, "s": 1362, "text": "The following Example demonstrates the creation of a ToolBar." }, { "code": null, "e": 2880, "s": 1424, "text": "import javafx.application.Application;\nimport javafx.collections.ObservableList;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.Separator;\nimport javafx.scene.control.ToolBar;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ToolBarExample extends Application {\n public void start(Stage stage) {\n Button bt1 = new Button(\"Java\");\n Button bt2 = new Button(\"JavaFX\");\n Separator sep1 = new Separator();\n Button bt3 = new Button(\"Neo4J\");\n Button bt4 = new Button(\"MongoDB\");\n Separator sep2 = new Separator();\n Button bt5 = new Button(\"Python\");\n Button bt6 = new Button(\"C++\");\n //Creating a tool bar\n ToolBar toolBar = new ToolBar();\n //Retrieving the items list of the toolbar\n ObservableList list = toolBar.getItems();\n list.addAll(bt1, bt2, sep1, bt3, bt4, sep2, bt5, bt6);\n //Creating a vbox to hold the pagination\n VBox vbox = new VBox();\n vbox.setSpacing(15);\n vbox.setPadding(new Insets(50, 50, 50, 100));\n vbox.getChildren().addAll(toolBar);\n //Setting the stage\n Scene scene = new Scene(new Group(vbox), 595, 150, Color.BEIGE);\n stage.setTitle(\"Tool Bar\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Angular7 - Project Setup
In this chapter, we shall discuss about the Project Setup in Angular 7. To get started with the project setup, make sure you have nodejs installed. You can check the version of node in the command line using the command, node –v, as shown below − If you do not get the version, install nodejs from their official site −https://nodejs.org/en/. Once you have nodejs installed, npm will also get installed with it. To check npm version, run npm -v in command line as shown below − So we have node version 10 and npm version 6.4.1. To install Angular 7, go to the site, https://cli.angular.io to install Angular CLI. You will see the following commands on the webpage − npm install -g @angular/cli //command to install angular 7 ng new my-dream-app // name of the project cd my-dream-app ng serve The above commands help to get the project setup in Angular 7. We will create a folder called projectA7 and install angular/cli as shown below − Once the installation is done, check the details of the packages installed by using the command ng version as shown below − It gives the version for Angular CLI, typescript version and other packages available for Angular 7. We are done with the installation of Angular 7, now we will start with the project setup. To create a project in Angular 7, we will use the following command − ng new projectname You can use the projectname of your choice. Let us now run the above command in the command line. Here, we use the projectname as angular7-app. Once you run the command it will ask you about routing as shown below − Type y to add routing to your project setup. The next question is about the stylesheet − The options available are CSS, Sass, Less and Stylus. In the above screenshot, the arrow is on CSS. To change, you can use arrow keys to select the one required for your project setup. At present, we shall discuss CSS for our project-setup. The project angular7-app is created successfully. It installs all the required packages necessary for our project to run in Angular7. Let us now switch to the project created, which is in the directory angular7-app. Change the directory in the command line using the given line of code − cd angular7-app We will use Visual Studio Code IDE for working with Angular 7, you can use any IDE, i.e., Atom, WebStorm, etc. To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows. Click Download for Windows for installing the IDE and run the setup to start using IDE. Following is the Editor − We have not started any project in it. Let us now take the project we have created using angular-cli. We will consider the angular7-app project. Let us open the angular7-app and see how the folder structure looks like. Now that we have the file structure for our project, let us compile our project with the following command − ng serve The ng serve command builds the application and starts the web server. You will see the below when the command starts executing − The web server starts on port 4200. Type the url, "http://localhost:4200/" in the browser and see the output. Once the project is compiled, you will receive the following output − Once you run url, http://localhost:4200/ in the browser, you will be directed to the following screen − Let us now make some changes to display the following content − “Welcome to Angular 7!” We have made changes in the files − app.component.html and app.component.ts. We will discuss more about this in our subsequent chapters. Let us complete the project setup. If you see we have used port 4200, which is the default port that angular–cli makes use of while compiling. You can change the port if you wish using the following command − ng serve --host 0.0.0.0 –port 4205 The angular7-app/ folder has the following folder structure− e2e/ − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine. e2e/ − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine. node_modules/ − The npm package installed is node_modules. You can open the folder and see the packages available. node_modules/ − The npm package installed is node_modules. You can open the folder and see the packages available. src/ − This folder is where we will work on the project using Angular 7.Inside src/ you will app/ folder created during the project setup and holds all the required files required for the project. src/ − This folder is where we will work on the project using Angular 7.Inside src/ you will app/ folder created during the project setup and holds all the required files required for the project. The angular7-app/ folder has the following file structure − angular.json − It basically holds the project name, version of cli, etc. angular.json − It basically holds the project name, version of cli, etc. .editorconfig − This is the config file for the editor. .editorconfig − This is the config file for the editor. .gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository. .gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository. package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install. package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install. At present, if you open the file package.json in the editor, you will get the following modules added in it − "@angular/animations": "~7.2.0", "@angular/common": "~7.2.0", "@angular/compiler": "~7.2.0", "@angular/core": "~7.2.0", "@angular/forms": "~7.2.0", "@angular/platform-browser": "~7.2.0", "@angular/platform-browser-dynamic": "~7.2.0", "@angular/router": "~7.2.0", "core-js": "^2.5.4", "rxjs": "~6.3.3", "tslib": "^1.9.0", "zone.js": "~0.8.26" In case you need to add more libraries, you can add those over here and run the npm install command. tsconfig.json − This basically contains the compiler options required during compilation. tsconfig.json − This basically contains the compiler options required during compilation. tslint.json − This is the config file with rules to be considered while compiling. tslint.json − This is the config file with rules to be considered while compiling. The src/ folder is the main folder, which internally has a different file structure. It contains the files described below. These files are installed by angular-cli by default. If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import: angular/core, platform-browser. The names itself explain the usage of the libraries. They are imported and saved into variables such as declarations, imports, providers, and bootstrap. We can see app-routing.module is also added. This is because we had selected routing at the start of the installation. The module is added by @angular/cli. Following is the structure of the file − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } @NgModule is imported from @angular/core and it has object with following properties − Declarations − In declarations, the reference to the components is stored. The App component is the default component that is created whenever a new project is initiated. We will learn about creating new components in a different section. Imports − This will have the modules imported as shown above. At present, BrowserModule is part of the imports which is imported from @angular/platform-browser. There is also routing module added AppRoutingModule. Providers − This will have reference to the services created. The service will be discussed in a subsequent chapter. Bootstrap − This has reference to the default component created, i.e., AppComponent. app.component.css − You can write your css over here. Right now, we have added the background color to the div as shown below. The structure of the file is as follows − .divdetails { background-color: #ccc; } The html code will be available in this file. The structure of the file is as follows − <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1>Welcome to {{ title }}!</h1> <img width = "300" alt = "Angular Logo" src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZp ZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA 2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBma WxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSA zMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2 wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3I DQwLjl6IiAvPgogIDwvc3ZnPg=="7> </div> <h2>Here are some links to help you start:</h2> <ul> <li> <h2><a target = "_blank" rel = "noopener" href = "https://angular.io/tutorial">Tour of Heroes</a> </h2> </li> <li> <h2><a target = "_blank" rel = "noopener" href = https://angular.io/cli">CLI Documentation</> </h2> </li> <li> <h2><a target = "_blank" rel = "noopener" href = "https://blog.angular.io/">Angular blog</a> </h2> </li> </ul> <router-outlet></router-outlet> This is the default html code currently available with the project creation. These are automatically generated files which contain unit tests for source component. The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc. The structure of the file is as follows − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7'; } This file will deal with the routing required for your project. It is connected with the main module, i.e., app.module.ts. The structure of the file is as follows − import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } You can save your images, js files in this folder. This folder has details for the production or the dev environment. The folder contains two files. environment.prod.ts environment.ts Both the files have details of whether the final file should be compiled in the production environment or the dev environment. The additional file structure of angular7-app/ folder includes the following − This is a file that is usually found in the root directory of a website. This is the file which is displayed in the browser. <html lang = "en"> <head> <meta charset = "utf-8"7gt; <title>Angular7App</title> <base href = "/"> <meta name = "viewport" content = "width=device-width, initial-scale=1"> <link rel = "icon" type = "image/x-icon" href = "favicon.ico"> </head> <body> <app-root></app-root> </body> </html> The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will display the details from app.component.html file. main.ts is the file from where we start our project development. It starts with importing the basic module which we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is imported by default during angular-cli installation and project setup. import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err)); The platformBrowserDynamic().bootstrapModule(AppModule) has the parent module reference AppModule. Hence, when it executes in the browser, the file is called index.html. Index.html internally refers to main.ts which calls the parent module, i.e., AppModule when the following code executes − platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err)); When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the bootstrap as follows − bootstrap: [AppComponent] In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the contents present in app.component.html. The following will be displayed in the browser − This is mainly used for backward compatibility. This is the style file required for the project. Here, the unit test cases for testing the project will be handled. This is used during compilation, it has the config details that need to be used to run the application. This helps maintain the details for testing. It is used to manage the Typescript definition. The final file structure will be as follows − 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 2061, "text": "In this chapter, we shall discuss about the Project Setup in Angular 7." }, { "code": null, "e": 2308, "s": 2133, "text": "To get started with the project setup, make sure you have nodejs installed. You can check the version of node in the command line using the command, node –v, as shown below −" }, { "code": null, "e": 2405, "s": 2308, "text": "If you do not get the version, install nodejs from their official site −https://nodejs.org/en/.\n" }, { "code": null, "e": 2540, "s": 2405, "text": "Once you have nodejs installed, npm will also get installed with it. To check npm version, run npm -v in command line as shown below −" }, { "code": null, "e": 2590, "s": 2540, "text": "So we have node version 10 and npm version 6.4.1." }, { "code": null, "e": 2675, "s": 2590, "text": "To install Angular 7, go to the site, https://cli.angular.io to install Angular CLI." }, { "code": null, "e": 2728, "s": 2675, "text": "You will see the following commands on the webpage −" }, { "code": null, "e": 2856, "s": 2728, "text": "npm install -g @angular/cli //command to install angular 7\nng new my-dream-app // name of the project\ncd my-dream-app\nng serve\n" }, { "code": null, "e": 2919, "s": 2856, "text": "The above commands help to get the project setup in Angular 7." }, { "code": null, "e": 3001, "s": 2919, "text": "We will create a folder called projectA7 and install angular/cli as shown below −" }, { "code": null, "e": 3125, "s": 3001, "text": "Once the installation is done, check the details of the packages installed by using the command ng version as shown below −" }, { "code": null, "e": 3226, "s": 3125, "text": "It gives the version for Angular CLI, typescript version and other packages available for Angular 7." }, { "code": null, "e": 3316, "s": 3226, "text": "We are done with the installation of Angular 7, now we will start with the project setup." }, { "code": null, "e": 3386, "s": 3316, "text": "To create a project in Angular 7, we will use the following command −" }, { "code": null, "e": 3406, "s": 3386, "text": "ng new projectname\n" }, { "code": null, "e": 3504, "s": 3406, "text": "You can use the projectname of your choice. Let us now run the above command in the command line." }, { "code": null, "e": 3622, "s": 3504, "text": "Here, we use the projectname as angular7-app. Once you run the command it will ask you about routing as shown below −" }, { "code": null, "e": 3667, "s": 3622, "text": "Type y to add routing to your project setup." }, { "code": null, "e": 3711, "s": 3667, "text": "The next question is about the stylesheet −" }, { "code": null, "e": 3952, "s": 3711, "text": "The options available are CSS, Sass, Less and Stylus. In the above screenshot, the arrow is on CSS. To change, you can use arrow keys to select the one required for your project setup. At present, we shall discuss CSS for our project-setup." }, { "code": null, "e": 4168, "s": 3952, "text": "The project angular7-app is created successfully. It installs all the required packages necessary for our project to run in Angular7. Let us now switch to the project created, which is in the directory angular7-app." }, { "code": null, "e": 4240, "s": 4168, "text": "Change the directory in the command line using the given line of code −" }, { "code": null, "e": 4257, "s": 4240, "text": "cd angular7-app\n" }, { "code": null, "e": 4368, "s": 4257, "text": "We will use Visual Studio Code IDE for working with Angular 7, you can use any IDE, i.e., Atom, WebStorm, etc." }, { "code": null, "e": 4469, "s": 4368, "text": "To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows." }, { "code": null, "e": 4557, "s": 4469, "text": "Click Download for Windows for installing the IDE and run the setup to start using IDE." }, { "code": null, "e": 4583, "s": 4557, "text": "Following is the Editor −" }, { "code": null, "e": 4685, "s": 4583, "text": "We have not started any project in it. Let us now take the project we have created using angular-cli." }, { "code": null, "e": 4802, "s": 4685, "text": "We will consider the angular7-app project. Let us open the angular7-app and see how the folder structure looks like." }, { "code": null, "e": 4911, "s": 4802, "text": "Now that we have the file structure for our project, let us compile our project with the following command −" }, { "code": null, "e": 4921, "s": 4911, "text": "ng serve\n" }, { "code": null, "e": 4992, "s": 4921, "text": "The ng serve command builds the application and starts the web server." }, { "code": null, "e": 5051, "s": 4992, "text": "You will see the below when the command starts executing −" }, { "code": null, "e": 5232, "s": 5051, "text": "The web server starts on port 4200. Type the url, \"http://localhost:4200/\" in the browser and see the output. Once the project is compiled, you will receive the following output −" }, { "code": null, "e": 5336, "s": 5232, "text": "Once you run url, http://localhost:4200/ in the browser, you will be directed to the following screen −" }, { "code": null, "e": 5400, "s": 5336, "text": "Let us now make some changes to display the following content −" }, { "code": null, "e": 5424, "s": 5400, "text": "“Welcome to Angular 7!”" }, { "code": null, "e": 5561, "s": 5424, "text": "We have made changes in the files − app.component.html and app.component.ts. We will discuss more about this in our subsequent chapters." }, { "code": null, "e": 5770, "s": 5561, "text": "Let us complete the project setup. If you see we have used port 4200, which is the default port that angular–cli makes use of while compiling. You can change the port if you wish using the following command −" }, { "code": null, "e": 5806, "s": 5770, "text": "ng serve --host 0.0.0.0 –port 4205\n" }, { "code": null, "e": 5867, "s": 5806, "text": "The angular7-app/ folder has the following folder structure−" }, { "code": null, "e": 5986, "s": 5867, "text": "e2e/ − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine." }, { "code": null, "e": 6105, "s": 5986, "text": "e2e/ − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine." }, { "code": null, "e": 6220, "s": 6105, "text": "node_modules/ − The npm package installed is node_modules. You can open the folder and see the packages available." }, { "code": null, "e": 6335, "s": 6220, "text": "node_modules/ − The npm package installed is node_modules. You can open the folder and see the packages available." }, { "code": null, "e": 6532, "s": 6335, "text": "src/ − This folder is where we will work on the project using Angular 7.Inside src/ you will app/ folder created during the project setup and holds all the required files required for the project." }, { "code": null, "e": 6729, "s": 6532, "text": "src/ − This folder is where we will work on the project using Angular 7.Inside src/ you will app/ folder created during the project setup and holds all the required files required for the project." }, { "code": null, "e": 6789, "s": 6729, "text": "The angular7-app/ folder has the following file structure −" }, { "code": null, "e": 6862, "s": 6789, "text": "angular.json − It basically holds the project name, version of cli, etc." }, { "code": null, "e": 6935, "s": 6862, "text": "angular.json − It basically holds the project name, version of cli, etc." }, { "code": null, "e": 6991, "s": 6935, "text": ".editorconfig − This is the config file for the editor." }, { "code": null, "e": 7047, "s": 6991, "text": ".editorconfig − This is the config file for the editor." }, { "code": null, "e": 7202, "s": 7047, "text": ".gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository." }, { "code": null, "e": 7357, "s": 7202, "text": ".gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository." }, { "code": null, "e": 7478, "s": 7357, "text": "package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install." }, { "code": null, "e": 7599, "s": 7478, "text": "package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install." }, { "code": null, "e": 7709, "s": 7599, "text": "At present, if you open the file package.json in the editor, you will get the following modules added in it −" }, { "code": null, "e": 8063, "s": 7709, "text": "\"@angular/animations\": \"~7.2.0\", \n\"@angular/common\": \"~7.2.0\", \n\"@angular/compiler\": \"~7.2.0\", \n\"@angular/core\": \"~7.2.0\", \n\"@angular/forms\": \"~7.2.0\", \n\"@angular/platform-browser\": \"~7.2.0\", \n\"@angular/platform-browser-dynamic\": \"~7.2.0\", \n\"@angular/router\": \"~7.2.0\", \n\"core-js\": \"^2.5.4\", \n\"rxjs\": \"~6.3.3\", \n\"tslib\": \"^1.9.0\", \n\"zone.js\": \"~0.8.26\"\n" }, { "code": null, "e": 8164, "s": 8063, "text": "In case you need to add more libraries, you can add those over here and run the npm install command." }, { "code": null, "e": 8254, "s": 8164, "text": "tsconfig.json − This basically contains the compiler options required during compilation." }, { "code": null, "e": 8344, "s": 8254, "text": "tsconfig.json − This basically contains the compiler options required during compilation." }, { "code": null, "e": 8427, "s": 8344, "text": "tslint.json − This is the config file with rules to be considered while compiling." }, { "code": null, "e": 8510, "s": 8427, "text": "tslint.json − This is the config file with rules to be considered while compiling." }, { "code": null, "e": 8595, "s": 8510, "text": "The src/ folder is the main folder, which internally has a different file structure." }, { "code": null, "e": 8687, "s": 8595, "text": "It contains the files described below. These files are installed by angular-cli by default." }, { "code": null, "e": 8887, "s": 8687, "text": "If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import: angular/core, platform-browser." }, { "code": null, "e": 9040, "s": 8887, "text": "The names itself explain the usage of the libraries. They are imported and saved into variables such as declarations, imports, providers, and bootstrap." }, { "code": null, "e": 9196, "s": 9040, "text": "We can see app-routing.module is also added. This is because we had selected routing at the start of the installation. The module is added by @angular/cli." }, { "code": null, "e": 9237, "s": 9196, "text": "Following is the structure of the file −" }, { "code": null, "e": 9641, "s": 9237, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n AppRoutingModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 9728, "s": 9641, "text": "@NgModule is imported from @angular/core and it has object with following properties −" }, { "code": null, "e": 9967, "s": 9728, "text": "Declarations − In declarations, the reference to the components is stored. The App component is the default component that is created whenever a new project is initiated. We will learn about creating new components in a different section." }, { "code": null, "e": 10181, "s": 9967, "text": "Imports − This will have the modules imported as shown above. At present, BrowserModule is part of the imports which is imported from @angular/platform-browser. There is also routing module added AppRoutingModule." }, { "code": null, "e": 10298, "s": 10181, "text": "Providers − This will have reference to the services created. The service will be discussed in a subsequent chapter." }, { "code": null, "e": 10383, "s": 10298, "text": "Bootstrap − This has reference to the default component created, i.e., AppComponent." }, { "code": null, "e": 10510, "s": 10383, "text": "app.component.css − You can write your css over here. Right now, we have added the background color to the div as shown below." }, { "code": null, "e": 10552, "s": 10510, "text": "The structure of the file is as follows −" }, { "code": null, "e": 10597, "s": 10552, "text": ".divdetails {\n background-color: #ccc; \n}\n" }, { "code": null, "e": 10643, "s": 10597, "text": "The html code will be available in this file." }, { "code": null, "e": 10685, "s": 10643, "text": "The structure of the file is as follows −" }, { "code": null, "e": 11961, "s": 10685, "text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"text-align:center\">\n <h1>Welcome to {{ title }}!</h1> \n <img width = \"300\" alt = \"Angular Logo\" \n src = \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZp\n ZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA\n 2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBma\n WxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSA\n zMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2\n wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3I\n DQwLjl6IiAvPgogIDwvc3ZnPg==\"7> \n</div> \n\n<h2>Here are some links to help you start:</h2> \n<ul> \n <li> \n <h2><a target = \"_blank\" rel = \"noopener\" \n href = \"https://angular.io/tutorial\">Tour of Heroes</a>\n </h2>\n </li> \n <li> \n <h2><a target = \"_blank\" rel = \"noopener\" \n href = https://angular.io/cli\">CLI Documentation</>\n </h2> \n </li> \n <li> \n <h2><a target = \"_blank\" rel = \"noopener\" \n href = \"https://blog.angular.io/\">Angular blog</a>\n </h2> \n </li> \n</ul> \n<router-outlet></router-outlet>" }, { "code": null, "e": 12038, "s": 11961, "text": "This is the default html code currently available with the project creation." }, { "code": null, "e": 12125, "s": 12038, "text": "These are automatically generated files which contain unit tests for source component." }, { "code": null, "e": 12374, "s": 12125, "text": "The class for the component is defined over here. You can do the processing of the html structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc." }, { "code": null, "e": 12416, "s": 12374, "text": "The structure of the file is as follows −" }, { "code": null, "e": 12637, "s": 12416, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n})\nexport class AppComponent { \n title = 'Angular 7';\n}" }, { "code": null, "e": 12760, "s": 12637, "text": "This file will deal with the routing required for your project. It is connected with the main module, i.e., app.module.ts." }, { "code": null, "e": 12802, "s": 12760, "text": "The structure of the file is as follows −" }, { "code": null, "e": 13053, "s": 12802, "text": "import { NgModule } from '@angular/core'; \nimport { Routes, RouterModule } from '@angular/router';\n\nconst routes: Routes = [];\n@NgModule({ \n imports: [RouterModule.forRoot(routes)], \n exports: [RouterModule] \n}) \nexport class AppRoutingModule { }" }, { "code": null, "e": 13104, "s": 13053, "text": "You can save your images, js files in this folder." }, { "code": null, "e": 13202, "s": 13104, "text": "This folder has details for the production or the dev environment. The folder contains two files." }, { "code": null, "e": 13222, "s": 13202, "text": "environment.prod.ts" }, { "code": null, "e": 13237, "s": 13222, "text": "environment.ts" }, { "code": null, "e": 13364, "s": 13237, "text": "Both the files have details of whether the final file should be compiled in the production environment or the dev environment." }, { "code": null, "e": 13443, "s": 13364, "text": "The additional file structure of angular7-app/ folder includes the following −" }, { "code": null, "e": 13516, "s": 13443, "text": "This is a file that is usually found in the root directory of a website." }, { "code": null, "e": 13568, "s": 13516, "text": "This is the file which is displayed in the browser." }, { "code": null, "e": 13912, "s": 13568, "text": "<html lang = \"en\"> \n <head>\n <meta charset = \"utf-8\"7gt;\n <title>Angular7App</title> \n <base href = \"/\">\n <meta name = \"viewport\" content = \"width=device-width, initial-scale=1\"> \n <link rel = \"icon\" type = \"image/x-icon\" href = \"favicon.ico\"> \n </head> \n <body> \n <app-root></app-root> \n </body> \n</html>" }, { "code": null, "e": 14067, "s": 13912, "text": "The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will display the details from app.component.html file." }, { "code": null, "e": 14359, "s": 14067, "text": "main.ts is the file from where we start our project development. It starts with importing the basic module which we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is imported by default during angular-cli installation and project setup." }, { "code": null, "e": 14730, "s": 14359, "text": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { AppModule } from './app/app.module'; \nimport { environment } from './environments/environment';\n\nif (environment.production) { \n enableProdMode(); \n}\nplatformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));" }, { "code": null, "e": 15022, "s": 14730, "text": "The platformBrowserDynamic().bootstrapModule(AppModule) has the parent module reference AppModule. Hence, when it executes in the browser, the file is called index.html. Index.html internally refers to main.ts which calls the parent module, i.e., AppModule when the following code executes −" }, { "code": null, "e": 15109, "s": 15022, "text": "platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));\n" }, { "code": null, "e": 15231, "s": 15109, "text": "When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the bootstrap as follows −" }, { "code": null, "e": 15258, "s": 15231, "text": "bootstrap: [AppComponent]\n" }, { "code": null, "e": 15409, "s": 15258, "text": "In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the contents present in app.component.html." }, { "code": null, "e": 15458, "s": 15409, "text": "The following will be displayed in the browser −" }, { "code": null, "e": 15506, "s": 15458, "text": "This is mainly used for backward compatibility." }, { "code": null, "e": 15555, "s": 15506, "text": "This is the style file required for the project." }, { "code": null, "e": 15622, "s": 15555, "text": "Here, the unit test cases for testing the project will be handled." }, { "code": null, "e": 15726, "s": 15622, "text": "This is used during compilation, it has the config details that need to be used to run the application." }, { "code": null, "e": 15771, "s": 15726, "text": "This helps maintain the details for testing." }, { "code": null, "e": 15819, "s": 15771, "text": "It is used to manage the Typescript definition." }, { "code": null, "e": 15865, "s": 15819, "text": "The final file structure will be as follows −" }, { "code": null, "e": 15900, "s": 15865, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 15914, "s": 15900, "text": " Anadi Sharma" }, { "code": null, "e": 15949, "s": 15914, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 15963, "s": 15949, "text": " Anadi Sharma" }, { "code": null, "e": 15998, "s": 15963, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 16018, "s": 15998, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 16053, "s": 16018, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 16070, "s": 16053, "text": " Frahaan Hussain" }, { "code": null, "e": 16103, "s": 16070, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 16115, "s": 16103, "text": " Senol Atac" }, { "code": null, "e": 16150, "s": 16115, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 16162, "s": 16150, "text": " Senol Atac" }, { "code": null, "e": 16169, "s": 16162, "text": " Print" }, { "code": null, "e": 16180, "s": 16169, "text": " Add Notes" } ]
Peak element | Practice | GeeksforGeeks
An element is called a peak element if its value is not smaller than the value of its adjacent elements(if they exists). Given an array arr[] of size N, find the index of any one of its peak elements. Note: The generated output will always be 1 if the index that you return is correct. Otherwise output will be 0. Example 1: Input: N = 3 arr[] = {1,2,3} Output: 2 Explanation: index 2 is 3. It is the peak element as it is greater than its neighbour 2. Example 2: Input: N = 2 arr[] = {3,4} Output: 1 Explanation: 4 (at index 1) is the peak element as it is greater than its only neighbour element 3. Your Task: You don't have to read input or print anything. Complete the function peakElement() which takes the array arr[] and its size N as input parameters and return the index of any one of its peak elements. Can you solve the problem in expected time complexity? Expected Time Complexity: O(log N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 105 1 ≤ A[] ≤ 106 -2 kashyapjhon17 hours ago C++ Solution Time=(0.25/1.48) EASY: int peakElement(int arr[], int n) { // Your code here if(n==1){ return 0; } else{ for(int i=0;i<n;i++){ if(i==0 && arr[i]>arr[i+1]){ return i; } if(i>0 && i<n-1 && arr[i]>arr[i-1] && arr[i]>arr[i+1]){ return i; } if(i==n-1 && arr[i]>arr[n-2]){ return i; } } return 0; } } 0 keith91911 day ago public int peakElement(int[] arr,int n) { //add code here. int pointer = 0; while(pointer < n){ //boolean isPeak = false; int left = pointer - 1 > 0 ? arr[pointer -1] : Integer.MIN_VALUE; int right = pointer + 1 < n ? arr[pointer + 1] : Integer.MIN_VALUE; if(arr[pointer] > left && arr[pointer] > right) { return pointer; } pointer++; } return 0; } 0 kalaiabster2 days ago JAVA SOLUTION Time Taken(1.51/3.86) public int peakElement(int[] arr,int n) { int out=0; for(int i=0;i<arr.length-1;i++) { if(arr[i]<arr[i+1]) { out=i+1; } } return out; } +1 aradgast12 days ago how can i solve it in O(logN)? unless the array is sorted and then it's clear... 0 sahithichowdhary93 days ago class Solution{// Function to find the peak element// arr[]: input array// n: size of array a[]public int peakElement(int[] arr,int n) { //add code here. int j=0; HashMap<Integer,Integer>map=new HashMap<>(); for(int i=0;i<n-1;i++) { if(arr[i+1]>arr[i]) { j=i+1; map.put(j,i+1); } } map.get(j); return j; } } 0 vishal8579943 days ago ///O(n) in java public int peakElement(int[] arr,int n) { //add code here. int low=0;int high=n-1; while(low<=high){ int mid=high-(high-low)/2; if((mid==0 || arr[mid]>=arr[mid-1])&&(mid==n-1 ||arr[mid]>=arr[mid+1])){ return mid; } if(mid>0 && arr[mid-1]>=arr[mid]){ high=mid-1; }else{ low=mid+1; } } return -1; } +1 riteshthakare11913 days ago For begineer: int peakElement(int arr[], int n) { if (arr[0]>arr[1]){ return 0; } if (arr[n-1]>arr[n-2]){ return n-1; } for (int i=1;i<=(n-2);i++){ if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){ return i; } } return 0; // Your code here } 0 mankesh0163 days ago O(log N) solution public: int findPeak(int arr[],int st, int end){ if(st==end) return st; int mid=(st+end)/2; if(arr[mid]<arr[mid+1]) return findPeak(arr,mid+1,end); else if(arr[mid]<arr[mid-1]) return findPeak(arr,st,mid-1); else return mid; } int peakElement(int arr[], int n) { // Your code here return findPeak(arr,0,n-1); } 0 mankesh016 This comment was deleted. 0 mankesh0163 days ago O(logN) solution c++ int findPeak( int arr[ ], int st, int end){ if(st==end) return st ; int mid=(st+end)/2; if (arr[mid]<arr[mid+1]) return findPeak(arr,mid+1,end); else if (arr[mid]<arr[mid-1]) return findPeak(arr, st, mid-1); else return mid; } int peakElement(int arr[], int n){ // Your code here return findPeak(arr,0,n-1); } 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": 553, "s": 238, "text": "An element is called a peak element if its value is not smaller than the value of its adjacent elements(if they exists).\nGiven an array arr[] of size N, find the index of any one of its peak elements.\nNote: The generated output will always be 1 if the index that you return is correct. Otherwise output will be 0. " }, { "code": null, "e": 565, "s": 553, "text": "\nExample 1:" }, { "code": null, "e": 695, "s": 565, "text": "Input:\nN = 3\narr[] = {1,2,3}\nOutput: 2\nExplanation: index 2 is 3.\nIt is the peak element as it is \ngreater than its neighbour 2.\n" }, { "code": null, "e": 706, "s": 695, "text": "Example 2:" }, { "code": null, "e": 846, "s": 706, "text": "Input:\nN = 2\narr[] = {3,4}\nOutput: 1\nExplanation: 4 (at index 1) is the \npeak element as it is greater than \nits only neighbour element 3.\n" }, { "code": null, "e": 1116, "s": 848, "text": "Your Task:\nYou don't have to read input or print anything. Complete the function peakElement() which takes the array arr[] and its size N as input parameters and return the index of any one of its peak elements.\n\nCan you solve the problem in expected time complexity?" }, { "code": null, "e": 1184, "s": 1118, "text": "Expected Time Complexity: O(log N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1224, "s": 1184, "text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ A[] ≤ 106" }, { "code": null, "e": 1227, "s": 1224, "text": "-2" }, { "code": null, "e": 1251, "s": 1227, "text": "kashyapjhon17 hours ago" }, { "code": null, "e": 1287, "s": 1251, "text": "C++ Solution Time=(0.25/1.48) EASY:" }, { "code": null, "e": 1753, "s": 1287, "text": "int peakElement(int arr[], int n) { // Your code here if(n==1){ return 0; } else{ for(int i=0;i<n;i++){ if(i==0 && arr[i]>arr[i+1]){ return i; } if(i>0 && i<n-1 && arr[i]>arr[i-1] && arr[i]>arr[i+1]){ return i; } if(i==n-1 && arr[i]>arr[n-2]){ return i; } } return 0; } }" }, { "code": null, "e": 1755, "s": 1753, "text": "0" }, { "code": null, "e": 1774, "s": 1755, "text": "keith91911 day ago" }, { "code": null, "e": 2268, "s": 1774, "text": "public int peakElement(int[] arr,int n) { //add code here. int pointer = 0; while(pointer < n){ //boolean isPeak = false; int left = pointer - 1 > 0 ? arr[pointer -1] : Integer.MIN_VALUE; int right = pointer + 1 < n ? arr[pointer + 1] : Integer.MIN_VALUE; if(arr[pointer] > left && arr[pointer] > right) { return pointer; } pointer++; } return 0; }" }, { "code": null, "e": 2270, "s": 2268, "text": "0" }, { "code": null, "e": 2292, "s": 2270, "text": "kalaiabster2 days ago" }, { "code": null, "e": 2328, "s": 2292, "text": "JAVA SOLUTION Time Taken(1.51/3.86)" }, { "code": null, "e": 2534, "s": 2328, "text": "public int peakElement(int[] arr,int n) { int out=0; for(int i=0;i<arr.length-1;i++) { if(arr[i]<arr[i+1]) { out=i+1; } } return out; }" }, { "code": null, "e": 2539, "s": 2536, "text": "+1" }, { "code": null, "e": 2559, "s": 2539, "text": "aradgast12 days ago" }, { "code": null, "e": 2640, "s": 2559, "text": "how can i solve it in O(logN)? unless the array is sorted and then it's clear..." }, { "code": null, "e": 2642, "s": 2640, "text": "0" }, { "code": null, "e": 2670, "s": 2642, "text": "sahithichowdhary93 days ago" }, { "code": null, "e": 3070, "s": 2670, "text": "class Solution{// Function to find the peak element// arr[]: input array// n: size of array a[]public int peakElement(int[] arr,int n) { //add code here. int j=0; HashMap<Integer,Integer>map=new HashMap<>(); for(int i=0;i<n-1;i++) { if(arr[i+1]>arr[i]) { j=i+1; map.put(j,i+1); } } map.get(j); return j; }" }, { "code": null, "e": 3072, "s": 3070, "text": "}" }, { "code": null, "e": 3074, "s": 3072, "text": "0" }, { "code": null, "e": 3097, "s": 3074, "text": "vishal8579943 days ago" }, { "code": null, "e": 3113, "s": 3097, "text": "///O(n) in java" }, { "code": null, "e": 3534, "s": 3113, "text": " public int peakElement(int[] arr,int n) { //add code here. int low=0;int high=n-1; while(low<=high){ int mid=high-(high-low)/2; if((mid==0 || arr[mid]>=arr[mid-1])&&(mid==n-1 ||arr[mid]>=arr[mid+1])){ return mid; } if(mid>0 && arr[mid-1]>=arr[mid]){ high=mid-1; }else{ low=mid+1; } } return -1; }" }, { "code": null, "e": 3537, "s": 3534, "text": "+1" }, { "code": null, "e": 3565, "s": 3537, "text": "riteshthakare11913 days ago" }, { "code": null, "e": 3579, "s": 3565, "text": "For begineer:" }, { "code": null, "e": 3916, "s": 3579, "text": "int peakElement(int arr[], int n) { if (arr[0]>arr[1]){ return 0; } if (arr[n-1]>arr[n-2]){ return n-1; } for (int i=1;i<=(n-2);i++){ if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){ return i; } } return 0; // Your code here }" }, { "code": null, "e": 3920, "s": 3918, "text": "0" }, { "code": null, "e": 3941, "s": 3920, "text": "mankesh0163 days ago" }, { "code": null, "e": 3959, "s": 3941, "text": "O(log N) solution" }, { "code": null, "e": 4370, "s": 3959, "text": "public:\n int findPeak(int arr[],int st, int end){\n if(st==end) return st;\n \n int mid=(st+end)/2;\n \n if(arr[mid]<arr[mid+1]) return findPeak(arr,mid+1,end);\n else if(arr[mid]<arr[mid-1]) return findPeak(arr,st,mid-1);\n else return mid;\n }\n int peakElement(int arr[], int n)\n {\n // Your code here\n \n return findPeak(arr,0,n-1);\n }" }, { "code": null, "e": 4374, "s": 4372, "text": "0" }, { "code": null, "e": 4385, "s": 4374, "text": "mankesh016" }, { "code": null, "e": 4411, "s": 4385, "text": "This comment was deleted." }, { "code": null, "e": 4413, "s": 4411, "text": "0" }, { "code": null, "e": 4434, "s": 4413, "text": "mankesh0163 days ago" }, { "code": null, "e": 4455, "s": 4434, "text": "O(logN) solution c++" }, { "code": null, "e": 4501, "s": 4457, "text": "int findPeak( int arr[ ], int st, int end){" }, { "code": null, "e": 4529, "s": 4501, "text": " if(st==end) return st ;" }, { "code": null, "e": 4552, "s": 4529, "text": " int mid=(st+end)/2;" }, { "code": null, "e": 4588, "s": 4552, "text": " if (arr[mid]<arr[mid+1]) " }, { "code": null, "e": 4641, "s": 4588, "text": " return findPeak(arr,mid+1,end);" }, { "code": null, "e": 4677, "s": 4641, "text": " else if (arr[mid]<arr[mid-1]) " }, { "code": null, "e": 4731, "s": 4677, "text": " return findPeak(arr, st, mid-1);" }, { "code": null, "e": 4762, "s": 4731, "text": " else return mid;" }, { "code": null, "e": 4764, "s": 4762, "text": "}" }, { "code": null, "e": 4799, "s": 4764, "text": "int peakElement(int arr[], int n){" }, { "code": null, "e": 4824, "s": 4799, "text": " // Your code here" }, { "code": null, "e": 4859, "s": 4824, "text": " return findPeak(arr,0,n-1);" }, { "code": null, "e": 4861, "s": 4859, "text": "}" }, { "code": null, "e": 5007, "s": 4861, "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": 5043, "s": 5007, "text": " Login to access your submissions. " }, { "code": null, "e": 5053, "s": 5043, "text": "\nProblem\n" }, { "code": null, "e": 5063, "s": 5053, "text": "\nContest\n" }, { "code": null, "e": 5126, "s": 5063, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5274, "s": 5126, "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": 5482, "s": 5274, "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": 5588, "s": 5482, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Perfect Cube - GeeksforGeeks
30 Nov, 2021 Given a number N, the task is to check whether the given number N is a perfect cube or not. Examples: Input: N = 216 Output: Yes Explanation: As 216 = 6*6*6. Therefore the cube root of 216 is 6.Input: N = 100 Output: No Method 1: Naive Approach The idea is to check for each number from 1 to N if the cube of any of these numbers equals N. If so, then that number is the cube root of N and the N is a perfect cube. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check whether the given// number N is the perfect cube or not.#include <bits/stdc++.h> using namespace std; // Function to check if a number// is a perfect Cube or notvoid perfectCube(int N){ int cube; // Iterate from 1-N for (int i; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube == N) { cout << "Yes"; return; } else if (cube > N) { cout << "NO"; return; } }} // Driver codeint main(){ int N = 216; // Function call perfectCube(N); return 0;} // Java program to check whether the given// number N is the perfect cube or notclass GFG { // Function to check if a number // is a perfect Cube or not static void perfectCube(int N) { int cube; // Iterate from 1-N for (int i = 0; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube == N) { System.out.println("Yes"); return; } else if (cube > N) { System.out.println("NO"); return; } } } // Driver code public static void main (String[] args) { int N = 216; // Function call perfectCube(N); }} // This code is contributed by AnkitRai01 # Python3 program to check whether the given# number N is the perfect cube or not # Function to check if a number# is a perfect Cube or notdef perfectCube(N) : cube = 0; # Iterate from 1-N for i in range(N + 1) : # Find the cube of # every number cube = i * i * i; # Check if cube equals # N or not if (cube == N) : print("Yes"); return; elif (cube > N) : print("NO"); return; # Driver codeif __name__ == "__main__" : N = 216; # Function call perfectCube(N); # This code is contributed by Yash_R // C# program to check whether the given// number N is the perfect cube or notusing System; class GFG { // Function to check if a number // is a perfect Cube or not static void perfectCube(int N) { int cube; // Iterate from 1-N for (int i = 0; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube == N) { Console.WriteLine("Yes"); return; } else if (cube > N) { Console.WriteLine("NO"); return; } } } // Driver code public static void Main (string[] args) { int N = 216; // Function call perfectCube(N); }} // This code is contributed by AnkitRai01 <script> // JavaScript program to check whether the given// number N is the perfect cube or not // Function to check if a number// is a perfect Cube or notfunction perfectCube(N){ let cube; // Iterate from 1-N for(let i = 0; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube === N) { document.write("Yes"); return; } else if (cube > N) { document.write("NO"); return; } }} // Driver codelet N = 216; // Function callperfectCube(N); // This code is contributed by Manoj. </script> Yes Time Complexity: O(N) Auxiliary Space: O(1) Method 2: Using inbuilt function The idea is to use the inbuilt function (cbrt()) to find the cube root of a number which returns floor value of the cube root of the number N. If the cube of this number equals N, then N is a perfect cube otherwise N is not a perfect cube. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check whether the given// number N is the perfect cube or not #include <bits/stdc++.h>using namespace std; // Function to check if a number is// a perfect Cube using inbuilt functionvoid perfectCube(int N){ int cube_root; cube_root = round(cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if (cube_root * cube_root * cube_root == N) { cout << "Yes"; return; } else { cout << "NO"; return; }} // Driver's codeint main(){ int N = 125; // Function call to check // N is cube or not perfectCube(N); return 0;} // Java program to check whether the given// number N is the perfect cube or notpublic class GFG { // Function to check if a number is // a perfect Cube using inbuilt function static void perfectCube(int N) { int cube_root; cube_root = (int)Math.round(Math.cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if (cube_root * cube_root * cube_root == N) { System.out.println("Yes"); return; } else { System.out.println("NO"); return; } } // Driver's code public static void main (String[] args) { int N = 125; // Function call to check // N is cube or not perfectCube(N); } }// This code is contributed by AnkitRai01 # Python program to check whether the given# number N is the perfect cube or not # Function to check if a number is# a perfect Cube using inbuilt functiondef perfectCube(N) : cube_root = round(N**(1/3)); # If cube of cube_root is equals to N, # then print Yes Else print No if cube_root * cube_root * cube_root == N : print("Yes"); return; else : print("NO"); return; # Driver's codeif __name__ == "__main__" : N = 125; # Function call to check # N is cube or not perfectCube(N); # This code is contributed by AnkitRai01 // C# program to check whether the given// number N is the perfect cube or notusing System; class GFG { // Function to check if a number is // a perfect Cube using inbuilt function static void perfectCube(int N) { int cube_root; cube_root = (int)Math.Round(Math.Cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if (cube_root * cube_root * cube_root == N) { Console.WriteLine("Yes"); return; } else { Console.WriteLine("NO"); return; } } // Driver's code public static void Main (string[] args) { int N = 125; // Function call to check // N is cube or not perfectCube(N); }} // This code is contributed by AnkitRai01 <script>// Javascript program to check whether the given// number N is the perfect cube or not // Function to check if a number is// a perfect Cube using inbuilt functionfunction perfectCube(N){ let cube_root; cube_root = Math.round(Math.cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if ((cube_root * cube_root * cube_root) == N) { document.write("Yes"); return; } else { document.write("NO"); return; }} // Driver's codelet N = 125; // Function call to check// N is cube or notperfectCube(N); // This code is contributed by subhammahato348.</script> Yes Time Complexity: O(cbrt(N)) Auxiliary Space: O(1) Method 3: Using Prime Factors Find all the Prime Factors of the given number N using the approach in this article.Store the frequency of all the prime factors obtained above in a Hash Map.Traverse the Hash Map and if the frequency of every prime factors is not a multiple of 3, then the given number N is not a perfect cube. Find all the Prime Factors of the given number N using the approach in this article. Store the frequency of all the prime factors obtained above in a Hash Map. Traverse the Hash Map and if the frequency of every prime factors is not a multiple of 3, then the given number N is not a perfect cube. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if a number// is a perfect cube using prime factors#include<bits/stdc++.h>using namespace std; // Inserts the prime factor in HashMap// if not present// if present updates it's frequencymap<int, int> insertPF(map<int, int> primeFact, int fact){ if (primeFact.find(fact) != primeFact.end()) { primeFact[fact]++; } else { primeFact[fact] = 1; } return primeFact;} // A utility function to find all// prime factors of a given number Nmap<int, int> primeFactors (int n){ map<int, int> primeFact; // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n /= 2; } // n must be odd at this point // So we can skip one element for(int i = 3; i <= sqrt(n); i += 2) { // while i divides n, insert // i and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n /= i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact;} // Function to check if a// number is perfect cubestring perfectCube (int n){ map<int, int> primeFact; primeFact = primeFactors(n); // Iteration in Map for(auto x : primeFact) { if (x.second % 3 != 0) return "No"; } return "Yes";} // Driver Codeint main(){ int N = 216; // Function to check if N is // perfect cube or not cout << perfectCube(N); return 0;} // This code is contributed by himanshu77 // Java program to check if a number// is a perfect cube using prime factors import java.io.*;import java.lang.*;import java.util.*; class GFG { // Inserts the prime factor in the Hash Map // if not present // If present updates it's frequency public static HashMap<Integer, Integer> insertPF(HashMap<Integer, Integer> primeFact, int fact) { if (primeFact.containsKey(fact)) { int freq; freq = primeFact.get(fact); primeFact.replace(fact, ++freq); } else { primeFact.put(fact, 1); } return primeFact; } // A utility function to find all // prime factors of a given number N public static HashMap<Integer, Integer> primeFactors(int n) { HashMap<Integer, Integer> primeFact = new HashMap<>(); // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n /= 2; } // n must be odd at this point. // So we can skip one element for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, insert i // and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n /= i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact; } // Function to check if a number // is a perfect cube public static String perfectCube(int n) { HashMap<Integer, Integer> primeFact; primeFact = primeFactors(n); // Using values() for iteration // over keys for (int freq : primeFact.values()) { if (freq % 3 != 0) return "No"; } return "Yes"; } // Driver Code public static void main(String[] args) { int N = 216; // Function to check if N is // perfect cube or not System.out.println(perfectCube(N)); }} # Python3 program to check if a number# is a perfect cube using prime factorsimport math # Inserts the prime factor in HashMap# if not present# if present updates it's frequencydef insertPF(primeFact, fact) : if (fact in primeFact) : primeFact[fact] += 1 else : primeFact[fact] = 1 return primeFact # A utility function to find all# prime factors of a given number Ndef primeFactors (n) : primeFact = {} # Insert the number of 2s # that divide n while (n % 2 == 0) : primeFact = insertPF(primeFact, 2) n = n // 2 # n must be odd at this point # So we can skip one element for i in range(3, int(math.sqrt(n)) + 1, 2) : # while i divides n, insert # i and divide n while (n % i == 0) : primeFact = insertPF(primeFact, i) n = n // i # This condition is to handle # the case when n is a prime # number greater than 2 if (n > 2) : primeFact = insertPF(primeFact, n) return primeFact # Function to check if a # number is perfect cubedef perfectCube (n) : primeFact = {} primeFact = primeFactors(n) # Iteration in Map for x in primeFact : if (primeFact[x] % 3 != 0) : return "No" return "Yes" N = 216 # Function to check if N is# perfect cube or notprint(perfectCube(N)) # This code is contributed by divyeshrabadiya07. // C# program to check if a number// is a perfect cube using prime factors using System;using System.Collections.Generic; public class GFG { // Inserts the prime factor in the Hash Map // if not present // If present updates it's frequency public static Dictionary<int, int> insertPF(Dictionary<int, int> primeFact, int fact) { if (primeFact.ContainsKey(fact)) { int freq; freq = primeFact[fact]; primeFact[fact] = ++freq; } else { primeFact.Add(fact, 1); } return primeFact; } // A utility function to find all // prime factors of a given number N public static Dictionary<int, int> primeFactors(int n) { Dictionary<int, int> primeFact = new Dictionary<int, int>(); // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n /= 2; } // n must be odd at this point. // So we can skip one element for (int i = 3; i <= Math.Sqrt(n); i += 2) { // While i divides n, insert i // and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n /= i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact; } // Function to check if a number // is a perfect cube public static String perfectCube(int n) { Dictionary<int, int> primeFact; primeFact = primeFactors(n); // Using values() for iteration // over keys foreach (int freq in primeFact.Values) { if (freq % 3 != 0) return "No"; } return "Yes"; } // Driver Code public static void Main(String[] args) { int N = 216; // Function to check if N is // perfect cube or not Console.WriteLine(perfectCube(N)); }} // This code is contributed by sapnasingh4991 <script> // Javascript program to check if a number// is a perfect cube using prime factors // Inserts the prime factor in HashMap// if not present// if present updates it's frequencyfunction insertPF(primeFact, fact){ if (primeFact.has(fact)) { primeFact.set(fact, primeFact.get(fact)+1); } else { primeFact.set(fact, 1); } return primeFact;} // A utility function to find all// prime factors of a given number Nfunction primeFactors (n){ var primeFact = new Map(); // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n = parseInt(n/2); } // n must be odd at this point // So we can skip one element for(var i = 3; i <= Math.sqrt(n); i += 2) { // while i divides n, insert // i and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n =parseInt(n/i); } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact;} // Function to check if a// number is perfect cubefunction perfectCube (n){ var primeFact = new Map(); primeFact = primeFactors(n); // Iteration in Map primeFact.forEach((value, key) => { if (value % 3 != 0) return "No"; }); return "Yes";} // Driver Codevar N = 216;// Function to check if N is// perfect cube or notdocument.write( perfectCube(N)); // This code is contributed by rrrtnx.</script> Yes Time Complexity: O(sqrt(n)) Auxiliary Space: O(sqrt(n)) Yash_R ankthon sapnasingh4991 himanshu77 divyeshrabadiya07 subhammahato348 mank1083 rrrtnx souravmahato348 maths-perfect-cube Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Program to find GCD or HCF of two numbers Prime Numbers Modulo Operator (%) in C/C++ with Examples Sieve of Eratosthenes Program for Decimal to Binary Conversion Find all factors of a natural number | Set 1 Modulo 10^9+7 (1000000007) Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 24691, "s": 24663, "text": "\n30 Nov, 2021" }, { "code": null, "e": 24795, "s": 24691, "text": "Given a number N, the task is to check whether the given number N is a perfect cube or not. Examples: " }, { "code": null, "e": 24914, "s": 24795, "text": "Input: N = 216 Output: Yes Explanation: As 216 = 6*6*6. Therefore the cube root of 216 is 6.Input: N = 100 Output: No " }, { "code": null, "e": 25109, "s": 24914, "text": "Method 1: Naive Approach The idea is to check for each number from 1 to N if the cube of any of these numbers equals N. If so, then that number is the cube root of N and the N is a perfect cube." }, { "code": null, "e": 25162, "s": 25109, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25166, "s": 25162, "text": "C++" }, { "code": null, "e": 25171, "s": 25166, "text": "Java" }, { "code": null, "e": 25179, "s": 25171, "text": "Python3" }, { "code": null, "e": 25182, "s": 25179, "text": "C#" }, { "code": null, "e": 25193, "s": 25182, "text": "Javascript" }, { "code": "// C++ program to check whether the given// number N is the perfect cube or not.#include <bits/stdc++.h> using namespace std; // Function to check if a number// is a perfect Cube or notvoid perfectCube(int N){ int cube; // Iterate from 1-N for (int i; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube == N) { cout << \"Yes\"; return; } else if (cube > N) { cout << \"NO\"; return; } }} // Driver codeint main(){ int N = 216; // Function call perfectCube(N); return 0;}", "e": 25862, "s": 25193, "text": null }, { "code": "// Java program to check whether the given// number N is the perfect cube or notclass GFG { // Function to check if a number // is a perfect Cube or not static void perfectCube(int N) { int cube; // Iterate from 1-N for (int i = 0; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube == N) { System.out.println(\"Yes\"); return; } else if (cube > N) { System.out.println(\"NO\"); return; } } } // Driver code public static void main (String[] args) { int N = 216; // Function call perfectCube(N); }} // This code is contributed by AnkitRai01", "e": 26728, "s": 25862, "text": null }, { "code": "# Python3 program to check whether the given# number N is the perfect cube or not # Function to check if a number# is a perfect Cube or notdef perfectCube(N) : cube = 0; # Iterate from 1-N for i in range(N + 1) : # Find the cube of # every number cube = i * i * i; # Check if cube equals # N or not if (cube == N) : print(\"Yes\"); return; elif (cube > N) : print(\"NO\"); return; # Driver codeif __name__ == \"__main__\" : N = 216; # Function call perfectCube(N); # This code is contributed by Yash_R", "e": 27347, "s": 26728, "text": null }, { "code": "// C# program to check whether the given// number N is the perfect cube or notusing System; class GFG { // Function to check if a number // is a perfect Cube or not static void perfectCube(int N) { int cube; // Iterate from 1-N for (int i = 0; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube == N) { Console.WriteLine(\"Yes\"); return; } else if (cube > N) { Console.WriteLine(\"NO\"); return; } } } // Driver code public static void Main (string[] args) { int N = 216; // Function call perfectCube(N); }} // This code is contributed by AnkitRai01", "e": 28223, "s": 27347, "text": null }, { "code": "<script> // JavaScript program to check whether the given// number N is the perfect cube or not // Function to check if a number// is a perfect Cube or notfunction perfectCube(N){ let cube; // Iterate from 1-N for(let i = 0; i <= N; i++) { // Find the cube of // every number cube = i * i * i; // Check if cube equals // N or not if (cube === N) { document.write(\"Yes\"); return; } else if (cube > N) { document.write(\"NO\"); return; } }} // Driver codelet N = 216; // Function callperfectCube(N); // This code is contributed by Manoj. </script>", "e": 28914, "s": 28223, "text": null }, { "code": null, "e": 28918, "s": 28914, "text": "Yes" }, { "code": null, "e": 28942, "s": 28920, "text": "Time Complexity: O(N)" }, { "code": null, "e": 28964, "s": 28942, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29237, "s": 28964, "text": "Method 2: Using inbuilt function The idea is to use the inbuilt function (cbrt()) to find the cube root of a number which returns floor value of the cube root of the number N. If the cube of this number equals N, then N is a perfect cube otherwise N is not a perfect cube." }, { "code": null, "e": 29289, "s": 29237, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29293, "s": 29289, "text": "C++" }, { "code": null, "e": 29298, "s": 29293, "text": "Java" }, { "code": null, "e": 29306, "s": 29298, "text": "Python3" }, { "code": null, "e": 29309, "s": 29306, "text": "C#" }, { "code": null, "e": 29320, "s": 29309, "text": "Javascript" }, { "code": "// C++ program to check whether the given// number N is the perfect cube or not #include <bits/stdc++.h>using namespace std; // Function to check if a number is// a perfect Cube using inbuilt functionvoid perfectCube(int N){ int cube_root; cube_root = round(cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if (cube_root * cube_root * cube_root == N) { cout << \"Yes\"; return; } else { cout << \"NO\"; return; }} // Driver's codeint main(){ int N = 125; // Function call to check // N is cube or not perfectCube(N); return 0;}", "e": 29946, "s": 29320, "text": null }, { "code": "// Java program to check whether the given// number N is the perfect cube or notpublic class GFG { // Function to check if a number is // a perfect Cube using inbuilt function static void perfectCube(int N) { int cube_root; cube_root = (int)Math.round(Math.cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if (cube_root * cube_root * cube_root == N) { System.out.println(\"Yes\"); return; } else { System.out.println(\"NO\"); return; } } // Driver's code public static void main (String[] args) { int N = 125; // Function call to check // N is cube or not perfectCube(N); } }// This code is contributed by AnkitRai01", "e": 30768, "s": 29946, "text": null }, { "code": "# Python program to check whether the given# number N is the perfect cube or not # Function to check if a number is# a perfect Cube using inbuilt functiondef perfectCube(N) : cube_root = round(N**(1/3)); # If cube of cube_root is equals to N, # then print Yes Else print No if cube_root * cube_root * cube_root == N : print(\"Yes\"); return; else : print(\"NO\"); return; # Driver's codeif __name__ == \"__main__\" : N = 125; # Function call to check # N is cube or not perfectCube(N); # This code is contributed by AnkitRai01", "e": 31348, "s": 30768, "text": null }, { "code": "// C# program to check whether the given// number N is the perfect cube or notusing System; class GFG { // Function to check if a number is // a perfect Cube using inbuilt function static void perfectCube(int N) { int cube_root; cube_root = (int)Math.Round(Math.Cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if (cube_root * cube_root * cube_root == N) { Console.WriteLine(\"Yes\"); return; } else { Console.WriteLine(\"NO\"); return; } } // Driver's code public static void Main (string[] args) { int N = 125; // Function call to check // N is cube or not perfectCube(N); }} // This code is contributed by AnkitRai01", "e": 32168, "s": 31348, "text": null }, { "code": "<script>// Javascript program to check whether the given// number N is the perfect cube or not // Function to check if a number is// a perfect Cube using inbuilt functionfunction perfectCube(N){ let cube_root; cube_root = Math.round(Math.cbrt(N)); // If cube of cube_root is equals to N, // then print Yes Else print No if ((cube_root * cube_root * cube_root) == N) { document.write(\"Yes\"); return; } else { document.write(\"NO\"); return; }} // Driver's codelet N = 125; // Function call to check// N is cube or notperfectCube(N); // This code is contributed by subhammahato348.</script>", "e": 32808, "s": 32168, "text": null }, { "code": null, "e": 32812, "s": 32808, "text": "Yes" }, { "code": null, "e": 32842, "s": 32814, "text": "Time Complexity: O(cbrt(N))" }, { "code": null, "e": 32864, "s": 32842, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 32895, "s": 32864, "text": "Method 3: Using Prime Factors " }, { "code": null, "e": 33190, "s": 32895, "text": "Find all the Prime Factors of the given number N using the approach in this article.Store the frequency of all the prime factors obtained above in a Hash Map.Traverse the Hash Map and if the frequency of every prime factors is not a multiple of 3, then the given number N is not a perfect cube." }, { "code": null, "e": 33275, "s": 33190, "text": "Find all the Prime Factors of the given number N using the approach in this article." }, { "code": null, "e": 33350, "s": 33275, "text": "Store the frequency of all the prime factors obtained above in a Hash Map." }, { "code": null, "e": 33487, "s": 33350, "text": "Traverse the Hash Map and if the frequency of every prime factors is not a multiple of 3, then the given number N is not a perfect cube." }, { "code": null, "e": 33540, "s": 33487, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 33544, "s": 33540, "text": "C++" }, { "code": null, "e": 33549, "s": 33544, "text": "Java" }, { "code": null, "e": 33557, "s": 33549, "text": "Python3" }, { "code": null, "e": 33560, "s": 33557, "text": "C#" }, { "code": null, "e": 33571, "s": 33560, "text": "Javascript" }, { "code": "// C++ program to check if a number// is a perfect cube using prime factors#include<bits/stdc++.h>using namespace std; // Inserts the prime factor in HashMap// if not present// if present updates it's frequencymap<int, int> insertPF(map<int, int> primeFact, int fact){ if (primeFact.find(fact) != primeFact.end()) { primeFact[fact]++; } else { primeFact[fact] = 1; } return primeFact;} // A utility function to find all// prime factors of a given number Nmap<int, int> primeFactors (int n){ map<int, int> primeFact; // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n /= 2; } // n must be odd at this point // So we can skip one element for(int i = 3; i <= sqrt(n); i += 2) { // while i divides n, insert // i and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n /= i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact;} // Function to check if a// number is perfect cubestring perfectCube (int n){ map<int, int> primeFact; primeFact = primeFactors(n); // Iteration in Map for(auto x : primeFact) { if (x.second % 3 != 0) return \"No\"; } return \"Yes\";} // Driver Codeint main(){ int N = 216; // Function to check if N is // perfect cube or not cout << perfectCube(N); return 0;} // This code is contributed by himanshu77", "e": 35214, "s": 33571, "text": null }, { "code": "// Java program to check if a number// is a perfect cube using prime factors import java.io.*;import java.lang.*;import java.util.*; class GFG { // Inserts the prime factor in the Hash Map // if not present // If present updates it's frequency public static HashMap<Integer, Integer> insertPF(HashMap<Integer, Integer> primeFact, int fact) { if (primeFact.containsKey(fact)) { int freq; freq = primeFact.get(fact); primeFact.replace(fact, ++freq); } else { primeFact.put(fact, 1); } return primeFact; } // A utility function to find all // prime factors of a given number N public static HashMap<Integer, Integer> primeFactors(int n) { HashMap<Integer, Integer> primeFact = new HashMap<>(); // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n /= 2; } // n must be odd at this point. // So we can skip one element for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, insert i // and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n /= i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact; } // Function to check if a number // is a perfect cube public static String perfectCube(int n) { HashMap<Integer, Integer> primeFact; primeFact = primeFactors(n); // Using values() for iteration // over keys for (int freq : primeFact.values()) { if (freq % 3 != 0) return \"No\"; } return \"Yes\"; } // Driver Code public static void main(String[] args) { int N = 216; // Function to check if N is // perfect cube or not System.out.println(perfectCube(N)); }}", "e": 37349, "s": 35214, "text": null }, { "code": "# Python3 program to check if a number# is a perfect cube using prime factorsimport math # Inserts the prime factor in HashMap# if not present# if present updates it's frequencydef insertPF(primeFact, fact) : if (fact in primeFact) : primeFact[fact] += 1 else : primeFact[fact] = 1 return primeFact # A utility function to find all# prime factors of a given number Ndef primeFactors (n) : primeFact = {} # Insert the number of 2s # that divide n while (n % 2 == 0) : primeFact = insertPF(primeFact, 2) n = n // 2 # n must be odd at this point # So we can skip one element for i in range(3, int(math.sqrt(n)) + 1, 2) : # while i divides n, insert # i and divide n while (n % i == 0) : primeFact = insertPF(primeFact, i) n = n // i # This condition is to handle # the case when n is a prime # number greater than 2 if (n > 2) : primeFact = insertPF(primeFact, n) return primeFact # Function to check if a # number is perfect cubedef perfectCube (n) : primeFact = {} primeFact = primeFactors(n) # Iteration in Map for x in primeFact : if (primeFact[x] % 3 != 0) : return \"No\" return \"Yes\" N = 216 # Function to check if N is# perfect cube or notprint(perfectCube(N)) # This code is contributed by divyeshrabadiya07.", "e": 38785, "s": 37349, "text": null }, { "code": "// C# program to check if a number// is a perfect cube using prime factors using System;using System.Collections.Generic; public class GFG { // Inserts the prime factor in the Hash Map // if not present // If present updates it's frequency public static Dictionary<int, int> insertPF(Dictionary<int, int> primeFact, int fact) { if (primeFact.ContainsKey(fact)) { int freq; freq = primeFact[fact]; primeFact[fact] = ++freq; } else { primeFact.Add(fact, 1); } return primeFact; } // A utility function to find all // prime factors of a given number N public static Dictionary<int, int> primeFactors(int n) { Dictionary<int, int> primeFact = new Dictionary<int, int>(); // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n /= 2; } // n must be odd at this point. // So we can skip one element for (int i = 3; i <= Math.Sqrt(n); i += 2) { // While i divides n, insert i // and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n /= i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact; } // Function to check if a number // is a perfect cube public static String perfectCube(int n) { Dictionary<int, int> primeFact; primeFact = primeFactors(n); // Using values() for iteration // over keys foreach (int freq in primeFact.Values) { if (freq % 3 != 0) return \"No\"; } return \"Yes\"; } // Driver Code public static void Main(String[] args) { int N = 216; // Function to check if N is // perfect cube or not Console.WriteLine(perfectCube(N)); }} // This code is contributed by sapnasingh4991", "e": 40953, "s": 38785, "text": null }, { "code": "<script> // Javascript program to check if a number// is a perfect cube using prime factors // Inserts the prime factor in HashMap// if not present// if present updates it's frequencyfunction insertPF(primeFact, fact){ if (primeFact.has(fact)) { primeFact.set(fact, primeFact.get(fact)+1); } else { primeFact.set(fact, 1); } return primeFact;} // A utility function to find all// prime factors of a given number Nfunction primeFactors (n){ var primeFact = new Map(); // Insert the number of 2s // that divide n while (n % 2 == 0) { primeFact = insertPF(primeFact, 2); n = parseInt(n/2); } // n must be odd at this point // So we can skip one element for(var i = 3; i <= Math.sqrt(n); i += 2) { // while i divides n, insert // i and divide n while (n % i == 0) { primeFact = insertPF(primeFact, i); n =parseInt(n/i); } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) primeFact = insertPF(primeFact, n); return primeFact;} // Function to check if a// number is perfect cubefunction perfectCube (n){ var primeFact = new Map(); primeFact = primeFactors(n); // Iteration in Map primeFact.forEach((value, key) => { if (value % 3 != 0) return \"No\"; }); return \"Yes\";} // Driver Codevar N = 216;// Function to check if N is// perfect cube or notdocument.write( perfectCube(N)); // This code is contributed by rrrtnx.</script> ", "e": 42531, "s": 40953, "text": null }, { "code": null, "e": 42535, "s": 42531, "text": "Yes" }, { "code": null, "e": 42565, "s": 42537, "text": "Time Complexity: O(sqrt(n))" }, { "code": null, "e": 42593, "s": 42565, "text": "Auxiliary Space: O(sqrt(n))" }, { "code": null, "e": 42600, "s": 42593, "text": "Yash_R" }, { "code": null, "e": 42608, "s": 42600, "text": "ankthon" }, { "code": null, "e": 42623, "s": 42608, "text": "sapnasingh4991" }, { "code": null, "e": 42634, "s": 42623, "text": "himanshu77" }, { "code": null, "e": 42652, "s": 42634, "text": "divyeshrabadiya07" }, { "code": null, "e": 42668, "s": 42652, "text": "subhammahato348" }, { "code": null, "e": 42677, "s": 42668, "text": "mank1083" }, { "code": null, "e": 42684, "s": 42677, "text": "rrrtnx" }, { "code": null, "e": 42700, "s": 42684, "text": "souravmahato348" }, { "code": null, "e": 42719, "s": 42700, "text": "maths-perfect-cube" }, { "code": null, "e": 42732, "s": 42719, "text": "Mathematical" }, { "code": null, "e": 42745, "s": 42732, "text": "Mathematical" }, { "code": null, "e": 42843, "s": 42745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42852, "s": 42843, "text": "Comments" }, { "code": null, "e": 42865, "s": 42852, "text": "Old Comments" }, { "code": null, "e": 42889, "s": 42865, "text": "Merge two sorted arrays" }, { "code": null, "e": 42931, "s": 42889, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 42945, "s": 42931, "text": "Prime Numbers" }, { "code": null, "e": 42988, "s": 42945, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 43010, "s": 42988, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 43051, "s": 43010, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 43096, "s": 43051, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 43123, "s": 43096, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 43172, "s": 43123, "text": "Program to find sum of elements in a given array" } ]
Extreme Rare Event Classification using Autoencoders in Keras | by Chitta Ranjan | Towards Data Science
<<Download the free book, Understanding Deep Learning, to learn more>> In a rare-event problem, we have an unbalanced dataset. Meaning, we have fewer positively labeled samples than negative. In a typical rare-event problem, the positively labeled data are around 5–10% of the total. In an extreme rare event problem, we have less than 1% positively labeled data. For example, in the dataset used here it is around 0.6%. Such extreme rare event problems are quite common in the real-world, for example, sheet-breaks and machine failure in manufacturing, clicks or purchase in an online industry. Classifying these rare events is quite challenging. Recently, Deep Learning has been quite extensively used for classification. However, the small number of positively labeled samples prohibits Deep Learning application. No matter how large the data, the use of Deep Learning gets limited by the amount of positively labeled samples. This is a legitimate question. Why should we not think of using some another Machine Learning approach? The answer is subjective. We can always go with a Machine Learning approach. To make it work, we can undersample from negatively labeled data to have a close to a balanced dataset. Since we have about 0.6% positively labeled data, the undersampling will result in rougly a dataset that is about 1% of the size of the original data. A Machine Learning approach, e.g. SVM or Random Forest, will still work on a dataset of this size. However, it will have limitations in its accuracy. And we will not utilize the information present in the remaining ~99% of the data. If the data is sufficient, Deep Learning methods are potentially more capable. It also allows flexibility for model improvement by using different architectures. We will, therefore, attempt to use Deep Learning methods. In this post, we will learn how we can use a simple dense layers autoencoder to build a rare event classifier. The purpose of this post is to demonstrate the implementation of an Autoencoder for extreme rare-event classification. We will leave the exploration of different architecture and configuration of the Autoencoder on the user. Please share in the comments if you find anything interesting. The autoencoder approach for classification is similar to anomaly detection. In anomaly detection, we learn the pattern of a normal process. Anything that does not follow this pattern is classified as an anomaly. For a binary classification of rare events, we can use a similar approach using autoencoders (derived from here [2]). An autoencoder is made of two modules: encoder and decoder. The encoder learns the underlying features of a process. These features are typically in a reduced dimension. The decoder can recreate the original data from these underlying features. We will divide the data into two parts: positively labeled and negatively labeled. The negatively labeled data is treated as normal state of the process. A normal state is when the process is eventless. We will ignore the positively labeled data, and train an Autoencoder on only negatively labeled data. This Autoencoder has now learned the features of the normal process. A well-trained Autoencoder will predict any new data that is coming from the normal state of the process (as it will have the same pattern or distribution). Therefore, the reconstruction error will be small. However, if we try to reconstruct a data from a rare-event, the Autoencoder will struggle. This will make the reconstruction error high during the rare-event. We can catch such high reconstruction errors and label them as a rare-event prediction. This procedure is similar to anomaly detection methods. This is a binary labeled data from a pulp-and-paper mill for sheet breaks. Sheet breaks is severe problem in paper manufacturing. A single sheet break causes loss of several thousand dollars, and the mills see at least one or more break every day. This causes millions of dollors of yearly losses and work hazards. Detecting a break event is challenging due to the nature of the process. As mentioned in [1], even a 5% reduction in the breaks will bring significant benefit to the mills. The data we have contains about 18k rows collected over 15 days. The column y contains the binary labels, with 1 denoting a sheet break. The rest columns are predictors. There are about 124 positive labeled sample (~0.6%). Download data here. Import the desired libraries. %matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport numpy as npfrom pylab import rcParamsimport tensorflow as tffrom keras.models import Model, load_modelfrom keras.layers import Input, Densefrom keras.callbacks import ModelCheckpoint, TensorBoardfrom keras import regularizersfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, precision_recall_curvefrom sklearn.metrics import recall_score, classification_report, auc, roc_curvefrom sklearn.metrics import precision_recall_fscore_support, f1_scorefrom numpy.random import seedseed(1)from tensorflow import set_random_seedset_random_seed(2)SEED = 123 #used to help randomly select the data pointsDATA_SPLIT_PCT = 0.2rcParams['figure.figsize'] = 8, 6LABELS = ["Normal","Break"] Note that we are setting the random seeds for reproducibility of the result. Data preprocessing Now, we read and prepare the data. df = pd.read_csv("data/processminer-rare-event-mts - data.csv") The objective of this rare-event problem is to predict a sheet-break before it occurs. We will try to predict the break 4 minutes in advance. To build this model, we will shift the labels 2 rows up (which corresponds to 4 minutes). We can do this as df.y=df.y.shift(-2). However, in this problem we would want to do the shifting as: if row n is positively labeled, Make row (n-2) and (n-1) equal to 1. This will help the classifier learn up to 4 minute ahead prediction. Delete row n. Because we do not want the classifier to learn predicting a break when it has happened. We will develop the following UDF for this curve shifting. sign = lambda x: (1, -1)[x < 0]def curve_shift(df, shift_by): ''' This function will shift the binary labels in a dataframe. The curve shift will be with respect to the 1s. For example, if shift is -2, the following process will happen: if row n is labeled as 1, then - Make row (n+shift_by):(n+shift_by-1) = 1. - Remove row n. i.e. the labels will be shifted up to 2 rows up. Inputs: df A pandas dataframe with a binary labeled column. This labeled column should be named as 'y'. shift_by An integer denoting the number of rows to shift. Output df A dataframe with the binary labels shifted by shift. ''' vector = df['y'].copy() for s in range(abs(shift_by)): tmp = vector.shift(sign(shift_by)) tmp = tmp.fillna(0) vector += tmp labelcol = 'y' # Add vector to the df df.insert(loc=0, column=labelcol+'tmp', value=vector) # Remove the rows with labelcol == 1. df = df.drop(df[df[labelcol] == 1].index) # Drop labelcol and rename the tmp col as labelcol df = df.drop(labelcol, axis=1) df = df.rename(columns={labelcol+'tmp': labelcol}) # Make the labelcol binary df.loc[df[labelcol] > 0, labelcol] = 1 return df Before moving forward, we will drop the time, and also the categorical columns for simplicity. # Remove time column, and the categorical columnsdf = df.drop(['time', 'x28', 'x61'], axis=1) Now, we divide the data into train, valid, and test sets. Then we will take the subset of data with only 0s to train the autoencoder. df_train, df_test = train_test_split(df, test_size=DATA_SPLIT_PCT, random_state=SEED)df_train, df_valid = train_test_split(df_train, test_size=DATA_SPLIT_PCT, random_state=SEED)df_train_0 = df_train.loc[df['y'] == 0]df_train_1 = df_train.loc[df['y'] == 1]df_train_0_x = df_train_0.drop(['y'], axis=1)df_train_1_x = df_train_1.drop(['y'], axis=1)df_valid_0 = df_valid.loc[df['y'] == 0]df_valid_1 = df_valid.loc[df['y'] == 1]df_valid_0_x = df_valid_0.drop(['y'], axis=1)df_valid_1_x = df_valid_1.drop(['y'], axis=1)df_test_0 = df_test.loc[df['y'] == 0]df_test_1 = df_test.loc[df['y'] == 1]df_test_0_x = df_test_0.drop(['y'], axis=1)df_test_1_x = df_test_1.drop(['y'], axis=1) Standardization It is usually better to use a standardized data (transformed to Gaussian, mean 0 and variance 1) for autoencoders. scaler = StandardScaler().fit(df_train_0_x)df_train_0_x_rescaled = scaler.transform(df_train_0_x)df_valid_0_x_rescaled = scaler.transform(df_valid_0_x)df_valid_x_rescaled = scaler.transform(df_valid.drop(['y'], axis = 1))df_test_0_x_rescaled = scaler.transform(df_test_0_x)df_test_x_rescaled = scaler.transform(df_test.drop(['y'], axis = 1)) Initialization First, we will initialize the Autoencoder architecture. We are building a simple autoencoder. More complex architectures and other configurations should be explored. nb_epoch = 200batch_size = 128input_dim = df_train_0_x_rescaled.shape[1] #num of predictor variables, encoding_dim = 32hidden_dim = int(encoding_dim / 2)learning_rate = 1e-3input_layer = Input(shape=(input_dim, ))encoder = Dense(encoding_dim, activation="relu", activity_regularizer=regularizers.l1(learning_rate))(input_layer)encoder = Dense(hidden_dim, activation="relu")(encoder)decoder = Dense(hidden_dim, activation="relu")(encoder)decoder = Dense(encoding_dim, activation="relu")(decoder)decoder = Dense(input_dim, activation="linear")(decoder)autoencoder = Model(inputs=input_layer, outputs=decoder)autoencoder.summary() Training We will train the model and save it in a file. Saving a trained model is a good practice for saving time for future analysis. autoencoder.compile(metrics=['accuracy'], loss='mean_squared_error', optimizer='adam')cp = ModelCheckpoint(filepath="autoencoder_classifier.h5", save_best_only=True, verbose=0)tb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)history = autoencoder.fit(df_train_0_x_rescaled, df_train_0_x_rescaled, epochs=nb_epoch, batch_size=batch_size, shuffle=True, validation_data=(df_valid_0_x_rescaled, df_valid_0_x_rescaled), verbose=1, callbacks=[cp, tb]).history Classification In the following, we show how we can use an Autoencoder reconstruction error for the rare-event classification. As mentioned before, if the reconstruction error is high, we will classify it as a sheet-break. We will need to determine the threshold for this. We will use the validation set to identify the threshold. valid_x_predictions = autoencoder.predict(df_valid_x_rescaled)mse = np.mean(np.power(df_valid_x_rescaled - valid_x_predictions, 2), axis=1)error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': df_valid['y']})precision_rt, recall_rt, threshold_rt = precision_recall_curve(error_df.True_class, error_df.Reconstruction_error)plt.plot(threshold_rt, precision_rt[1:], label="Precision",linewidth=5)plt.plot(threshold_rt, recall_rt[1:], label="Recall",linewidth=5)plt.title('Precision and recall for different threshold values')plt.xlabel('Threshold')plt.ylabel('Precision/Recall')plt.legend()plt.show() Now, we will perform classification on the test data. We should not estimate the classification threshold from the test data. It will result in overfitting. test_x_predictions = autoencoder.predict(df_test_x_rescaled)mse = np.mean(np.power(df_test_x_rescaled - test_x_predictions, 2), axis=1)error_df_test = pd.DataFrame({'Reconstruction_error': mse, 'True_class': df_test['y']})error_df_test = error_df_test.reset_index()threshold_fixed = 0.4groups = error_df_test.groupby('True_class')fig, ax = plt.subplots()for name, group in groups: ax.plot(group.index, group.Reconstruction_error, marker='o', ms=3.5, linestyle='', label= "Break" if name == 1 else "Normal")ax.hlines(threshold_fixed, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')ax.legend()plt.title("Reconstruction error for different classes")plt.ylabel("Reconstruction error")plt.xlabel("Data point index")plt.show(); In Figure 4, the orange and blue dot above the threshold line represents the True Positive and False Positive, respectively. As we can see, we have good number of false positives. To have a better look, we can see a confusion matrix. pred_y = [1 if e > threshold_fixed else 0 for e in error_df.Reconstruction_error.values]conf_matrix = confusion_matrix(error_df.True_class, pred_y)plt.figure(figsize=(12, 12))sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt="d");plt.title("Confusion matrix")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show() We could predict 8 out of 41 breaks instances. Note that these instances include 2 or 4 minute ahead predictions. This is around 20%, which is a good recall rate for the paper industry. The False Positive Rate is around 6%. This is not ideal but not terrible for a mill. Still, this model can be further improved to increase the recall rate with smaller False Positive Rate. We will look at the AUC below and then talk about the next approach for improvement. ROC curve and AUC false_pos_rate, true_pos_rate, thresholds = roc_curve(error_df.True_class, error_df.Reconstruction_error)roc_auc = auc(false_pos_rate, true_pos_rate,)plt.plot(false_pos_rate, true_pos_rate, linewidth=5, label='AUC = %0.3f'% roc_auc)plt.plot([0,1],[0,1], linewidth=5)plt.xlim([-0.01, 1])plt.ylim([0, 1.01])plt.legend(loc='lower right')plt.title('Receiver operating characteristic curve (ROC)')plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show() The AUC is 0.69. The entire code with comments are present here. github.com Autoencoders are a nonlinear extension of PCA. However, the conventional Autoencoder developed above does not follow the principles of PCA. In Build the right Autoencoder — Tune and Optimize using PCA principles. Part I and Part II, the required PCA principles that should be incorporated in an Autoencoder for optimization are explained and implemented. The problem discussed here is a (multivariate) time series. However, in the Autoencoder model we are not taking into account the temporal information/patterns. In the next post, we will explore if it is possible with an RNN. We will try a LSTM autoencoder. We worked on an extreme rare event binary labeled data from a paper mill to build an Autoencoder Classifier. We achieved reasonable accuracy. The purpose here was to demonstrate the use of a basic Autoencoder for rare event classification. We will further work on developing other methods, including an LSTM Autoencoder that can extract the temporal features for better accuracy. The next post on LSTM Autoencoder is here, LSTM Autoencoder for rare event classification. Build the right Autoencoder — Tune and Optimize using PCA principles. Part I. Build the right Autoencoder — Tune and Optimize using PCA principles. Part II. LSTM Autoencoder for Extreme Rare Event Classification in Keras. Ranjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717.https://www.datascience.com/blog/fraud-detection-with-tensorflowGithub repo: https://github.com/cran2367/autoencoder_classifier Ranjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717. https://www.datascience.com/blog/fraud-detection-with-tensorflow Github repo: https://github.com/cran2367/autoencoder_classifier Disclaimer: The scope of this post is limited to a tutorial for building a Dense Layer Autoencoder and using it as a rare-event classifier. A practitioner is expected to achieve better results for this data by network tuning. The purpose of the article is helping Data Scientists implement an Autoencoder.
[ { "code": null, "e": 242, "s": 171, "text": "<<Download the free book, Understanding Deep Learning, to learn more>>" }, { "code": null, "e": 592, "s": 242, "text": "In a rare-event problem, we have an unbalanced dataset. Meaning, we have fewer positively labeled samples than negative. In a typical rare-event problem, the positively labeled data are around 5–10% of the total. In an extreme rare event problem, we have less than 1% positively labeled data. For example, in the dataset used here it is around 0.6%." }, { "code": null, "e": 767, "s": 592, "text": "Such extreme rare event problems are quite common in the real-world, for example, sheet-breaks and machine failure in manufacturing, clicks or purchase in an online industry." }, { "code": null, "e": 1101, "s": 767, "text": "Classifying these rare events is quite challenging. Recently, Deep Learning has been quite extensively used for classification. However, the small number of positively labeled samples prohibits Deep Learning application. No matter how large the data, the use of Deep Learning gets limited by the amount of positively labeled samples." }, { "code": null, "e": 1205, "s": 1101, "text": "This is a legitimate question. Why should we not think of using some another Machine Learning approach?" }, { "code": null, "e": 1770, "s": 1205, "text": "The answer is subjective. We can always go with a Machine Learning approach. To make it work, we can undersample from negatively labeled data to have a close to a balanced dataset. Since we have about 0.6% positively labeled data, the undersampling will result in rougly a dataset that is about 1% of the size of the original data. A Machine Learning approach, e.g. SVM or Random Forest, will still work on a dataset of this size. However, it will have limitations in its accuracy. And we will not utilize the information present in the remaining ~99% of the data." }, { "code": null, "e": 1990, "s": 1770, "text": "If the data is sufficient, Deep Learning methods are potentially more capable. It also allows flexibility for model improvement by using different architectures. We will, therefore, attempt to use Deep Learning methods." }, { "code": null, "e": 2389, "s": 1990, "text": "In this post, we will learn how we can use a simple dense layers autoencoder to build a rare event classifier. The purpose of this post is to demonstrate the implementation of an Autoencoder for extreme rare-event classification. We will leave the exploration of different architecture and configuration of the Autoencoder on the user. Please share in the comments if you find anything interesting." }, { "code": null, "e": 2720, "s": 2389, "text": "The autoencoder approach for classification is similar to anomaly detection. In anomaly detection, we learn the pattern of a normal process. Anything that does not follow this pattern is classified as an anomaly. For a binary classification of rare events, we can use a similar approach using autoencoders (derived from here [2])." }, { "code": null, "e": 2780, "s": 2720, "text": "An autoencoder is made of two modules: encoder and decoder." }, { "code": null, "e": 2890, "s": 2780, "text": "The encoder learns the underlying features of a process. These features are typically in a reduced dimension." }, { "code": null, "e": 2965, "s": 2890, "text": "The decoder can recreate the original data from these underlying features." }, { "code": null, "e": 3048, "s": 2965, "text": "We will divide the data into two parts: positively labeled and negatively labeled." }, { "code": null, "e": 3168, "s": 3048, "text": "The negatively labeled data is treated as normal state of the process. A normal state is when the process is eventless." }, { "code": null, "e": 3270, "s": 3168, "text": "We will ignore the positively labeled data, and train an Autoencoder on only negatively labeled data." }, { "code": null, "e": 3339, "s": 3270, "text": "This Autoencoder has now learned the features of the normal process." }, { "code": null, "e": 3496, "s": 3339, "text": "A well-trained Autoencoder will predict any new data that is coming from the normal state of the process (as it will have the same pattern or distribution)." }, { "code": null, "e": 3547, "s": 3496, "text": "Therefore, the reconstruction error will be small." }, { "code": null, "e": 3638, "s": 3547, "text": "However, if we try to reconstruct a data from a rare-event, the Autoencoder will struggle." }, { "code": null, "e": 3706, "s": 3638, "text": "This will make the reconstruction error high during the rare-event." }, { "code": null, "e": 3794, "s": 3706, "text": "We can catch such high reconstruction errors and label them as a rare-event prediction." }, { "code": null, "e": 3850, "s": 3794, "text": "This procedure is similar to anomaly detection methods." }, { "code": null, "e": 4165, "s": 3850, "text": "This is a binary labeled data from a pulp-and-paper mill for sheet breaks. Sheet breaks is severe problem in paper manufacturing. A single sheet break causes loss of several thousand dollars, and the mills see at least one or more break every day. This causes millions of dollors of yearly losses and work hazards." }, { "code": null, "e": 4338, "s": 4165, "text": "Detecting a break event is challenging due to the nature of the process. As mentioned in [1], even a 5% reduction in the breaks will bring significant benefit to the mills." }, { "code": null, "e": 4561, "s": 4338, "text": "The data we have contains about 18k rows collected over 15 days. The column y contains the binary labels, with 1 denoting a sheet break. The rest columns are predictors. There are about 124 positive labeled sample (~0.6%)." }, { "code": null, "e": 4581, "s": 4561, "text": "Download data here." }, { "code": null, "e": 4611, "s": 4581, "text": "Import the desired libraries." }, { "code": null, "e": 5477, "s": 4611, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport numpy as npfrom pylab import rcParamsimport tensorflow as tffrom keras.models import Model, load_modelfrom keras.layers import Input, Densefrom keras.callbacks import ModelCheckpoint, TensorBoardfrom keras import regularizersfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, precision_recall_curvefrom sklearn.metrics import recall_score, classification_report, auc, roc_curvefrom sklearn.metrics import precision_recall_fscore_support, f1_scorefrom numpy.random import seedseed(1)from tensorflow import set_random_seedset_random_seed(2)SEED = 123 #used to help randomly select the data pointsDATA_SPLIT_PCT = 0.2rcParams['figure.figsize'] = 8, 6LABELS = [\"Normal\",\"Break\"]" }, { "code": null, "e": 5554, "s": 5477, "text": "Note that we are setting the random seeds for reproducibility of the result." }, { "code": null, "e": 5573, "s": 5554, "text": "Data preprocessing" }, { "code": null, "e": 5608, "s": 5573, "text": "Now, we read and prepare the data." }, { "code": null, "e": 5672, "s": 5608, "text": "df = pd.read_csv(\"data/processminer-rare-event-mts - data.csv\")" }, { "code": null, "e": 6037, "s": 5672, "text": "The objective of this rare-event problem is to predict a sheet-break before it occurs. We will try to predict the break 4 minutes in advance. To build this model, we will shift the labels 2 rows up (which corresponds to 4 minutes). We can do this as df.y=df.y.shift(-2). However, in this problem we would want to do the shifting as: if row n is positively labeled," }, { "code": null, "e": 6143, "s": 6037, "text": "Make row (n-2) and (n-1) equal to 1. This will help the classifier learn up to 4 minute ahead prediction." }, { "code": null, "e": 6245, "s": 6143, "text": "Delete row n. Because we do not want the classifier to learn predicting a break when it has happened." }, { "code": null, "e": 6304, "s": 6245, "text": "We will develop the following UDF for this curve shifting." }, { "code": null, "e": 7551, "s": 6304, "text": "sign = lambda x: (1, -1)[x < 0]def curve_shift(df, shift_by): ''' This function will shift the binary labels in a dataframe. The curve shift will be with respect to the 1s. For example, if shift is -2, the following process will happen: if row n is labeled as 1, then - Make row (n+shift_by):(n+shift_by-1) = 1. - Remove row n. i.e. the labels will be shifted up to 2 rows up. Inputs: df A pandas dataframe with a binary labeled column. This labeled column should be named as 'y'. shift_by An integer denoting the number of rows to shift. Output df A dataframe with the binary labels shifted by shift. ''' vector = df['y'].copy() for s in range(abs(shift_by)): tmp = vector.shift(sign(shift_by)) tmp = tmp.fillna(0) vector += tmp labelcol = 'y' # Add vector to the df df.insert(loc=0, column=labelcol+'tmp', value=vector) # Remove the rows with labelcol == 1. df = df.drop(df[df[labelcol] == 1].index) # Drop labelcol and rename the tmp col as labelcol df = df.drop(labelcol, axis=1) df = df.rename(columns={labelcol+'tmp': labelcol}) # Make the labelcol binary df.loc[df[labelcol] > 0, labelcol] = 1 return df" }, { "code": null, "e": 7646, "s": 7551, "text": "Before moving forward, we will drop the time, and also the categorical columns for simplicity." }, { "code": null, "e": 7740, "s": 7646, "text": "# Remove time column, and the categorical columnsdf = df.drop(['time', 'x28', 'x61'], axis=1)" }, { "code": null, "e": 7874, "s": 7740, "text": "Now, we divide the data into train, valid, and test sets. Then we will take the subset of data with only 0s to train the autoencoder." }, { "code": null, "e": 8548, "s": 7874, "text": "df_train, df_test = train_test_split(df, test_size=DATA_SPLIT_PCT, random_state=SEED)df_train, df_valid = train_test_split(df_train, test_size=DATA_SPLIT_PCT, random_state=SEED)df_train_0 = df_train.loc[df['y'] == 0]df_train_1 = df_train.loc[df['y'] == 1]df_train_0_x = df_train_0.drop(['y'], axis=1)df_train_1_x = df_train_1.drop(['y'], axis=1)df_valid_0 = df_valid.loc[df['y'] == 0]df_valid_1 = df_valid.loc[df['y'] == 1]df_valid_0_x = df_valid_0.drop(['y'], axis=1)df_valid_1_x = df_valid_1.drop(['y'], axis=1)df_test_0 = df_test.loc[df['y'] == 0]df_test_1 = df_test.loc[df['y'] == 1]df_test_0_x = df_test_0.drop(['y'], axis=1)df_test_1_x = df_test_1.drop(['y'], axis=1)" }, { "code": null, "e": 8564, "s": 8548, "text": "Standardization" }, { "code": null, "e": 8679, "s": 8564, "text": "It is usually better to use a standardized data (transformed to Gaussian, mean 0 and variance 1) for autoencoders." }, { "code": null, "e": 9021, "s": 8679, "text": "scaler = StandardScaler().fit(df_train_0_x)df_train_0_x_rescaled = scaler.transform(df_train_0_x)df_valid_0_x_rescaled = scaler.transform(df_valid_0_x)df_valid_x_rescaled = scaler.transform(df_valid.drop(['y'], axis = 1))df_test_0_x_rescaled = scaler.transform(df_test_0_x)df_test_x_rescaled = scaler.transform(df_test.drop(['y'], axis = 1))" }, { "code": null, "e": 9036, "s": 9021, "text": "Initialization" }, { "code": null, "e": 9202, "s": 9036, "text": "First, we will initialize the Autoencoder architecture. We are building a simple autoencoder. More complex architectures and other configurations should be explored." }, { "code": null, "e": 9830, "s": 9202, "text": "nb_epoch = 200batch_size = 128input_dim = df_train_0_x_rescaled.shape[1] #num of predictor variables, encoding_dim = 32hidden_dim = int(encoding_dim / 2)learning_rate = 1e-3input_layer = Input(shape=(input_dim, ))encoder = Dense(encoding_dim, activation=\"relu\", activity_regularizer=regularizers.l1(learning_rate))(input_layer)encoder = Dense(hidden_dim, activation=\"relu\")(encoder)decoder = Dense(hidden_dim, activation=\"relu\")(encoder)decoder = Dense(encoding_dim, activation=\"relu\")(decoder)decoder = Dense(input_dim, activation=\"linear\")(decoder)autoencoder = Model(inputs=input_layer, outputs=decoder)autoencoder.summary()" }, { "code": null, "e": 9839, "s": 9830, "text": "Training" }, { "code": null, "e": 9965, "s": 9839, "text": "We will train the model and save it in a file. Saving a trained model is a good practice for saving time for future analysis." }, { "code": null, "e": 10716, "s": 9965, "text": "autoencoder.compile(metrics=['accuracy'], loss='mean_squared_error', optimizer='adam')cp = ModelCheckpoint(filepath=\"autoencoder_classifier.h5\", save_best_only=True, verbose=0)tb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)history = autoencoder.fit(df_train_0_x_rescaled, df_train_0_x_rescaled, epochs=nb_epoch, batch_size=batch_size, shuffle=True, validation_data=(df_valid_0_x_rescaled, df_valid_0_x_rescaled), verbose=1, callbacks=[cp, tb]).history" }, { "code": null, "e": 10731, "s": 10716, "text": "Classification" }, { "code": null, "e": 10843, "s": 10731, "text": "In the following, we show how we can use an Autoencoder reconstruction error for the rare-event classification." }, { "code": null, "e": 10989, "s": 10843, "text": "As mentioned before, if the reconstruction error is high, we will classify it as a sheet-break. We will need to determine the threshold for this." }, { "code": null, "e": 11047, "s": 10989, "text": "We will use the validation set to identify the threshold." }, { "code": null, "e": 11682, "s": 11047, "text": "valid_x_predictions = autoencoder.predict(df_valid_x_rescaled)mse = np.mean(np.power(df_valid_x_rescaled - valid_x_predictions, 2), axis=1)error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': df_valid['y']})precision_rt, recall_rt, threshold_rt = precision_recall_curve(error_df.True_class, error_df.Reconstruction_error)plt.plot(threshold_rt, precision_rt[1:], label=\"Precision\",linewidth=5)plt.plot(threshold_rt, recall_rt[1:], label=\"Recall\",linewidth=5)plt.title('Precision and recall for different threshold values')plt.xlabel('Threshold')plt.ylabel('Precision/Recall')plt.legend()plt.show()" }, { "code": null, "e": 11736, "s": 11682, "text": "Now, we will perform classification on the test data." }, { "code": null, "e": 11839, "s": 11736, "text": "We should not estimate the classification threshold from the test data. It will result in overfitting." }, { "code": null, "e": 12629, "s": 11839, "text": "test_x_predictions = autoencoder.predict(df_test_x_rescaled)mse = np.mean(np.power(df_test_x_rescaled - test_x_predictions, 2), axis=1)error_df_test = pd.DataFrame({'Reconstruction_error': mse, 'True_class': df_test['y']})error_df_test = error_df_test.reset_index()threshold_fixed = 0.4groups = error_df_test.groupby('True_class')fig, ax = plt.subplots()for name, group in groups: ax.plot(group.index, group.Reconstruction_error, marker='o', ms=3.5, linestyle='', label= \"Break\" if name == 1 else \"Normal\")ax.hlines(threshold_fixed, ax.get_xlim()[0], ax.get_xlim()[1], colors=\"r\", zorder=100, label='Threshold')ax.legend()plt.title(\"Reconstruction error for different classes\")plt.ylabel(\"Reconstruction error\")plt.xlabel(\"Data point index\")plt.show();" }, { "code": null, "e": 12863, "s": 12629, "text": "In Figure 4, the orange and blue dot above the threshold line represents the True Positive and False Positive, respectively. As we can see, we have good number of false positives. To have a better look, we can see a confusion matrix." }, { "code": null, "e": 13217, "s": 12863, "text": "pred_y = [1 if e > threshold_fixed else 0 for e in error_df.Reconstruction_error.values]conf_matrix = confusion_matrix(error_df.True_class, pred_y)plt.figure(figsize=(12, 12))sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt=\"d\");plt.title(\"Confusion matrix\")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show()" }, { "code": null, "e": 13488, "s": 13217, "text": "We could predict 8 out of 41 breaks instances. Note that these instances include 2 or 4 minute ahead predictions. This is around 20%, which is a good recall rate for the paper industry. The False Positive Rate is around 6%. This is not ideal but not terrible for a mill." }, { "code": null, "e": 13677, "s": 13488, "text": "Still, this model can be further improved to increase the recall rate with smaller False Positive Rate. We will look at the AUC below and then talk about the next approach for improvement." }, { "code": null, "e": 13695, "s": 13677, "text": "ROC curve and AUC" }, { "code": null, "e": 14163, "s": 13695, "text": "false_pos_rate, true_pos_rate, thresholds = roc_curve(error_df.True_class, error_df.Reconstruction_error)roc_auc = auc(false_pos_rate, true_pos_rate,)plt.plot(false_pos_rate, true_pos_rate, linewidth=5, label='AUC = %0.3f'% roc_auc)plt.plot([0,1],[0,1], linewidth=5)plt.xlim([-0.01, 1])plt.ylim([0, 1.01])plt.legend(loc='lower right')plt.title('Receiver operating characteristic curve (ROC)')plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show()" }, { "code": null, "e": 14180, "s": 14163, "text": "The AUC is 0.69." }, { "code": null, "e": 14228, "s": 14180, "text": "The entire code with comments are present here." }, { "code": null, "e": 14239, "s": 14228, "text": "github.com" }, { "code": null, "e": 14594, "s": 14239, "text": "Autoencoders are a nonlinear extension of PCA. However, the conventional Autoencoder developed above does not follow the principles of PCA. In Build the right Autoencoder — Tune and Optimize using PCA principles. Part I and Part II, the required PCA principles that should be incorporated in an Autoencoder for optimization are explained and implemented." }, { "code": null, "e": 14851, "s": 14594, "text": "The problem discussed here is a (multivariate) time series. However, in the Autoencoder model we are not taking into account the temporal information/patterns. In the next post, we will explore if it is possible with an RNN. We will try a LSTM autoencoder." }, { "code": null, "e": 15231, "s": 14851, "text": "We worked on an extreme rare event binary labeled data from a paper mill to build an Autoencoder Classifier. We achieved reasonable accuracy. The purpose here was to demonstrate the use of a basic Autoencoder for rare event classification. We will further work on developing other methods, including an LSTM Autoencoder that can extract the temporal features for better accuracy." }, { "code": null, "e": 15322, "s": 15231, "text": "The next post on LSTM Autoencoder is here, LSTM Autoencoder for rare event classification." }, { "code": null, "e": 15400, "s": 15322, "text": "Build the right Autoencoder — Tune and Optimize using PCA principles. Part I." }, { "code": null, "e": 15479, "s": 15400, "text": "Build the right Autoencoder — Tune and Optimize using PCA principles. Part II." }, { "code": null, "e": 15544, "s": 15479, "text": "LSTM Autoencoder for Extreme Rare Event Classification in Keras." }, { "code": null, "e": 15829, "s": 15544, "text": "Ranjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717.https://www.datascience.com/blog/fraud-detection-with-tensorflowGithub repo: https://github.com/cran2367/autoencoder_classifier" }, { "code": null, "e": 15987, "s": 15829, "text": "Ranjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717." }, { "code": null, "e": 16052, "s": 15987, "text": "https://www.datascience.com/blog/fraud-detection-with-tensorflow" }, { "code": null, "e": 16116, "s": 16052, "text": "Github repo: https://github.com/cran2367/autoencoder_classifier" } ]
AWK - Bit Manipulation Functions
AWK has the following built-in bit manipulation functions − Performs bitwise AND operation. [jerry]$ awk 'BEGIN { num1 = 10 num2 = 6 printf "(%d AND %d) = %d\n", num1, num2, and(num1, num2) }' On executing this code, you get the following result − (10 AND 6) = 2 It performs bitwise COMPLEMENT operation. [jerry]$ awk 'BEGIN { num1 = 10 printf "compl(%d) = %d\n", num1, compl(num1) }' On executing this code, you get the following result − compl(10) = 9007199254740981 It performs bitwise LEFT SHIFT operation. [jerry]$ awk 'BEGIN { num1 = 10 printf "lshift(%d) by 1 = %d\n", num1, lshift(num1, 1) }' On executing this code, you get the following result − lshift(10) by 1 = 20 It performs bitwise RIGHT SHIFT operation. [jerry]$ awk 'BEGIN { num1 = 10 printf "rshift(%d) by 1 = %d\n", num1, rshift(num1, 1) }' On executing this code, you get the following result − rshift(10) by 1 = 5 It performs bitwise OR operation. [jerry]$ awk 'BEGIN { num1 = 10 num2 = 6 printf "(%d OR %d) = %d\n", num1, num2, or(num1, num2) }' On executing this code, you get the following result − (10 OR 6) = 14 It performs bitwise XOR operation. [jerry]$ awk 'BEGIN { num1 = 10 num2 = 6 printf "(%d XOR %d) = %d\n", num1, num2, xor(num1, num2) }' On executing this code, you get the following result − (10 bitwise xor 6) = 12 Print Add Notes Bookmark this page
[ { "code": null, "e": 1917, "s": 1857, "text": "AWK has the following built-in bit manipulation functions −" }, { "code": null, "e": 1949, "s": 1917, "text": "Performs bitwise AND operation." }, { "code": null, "e": 2059, "s": 1949, "text": "[jerry]$ awk 'BEGIN {\n num1 = 10\n num2 = 6\n printf \"(%d AND %d) = %d\\n\", num1, num2, and(num1, num2)\n}'" }, { "code": null, "e": 2114, "s": 2059, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2130, "s": 2114, "text": "(10 AND 6) = 2\n" }, { "code": null, "e": 2172, "s": 2130, "text": "It performs bitwise COMPLEMENT operation." }, { "code": null, "e": 2258, "s": 2172, "text": "[jerry]$ awk 'BEGIN {\n num1 = 10\n printf \"compl(%d) = %d\\n\", num1, compl(num1)\n}'" }, { "code": null, "e": 2313, "s": 2258, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2343, "s": 2313, "text": "compl(10) = 9007199254740981\n" }, { "code": null, "e": 2385, "s": 2343, "text": "It performs bitwise LEFT SHIFT operation." }, { "code": null, "e": 2481, "s": 2385, "text": "[jerry]$ awk 'BEGIN {\n num1 = 10\n printf \"lshift(%d) by 1 = %d\\n\", num1, lshift(num1, 1)\n}'" }, { "code": null, "e": 2536, "s": 2481, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2558, "s": 2536, "text": "lshift(10) by 1 = 20\n" }, { "code": null, "e": 2601, "s": 2558, "text": "It performs bitwise RIGHT SHIFT operation." }, { "code": null, "e": 2697, "s": 2601, "text": "[jerry]$ awk 'BEGIN {\n num1 = 10\n printf \"rshift(%d) by 1 = %d\\n\", num1, rshift(num1, 1)\n}'" }, { "code": null, "e": 2752, "s": 2697, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2773, "s": 2752, "text": "rshift(10) by 1 = 5\n" }, { "code": null, "e": 2807, "s": 2773, "text": "It performs bitwise OR operation." }, { "code": null, "e": 2915, "s": 2807, "text": "[jerry]$ awk 'BEGIN {\n num1 = 10\n num2 = 6\n printf \"(%d OR %d) = %d\\n\", num1, num2, or(num1, num2)\n}'" }, { "code": null, "e": 2970, "s": 2915, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2986, "s": 2970, "text": "(10 OR 6) = 14\n" }, { "code": null, "e": 3021, "s": 2986, "text": "It performs bitwise XOR operation." }, { "code": null, "e": 3131, "s": 3021, "text": "[jerry]$ awk 'BEGIN {\n num1 = 10\n num2 = 6\n printf \"(%d XOR %d) = %d\\n\", num1, num2, xor(num1, num2)\n}'" }, { "code": null, "e": 3186, "s": 3131, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3211, "s": 3186, "text": "(10 bitwise xor 6) = 12\n" }, { "code": null, "e": 3218, "s": 3211, "text": " Print" }, { "code": null, "e": 3229, "s": 3218, "text": " Add Notes" } ]
C library function - fclose()
The C library function int fclose(FILE *stream) closes the stream. All buffers are flushed. Following is the declaration for fclose() function. int fclose(FILE *stream) stream − This is the pointer to a FILE object that specifies the stream to be closed. stream − This is the pointer to a FILE object that specifies the stream to be closed. This method returns zero if the stream is successfully closed. On failure, EOF is returned. The following example shows the usage of fclose() function. #include <stdio.h> int main () { FILE *fp; fp = fopen("file.txt", "w"); fprintf(fp, "%s", "This is tutorialspoint.com"); fclose(fp); return(0); } Let us compile and run the above program that will create a file file.txt, and then it will write following text line and finally it will close the file using fclose() function. This is tutorialspoint.com 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2099, "s": 2007, "text": "The C library function int fclose(FILE *stream) closes the stream. All buffers are flushed." }, { "code": null, "e": 2151, "s": 2099, "text": "Following is the declaration for fclose() function." }, { "code": null, "e": 2176, "s": 2151, "text": "int fclose(FILE *stream)" }, { "code": null, "e": 2262, "s": 2176, "text": "stream − This is the pointer to a FILE object that specifies the stream to be closed." }, { "code": null, "e": 2348, "s": 2262, "text": "stream − This is the pointer to a FILE object that specifies the stream to be closed." }, { "code": null, "e": 2440, "s": 2348, "text": "This method returns zero if the stream is successfully closed. On failure, EOF is returned." }, { "code": null, "e": 2500, "s": 2440, "text": "The following example shows the usage of fclose() function." }, { "code": null, "e": 2669, "s": 2500, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n \n fp = fopen(\"file.txt\", \"w\");\n\n fprintf(fp, \"%s\", \"This is tutorialspoint.com\");\n fclose(fp);\n \n return(0);\n}" }, { "code": null, "e": 2847, "s": 2669, "text": "Let us compile and run the above program that will create a file file.txt, and then it will write following text line and finally it will close the file using fclose() function." }, { "code": null, "e": 2875, "s": 2847, "text": "This is tutorialspoint.com\n" }, { "code": null, "e": 2908, "s": 2875, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2923, "s": 2908, "text": " Nishant Malik" }, { "code": null, "e": 2958, "s": 2923, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2973, "s": 2958, "text": " Nishant Malik" }, { "code": null, "e": 3008, "s": 2973, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3022, "s": 3008, "text": " Asif Hussain" }, { "code": null, "e": 3055, "s": 3022, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3073, "s": 3055, "text": " Richa Maheshwari" }, { "code": null, "e": 3108, "s": 3073, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3127, "s": 3108, "text": " Vandana Annavaram" }, { "code": null, "e": 3160, "s": 3127, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3172, "s": 3160, "text": " Amit Diwan" }, { "code": null, "e": 3179, "s": 3172, "text": " Print" }, { "code": null, "e": 3190, "s": 3179, "text": " Add Notes" } ]
DateTime.AddTicks() Method in C# - GeeksforGeeks
22 Jan, 2019 This method is used to returns a new DateTime that adds the specified number of ticks to the value of this instance. This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation. Syntax: public DateTime AddTicks (long value); Here, it takes a number of 100-nanosecond ticks. Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the time represented by value. Exception: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue. Below programs illustrate the use of DateTime.AddTicks(Int64) Method: Example 1: // C# program to demonstrate the// DateTime.AddTicks(Double) Methodusing System; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // adding the 3000 ticks // using AddTicks() method; DateTime date2 = date1.AddTicks(3000); // Display the date1 Console.WriteLine("No. of ticks before operation: " + "{0}", date1.Ticks); // Display the date2 Console.WriteLine("\nNo. of ticks after operation: " + "{0}", date2.Ticks); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} No. of ticks before operation: 633979152150000000 No. of ticks after operation: 633979152150003000 Example 2: For ArgumentOutOfRangeException // C# program to demonstrate the// DateTime.AddTicks(long) Methodusing System; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MaxValue; // Display the date1 Console.WriteLine("DateTime before operation: " + "{0}", date1.Ticks); // adding the 1 Ticks // using AddTicks() method; DateTime date2 = date1.AddTicks(1); // Display the date2 Console.WriteLine("\nDateTime after operation: " + "{0}", date2.Ticks); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\nThe resulting DateTime is "+ "greater than the DateTime.MaxValue "); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTime before operation: 3155378975999999999 The resulting DateTime is greater than the DateTime.MaxValue Exception Thrown: System.ArgumentOutOfRangeException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addticks?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates Destructors in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Abstract Classes C# | Data Types HashSet in C# with Examples Different ways to sort an array in descending order in C#
[ { "code": null, "e": 24256, "s": 24228, "text": "\n22 Jan, 2019" }, { "code": null, "e": 24509, "s": 24256, "text": "This method is used to returns a new DateTime that adds the specified number of ticks to the value of this instance. This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation." }, { "code": null, "e": 24517, "s": 24509, "text": "Syntax:" }, { "code": null, "e": 24556, "s": 24517, "text": "public DateTime AddTicks (long value);" }, { "code": null, "e": 24605, "s": 24556, "text": "Here, it takes a number of 100-nanosecond ticks." }, { "code": null, "e": 24757, "s": 24605, "text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the time represented by value." }, { "code": null, "e": 24892, "s": 24757, "text": "Exception: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue." }, { "code": null, "e": 24962, "s": 24892, "text": "Below programs illustrate the use of DateTime.AddTicks(Int64) Method:" }, { "code": null, "e": 24973, "s": 24962, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.AddTicks(Double) Methodusing System; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // adding the 3000 ticks // using AddTicks() method; DateTime date2 = date1.AddTicks(3000); // Display the date1 Console.WriteLine(\"No. of ticks before operation: \" + \"{0}\", date1.Ticks); // Display the date2 Console.WriteLine(\"\\nNo. of ticks after operation: \" + \"{0}\", date2.Ticks); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 25989, "s": 24973, "text": null }, { "code": null, "e": 26090, "s": 25989, "text": "No. of ticks before operation: 633979152150000000\n\nNo. of ticks after operation: 633979152150003000\n" }, { "code": null, "e": 26133, "s": 26090, "text": "Example 2: For ArgumentOutOfRangeException" }, { "code": "// C# program to demonstrate the// DateTime.AddTicks(long) Methodusing System; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MaxValue; // Display the date1 Console.WriteLine(\"DateTime before operation: \" + \"{0}\", date1.Ticks); // adding the 1 Ticks // using AddTicks() method; DateTime date2 = date1.AddTicks(1); // Display the date2 Console.WriteLine(\"\\nDateTime after operation: \" + \"{0}\", date2.Ticks); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\nThe resulting DateTime is \"+ \"greater than the DateTime.MaxValue \"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 27241, "s": 26133, "text": null }, { "code": null, "e": 27405, "s": 27241, "text": "DateTime before operation: 3155378975999999999\n\nThe resulting DateTime is greater than the DateTime.MaxValue \nException Thrown: System.ArgumentOutOfRangeException\n" }, { "code": null, "e": 27416, "s": 27405, "text": "Reference:" }, { "code": null, "e": 27509, "s": 27416, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addticks?view=netframework-4.7.2" }, { "code": null, "e": 27532, "s": 27509, "text": "CSharp DateTime Struct" }, { "code": null, "e": 27546, "s": 27532, "text": "CSharp-method" }, { "code": null, "e": 27549, "s": 27546, "text": "C#" }, { "code": null, "e": 27647, "s": 27549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27675, "s": 27647, "text": "C# Dictionary with examples" }, { "code": null, "e": 27690, "s": 27675, "text": "C# | Delegates" }, { "code": null, "e": 27708, "s": 27690, "text": "Destructors in C#" }, { "code": null, "e": 27731, "s": 27708, "text": "Extension Method in C#" }, { "code": null, "e": 27771, "s": 27731, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27802, "s": 27771, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27824, "s": 27802, "text": "C# | Abstract Classes" }, { "code": null, "e": 27840, "s": 27824, "text": "C# | Data Types" }, { "code": null, "e": 27868, "s": 27840, "text": "HashSet in C# with Examples" } ]
unordered_map hash_function() function in C++ STL - GeeksforGeeks
17 Dec, 2018 The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it. Syntax: unordered_map_name.hash_function() Parameter: The function does not accept any parameter. Return Value: The function returns the hash function. Time complexity: Time Complexity of this function is constant O(1). Below programs illustrate the unordered_map::hash_function() function. Example 1 // C++ program to illustrate the// unordered_map::hash_function() #include <bits/stdc++.h>using namespace std; int main(){ // declaration unordered_map<string, string> sample; // inserts key and elements sample.insert({ "Ankit", "MNNIT" }); sample.insert({ "Ram", "MNNIT" }); sample.insert({ "Manoj", "Trichy" }); sample.insert({ "geeks", "geeks" }); // use of hash_function unordered_map<string, string>::hasher fn = sample.hash_function(); cout << fn("geeks") << endl; // print the key and elements cout << "Key and Elements: "; for (auto it = sample.begin(); it != sample.end(); it++) { cout << "\n{" << it->first << ":" << it->second << "}, "; } return 0;} 15276750567035005396 Key and Elements: {geeks:geeks}, {Manoj:Trichy}, {Ankit:MNNIT}, {Ram:MNNIT}, Example 2 // C++ program to illustrate the// unordered_map::hash_function() #include <bits/stdc++.h>using namespace std; int main(){ // declaration unordered_map<int, int> sample; // inserts key and elements sample.insert({ 1, 5 }); sample.insert({ 2, 6 }); sample.insert({ 3, 6 }); sample.insert({ 4, 7 }); // use of hash_function unordered_map<int, int>::hasher fn = sample.hash_function(); cout << fn(4) << endl; // print the key and elements cout << "Key and Elements: "; for (auto it = sample.begin(); it != sample.end(); it++) { cout << "\n{" << it->first << ":" << it->second << "}, "; } return 0;} 4 Key and Elements: {4:7}, {3:6}, {1:5}, {2:6}, cpp-unordered_map cpp-unordered_map-functions C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) new and delete operators in C++ for dynamic memory std::string class in C++
[ { "code": null, "e": 24122, "s": 24094, "text": "\n17 Dec, 2018" }, { "code": null, "e": 24360, "s": 24122, "text": "The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it." }, { "code": null, "e": 24368, "s": 24360, "text": "Syntax:" }, { "code": null, "e": 24404, "s": 24368, "text": "unordered_map_name.hash_function()\n" }, { "code": null, "e": 24459, "s": 24404, "text": "Parameter: The function does not accept any parameter." }, { "code": null, "e": 24513, "s": 24459, "text": "Return Value: The function returns the hash function." }, { "code": null, "e": 24581, "s": 24513, "text": "Time complexity: Time Complexity of this function is constant O(1)." }, { "code": null, "e": 24652, "s": 24581, "text": "Below programs illustrate the unordered_map::hash_function() function." }, { "code": null, "e": 24662, "s": 24652, "text": "Example 1" }, { "code": "// C++ program to illustrate the// unordered_map::hash_function() #include <bits/stdc++.h>using namespace std; int main(){ // declaration unordered_map<string, string> sample; // inserts key and elements sample.insert({ \"Ankit\", \"MNNIT\" }); sample.insert({ \"Ram\", \"MNNIT\" }); sample.insert({ \"Manoj\", \"Trichy\" }); sample.insert({ \"geeks\", \"geeks\" }); // use of hash_function unordered_map<string, string>::hasher fn = sample.hash_function(); cout << fn(\"geeks\") << endl; // print the key and elements cout << \"Key and Elements: \"; for (auto it = sample.begin(); it != sample.end(); it++) { cout << \"\\n{\" << it->first << \":\" << it->second << \"}, \"; } return 0;}", "e": 25408, "s": 24662, "text": null }, { "code": null, "e": 25511, "s": 25408, "text": "15276750567035005396\nKey and Elements: \n{geeks:geeks}, \n{Manoj:Trichy}, \n{Ankit:MNNIT}, \n{Ram:MNNIT},\n" }, { "code": null, "e": 25521, "s": 25511, "text": "Example 2" }, { "code": "// C++ program to illustrate the// unordered_map::hash_function() #include <bits/stdc++.h>using namespace std; int main(){ // declaration unordered_map<int, int> sample; // inserts key and elements sample.insert({ 1, 5 }); sample.insert({ 2, 6 }); sample.insert({ 3, 6 }); sample.insert({ 4, 7 }); // use of hash_function unordered_map<int, int>::hasher fn = sample.hash_function(); cout << fn(4) << endl; // print the key and elements cout << \"Key and Elements: \"; for (auto it = sample.begin(); it != sample.end(); it++) { cout << \"\\n{\" << it->first << \":\" << it->second << \"}, \"; } return 0;}", "e": 26202, "s": 25521, "text": null }, { "code": null, "e": 26255, "s": 26202, "text": "4\nKey and Elements: \n{4:7}, \n{3:6}, \n{1:5}, \n{2:6},\n" }, { "code": null, "e": 26273, "s": 26255, "text": "cpp-unordered_map" }, { "code": null, "e": 26301, "s": 26273, "text": "cpp-unordered_map-functions" }, { "code": null, "e": 26305, "s": 26301, "text": "C++" }, { "code": null, "e": 26324, "s": 26305, "text": "Technical Scripter" }, { "code": null, "e": 26328, "s": 26324, "text": "CPP" }, { "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": 26435, "s": 26426, "text": "Comments" }, { "code": null, "e": 26448, "s": 26435, "text": "Old Comments" }, { "code": null, "e": 26476, "s": 26448, "text": "Operator Overloading in C++" }, { "code": null, "e": 26497, "s": 26476, "text": "Iterators in C++ STL" }, { "code": null, "e": 26517, "s": 26497, "text": "Polymorphism in C++" }, { "code": null, "e": 26550, "s": 26517, "text": "Friend class and function in C++" }, { "code": null, "e": 26574, "s": 26550, "text": "Sorting a vector in C++" }, { "code": null, "e": 26610, "s": 26574, "text": "Convert string to char array in C++" }, { "code": null, "e": 26634, "s": 26610, "text": "Inline Functions in C++" }, { "code": null, "e": 26678, "s": 26634, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 26729, "s": 26678, "text": "new and delete operators in C++ for dynamic memory" } ]
Find the first repeated word in a string in Python using Dictionary
In a given sentence there may be a word which get repeated before the sentence ends. In this python program, we are going to catch such word which is repeated in sentence. Below is the logical steps we are going to follow to get this result. Splits the given string into words separated by space. Then we convert these words into Dictionary using collections Traverse this list of words and check which first word has the frequency > 1 In the below program we use the counter method from the collections package to keep a count of the words. Live Demo from collections import Counter def Repeat_word(load): word = load.split(' ') dict = Counter(word) for value in word: if dict[value]>1: print (value) return if __name__ == "__main__": input = 'In good time in bad time friends are friends' Repeat_word(input) Running the above code gives us the following result − time
[ { "code": null, "e": 1304, "s": 1062, "text": "In a given sentence there may be a word which get repeated before the sentence ends. In this python program, we are going to catch such word which is repeated in sentence. Below is the logical steps we are going to follow to get this result." }, { "code": null, "e": 1359, "s": 1304, "text": "Splits the given string into words separated by space." }, { "code": null, "e": 1421, "s": 1359, "text": "Then we convert these words into Dictionary using collections" }, { "code": null, "e": 1498, "s": 1421, "text": "Traverse this list of words and check which first word has the frequency > 1" }, { "code": null, "e": 1604, "s": 1498, "text": "In the below program we use the counter method from the collections package to keep a count of the words." }, { "code": null, "e": 1615, "s": 1604, "text": " Live Demo" }, { "code": null, "e": 1915, "s": 1615, "text": "from collections import Counter\ndef Repeat_word(load):\n word = load.split(' ')\n dict = Counter(word)\n for value in word:\n if dict[value]>1:\n print (value)\n return\nif __name__ == \"__main__\":\n input = 'In good time in bad time friends are friends'\n Repeat_word(input)" }, { "code": null, "e": 1970, "s": 1915, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1975, "s": 1970, "text": "time" } ]
Vue.js v-on:keyup Directive
08 Jul, 2020 The v-on:keyup directive is a Vue.js directive used to add an event listener to an button in the keyboard. First, we will create a div element with id as app and let’s apply the v-on:keyup directive to the input element. Further, we can execute a function when we press the associated key. Syntax: v-on:keyup="function" Supported Keys: Following keys are supported: Enter key: .enter Tab key: .tab Delete key: .delete Esc key: .esc Up key: .up Down key: .down Left key: .left Right key: .right Parameters: This directive holds function as a value that will be executed when the key event occurs.Example: This example uses VueJS to toggle the visibility of a element with v-on:keyup using Enter key. HTML <!DOCTYPE html><html> <head> <title> VueJS v-on:keyup Directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-on:keyup directive </b> </div> <div id="canvas" style= "border:1px solid #000000; width: 600px;height: 200px;"> <div id="app" style= "text-align: center; padding-top: 40px;"> Write anything and press enter <input v-on:keyup.enter= "data = !data"> </input> <h1 v-if="data">GeeksforGeeks</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: false } }) </script></body> </html> Output: Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2020" }, { "code": null, "e": 318, "s": 28, "text": "The v-on:keyup directive is a Vue.js directive used to add an event listener to an button in the keyboard. First, we will create a div element with id as app and let’s apply the v-on:keyup directive to the input element. Further, we can execute a function when we press the associated key." }, { "code": null, "e": 326, "s": 318, "text": "Syntax:" }, { "code": null, "e": 348, "s": 326, "text": "v-on:keyup=\"function\"" }, { "code": null, "e": 394, "s": 348, "text": "Supported Keys: Following keys are supported:" }, { "code": null, "e": 412, "s": 394, "text": "Enter key: .enter" }, { "code": null, "e": 426, "s": 412, "text": "Tab key: .tab" }, { "code": null, "e": 446, "s": 426, "text": "Delete key: .delete" }, { "code": null, "e": 460, "s": 446, "text": "Esc key: .esc" }, { "code": null, "e": 472, "s": 460, "text": "Up key: .up" }, { "code": null, "e": 488, "s": 472, "text": "Down key: .down" }, { "code": null, "e": 504, "s": 488, "text": "Left key: .left" }, { "code": null, "e": 522, "s": 504, "text": "Right key: .right" }, { "code": null, "e": 727, "s": 522, "text": "Parameters: This directive holds function as a value that will be executed when the key event occurs.Example: This example uses VueJS to toggle the visibility of a element with v-on:keyup using Enter key." }, { "code": null, "e": 732, "s": 727, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS v-on:keyup Directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-on:keyup directive </b> </div> <div id=\"canvas\" style= \"border:1px solid #000000; width: 600px;height: 200px;\"> <div id=\"app\" style= \"text-align: center; padding-top: 40px;\"> Write anything and press enter <input v-on:keyup.enter= \"data = !data\"> </input> <h1 v-if=\"data\">GeeksforGeeks</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: false } }) </script></body> </html> ", "e": 1745, "s": 732, "text": null }, { "code": null, "e": 1753, "s": 1745, "text": "Output:" }, { "code": null, "e": 1760, "s": 1753, "text": "Vue.JS" }, { "code": null, "e": 1771, "s": 1760, "text": "JavaScript" }, { "code": null, "e": 1788, "s": 1771, "text": "Web Technologies" } ]
Worst-Fit Allocation in Operating Systems
03 Feb, 2021 For both fixed and dynamic memory allocation schemes, the operating system must keep a list of each memory location noting which are free and which are busy. Then as new jobs come into the system, the free partitions must be allocated. These partitions may be allocated in 4 ways: 1. First-Fit Memory Allocation 2. Best-Fit Memory Allocation 3. Worst-Fit Memory Allocation 4. Next-Fit Memory Allocation These are Contiguous memory allocation techniques. Worst-Fit Memory Allocation : In this allocation technique, the process traverses the whole memory and always search for the largest hole/partition, and then the process is placed in that hole/partition. It is a slow process because it has to traverse the entire memory to search the largest hole. Here is an example to understand Worst Fit-Allocation – Here Process P1=30K is allocated with the Worst Fit-Allocation technique, so it traverses the entire memory and selects memory size 400K which is the largest, and hence there is an internal fragmentation of 370K which is very large and so many other processes can also utilize this leftover space. Advantages of Worst-Fit Allocation : Since this process chooses the largest hole/partition, therefore there will be large internal fragmentation. Now, this internal fragmentation will be quite big so that other small processes can also be placed in that leftover partition. Disadvantages of Worst-Fit Allocation : It is a slow process because it traverses all the partitions in the memory and then selects the largest partition among all the partitions, which is a time-consuming process. aman singh 34 soumalimukhopadhyay memory-management Operating Systems-Memory Management GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Feb, 2021" }, { "code": null, "e": 265, "s": 28, "text": "For both fixed and dynamic memory allocation schemes, the operating system must keep a list of each memory location noting which are free and which are busy. Then as new jobs come into the system, the free partitions must be allocated. " }, { "code": null, "e": 311, "s": 265, "text": "These partitions may be allocated in 4 ways: " }, { "code": null, "e": 434, "s": 311, "text": "1. First-Fit Memory Allocation\n2. Best-Fit Memory Allocation\n3. Worst-Fit Memory Allocation\n4. Next-Fit Memory Allocation " }, { "code": null, "e": 486, "s": 434, "text": "These are Contiguous memory allocation techniques. " }, { "code": null, "e": 785, "s": 486, "text": "Worst-Fit Memory Allocation : In this allocation technique, the process traverses the whole memory and always search for the largest hole/partition, and then the process is placed in that hole/partition. It is a slow process because it has to traverse the entire memory to search the largest hole. " }, { "code": null, "e": 842, "s": 785, "text": "Here is an example to understand Worst Fit-Allocation – " }, { "code": null, "e": 1141, "s": 842, "text": "Here Process P1=30K is allocated with the Worst Fit-Allocation technique, so it traverses the entire memory and selects memory size 400K which is the largest, and hence there is an internal fragmentation of 370K which is very large and so many other processes can also utilize this leftover space. " }, { "code": null, "e": 1416, "s": 1141, "text": "Advantages of Worst-Fit Allocation : Since this process chooses the largest hole/partition, therefore there will be large internal fragmentation. Now, this internal fragmentation will be quite big so that other small processes can also be placed in that leftover partition. " }, { "code": null, "e": 1632, "s": 1416, "text": "Disadvantages of Worst-Fit Allocation : It is a slow process because it traverses all the partitions in the memory and then selects the largest partition among all the partitions, which is a time-consuming process. " }, { "code": null, "e": 1646, "s": 1632, "text": "aman singh 34" }, { "code": null, "e": 1666, "s": 1646, "text": "soumalimukhopadhyay" }, { "code": null, "e": 1684, "s": 1666, "text": "memory-management" }, { "code": null, "e": 1720, "s": 1684, "text": "Operating Systems-Memory Management" }, { "code": null, "e": 1728, "s": 1720, "text": "GATE CS" }, { "code": null, "e": 1746, "s": 1728, "text": "Operating Systems" }, { "code": null, "e": 1764, "s": 1746, "text": "Operating Systems" } ]
Stack contains() method in Java with Example
24 Dec, 2018 The java.util.Stack.contains() method is used to check whether a specific element is present in the Stack or not. So basically it is used to check if a Stack contains any particular element or not. Syntax: Stack.contains(Object element) Parameters: This method takes a mandatory parameter element which is of the type of Stack. This is the element that needs to be tested if it is present in the Stack or not. Return Value: This method returns True if the element is present in the Stack otherwise it returns False. Below programs illustrate the Java.util.Stack.contains() method: Program 1: // Java code to illustrate contains()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Check for "Geeks" in the Stack System.out.println("Does the Stack contains 'Geeks'? " + stack.contains("Geeks")); // Check for "4" in the Stack System.out.println("Does the Stack contains '4'? " + stack.contains("4")); // Check if the Queue contains "No" System.out.println("Does the Stack contains 'No'? " + stack.contains("No")); }} Stack: [Welcome, To, Geeks, 4, Geeks] Does the Stack contains 'Geeks'? true Does the Stack contains '4'? true Does the Stack contains 'No'? false Program 2: // Java code to illustrate contains()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Stack stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println("Stack: " + stack); // Check for "Geeks" in the Stack System.out.println("Does the Stack contains 'Geeks'? " + stack.contains("Geeks")); // Check for "4" in the Stack System.out.println("Does the Stack contains '4'? " + stack.contains("4")); // Check if the Stack contains "No" System.out.println("Does the Stack contains 'No'? " + stack.contains("No")); }} Stack: [10, 15, 30, 20, 5] Does the Stack contains 'Geeks'? false Does the Stack contains '4'? false Does the Stack contains 'No'? false Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 226, "s": 28, "text": "The java.util.Stack.contains() method is used to check whether a specific element is present in the Stack or not. So basically it is used to check if a Stack contains any particular element or not." }, { "code": null, "e": 234, "s": 226, "text": "Syntax:" }, { "code": null, "e": 265, "s": 234, "text": "Stack.contains(Object element)" }, { "code": null, "e": 438, "s": 265, "text": "Parameters: This method takes a mandatory parameter element which is of the type of Stack. This is the element that needs to be tested if it is present in the Stack or not." }, { "code": null, "e": 544, "s": 438, "text": "Return Value: This method returns True if the element is present in the Stack otherwise it returns False." }, { "code": null, "e": 609, "s": 544, "text": "Below programs illustrate the Java.util.Stack.contains() method:" }, { "code": null, "e": 620, "s": 609, "text": "Program 1:" }, { "code": "// Java code to illustrate contains()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Check for \"Geeks\" in the Stack System.out.println(\"Does the Stack contains 'Geeks'? \" + stack.contains(\"Geeks\")); // Check for \"4\" in the Stack System.out.println(\"Does the Stack contains '4'? \" + stack.contains(\"4\")); // Check if the Queue contains \"No\" System.out.println(\"Does the Stack contains 'No'? \" + stack.contains(\"No\")); }}", "e": 1570, "s": 620, "text": null }, { "code": null, "e": 1717, "s": 1570, "text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nDoes the Stack contains 'Geeks'? true\nDoes the Stack contains '4'? true\nDoes the Stack contains 'No'? false\n" }, { "code": null, "e": 1728, "s": 1717, "text": "Program 2:" }, { "code": "// Java code to illustrate contains()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Stack stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Check for \"Geeks\" in the Stack System.out.println(\"Does the Stack contains 'Geeks'? \" + stack.contains(\"Geeks\")); // Check for \"4\" in the Stack System.out.println(\"Does the Stack contains '4'? \" + stack.contains(\"4\")); // Check if the Stack contains \"No\" System.out.println(\"Does the Stack contains 'No'? \" + stack.contains(\"No\")); }}", "e": 2659, "s": 1728, "text": null }, { "code": null, "e": 2797, "s": 2659, "text": "Stack: [10, 15, 30, 20, 5]\nDoes the Stack contains 'Geeks'? false\nDoes the Stack contains '4'? false\nDoes the Stack contains 'No'? false\n" }, { "code": null, "e": 2817, "s": 2797, "text": "Java - util package" }, { "code": null, "e": 2834, "s": 2817, "text": "Java-Collections" }, { "code": null, "e": 2849, "s": 2834, "text": "Java-Functions" }, { "code": null, "e": 2860, "s": 2849, "text": "Java-Stack" }, { "code": null, "e": 2865, "s": 2860, "text": "Java" }, { "code": null, "e": 2870, "s": 2865, "text": "Java" }, { "code": null, "e": 2887, "s": 2870, "text": "Java-Collections" } ]
Ruby | pop() function
06 May, 2019 The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements. Syntax: pop(Elements) Parameters:Elements : This is the number of elements which are to be removed from the end of the given array. If this parameter is not used then it removes and returns the single last element of the given array. Returns: the removed elements. Example 1: # Initializing some arrays of elementsArray = [1, 2, 3, 4, 5, 6, 7] # Calling pop() functionA = Array.pop B = Array.pop(2)C = Array.pop(3)D = Array # Printing the removed elements puts "#{A}"puts "#{B}"puts "#{C}" # Printing the remaining arrayputs "#{D}" Output: 7 [5, 6] [2, 3, 4] [1] Example 2: # Initializing some arrays of elementsArray = ["a", "b", "c", "d", "e", "f", "g"] # Calling pop() functionA = Array.pop B = Array.pop(1)C = Array.pop(2)D = Array.pop(3)E = Array # Printing the removed elements puts "#{A}"puts "#{B}"puts "#{C}"puts "#{D}" # Printing the remaining arrayputs "#{E}" Output: g ["f"] ["d", "e"] ["a", "b", "c"] [] Reference: https://devdocs.io/ruby~2.5/array#method-i-pop Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2019" }, { "code": null, "e": 150, "s": 28, "text": "The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements." }, { "code": null, "e": 172, "s": 150, "text": "Syntax: pop(Elements)" }, { "code": null, "e": 384, "s": 172, "text": "Parameters:Elements : This is the number of elements which are to be removed from the end of the given array. If this parameter is not used then it removes and returns the single last element of the given array." }, { "code": null, "e": 415, "s": 384, "text": "Returns: the removed elements." }, { "code": null, "e": 426, "s": 415, "text": "Example 1:" }, { "code": "# Initializing some arrays of elementsArray = [1, 2, 3, 4, 5, 6, 7] # Calling pop() functionA = Array.pop B = Array.pop(2)C = Array.pop(3)D = Array # Printing the removed elements puts \"#{A}\"puts \"#{B}\"puts \"#{C}\" # Printing the remaining arrayputs \"#{D}\"", "e": 685, "s": 426, "text": null }, { "code": null, "e": 693, "s": 685, "text": "Output:" }, { "code": null, "e": 716, "s": 693, "text": "7\n[5, 6]\n[2, 3, 4]\n[1]" }, { "code": null, "e": 727, "s": 716, "text": "Example 2:" }, { "code": "# Initializing some arrays of elementsArray = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"] # Calling pop() functionA = Array.pop B = Array.pop(1)C = Array.pop(2)D = Array.pop(3)E = Array # Printing the removed elements puts \"#{A}\"puts \"#{B}\"puts \"#{C}\"puts \"#{D}\" # Printing the remaining arrayputs \"#{E}\"", "e": 1027, "s": 727, "text": null }, { "code": null, "e": 1035, "s": 1027, "text": "Output:" }, { "code": null, "e": 1074, "s": 1035, "text": "g\n[\"f\"]\n[\"d\", \"e\"]\n[\"a\", \"b\", \"c\"]\n[]\n" }, { "code": null, "e": 1132, "s": 1074, "text": "Reference: https://devdocs.io/ruby~2.5/array#method-i-pop" }, { "code": null, "e": 1145, "s": 1132, "text": "Ruby-Methods" }, { "code": null, "e": 1150, "s": 1145, "text": "Ruby" } ]
Matplotlib – Textbox Widgets
17 Feb, 2022 In this article, we are going to see matplotlib’s textbox widget. Matplotlib is a plotting library for the Python programming language. In this article, we will try to plot a graph for different powers(e.g. t^2, t^3, t^9, etc.) using textbox widget. The Textbox is a widget that accepts input from the user. Input can also be formulas so that we can generate a graph based on those formulas. To use this widget we use TextBox() function. It accepts two parameters Figure i.e. graph to use. Text to display with textbox i.e. Label to textBox. Below is the implementation of this widget: Python # Import modulesimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox # Adjust illustrationfig, ax = plt.subplots()fig.subplots_adjust(bottom=0.2) t = np.arange(-4.0, 4.0, 0.01)l, = ax.plot(t, np.zeros_like(t), lw=2) # Function to plot graph# according to expressiondef visualizeGraph(expr): ydata = eval(expr) l.set_ydata(ydata) ax.relim() ax.autoscale_view() plt.draw() # Adding TextBox to graphgraphBox = fig.add_axes([0.1, 0.05, 0.8, 0.075])txtBox = TextBox(graphBox, "Plot: ")txtBox.on_submit(visualizeGraph)txtBox.set_val("t**5") # Plot graphplt.show() Output: Explanation: In the above program, we created a graph for t2 as by default graph. In txtBox labelled as Plot: we can enter the formula we want to view the graph for. varshagumber28 Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Feb, 2022" }, { "code": null, "e": 278, "s": 28, "text": "In this article, we are going to see matplotlib’s textbox widget. Matplotlib is a plotting library for the Python programming language. In this article, we will try to plot a graph for different powers(e.g. t^2, t^3, t^9, etc.) using textbox widget." }, { "code": null, "e": 467, "s": 278, "text": "The Textbox is a widget that accepts input from the user. Input can also be formulas so that we can generate a graph based on those formulas. To use this widget we use TextBox() function. " }, { "code": null, "e": 493, "s": 467, "text": "It accepts two parameters" }, { "code": null, "e": 519, "s": 493, "text": "Figure i.e. graph to use." }, { "code": null, "e": 571, "s": 519, "text": "Text to display with textbox i.e. Label to textBox." }, { "code": null, "e": 615, "s": 571, "text": "Below is the implementation of this widget:" }, { "code": null, "e": 622, "s": 615, "text": "Python" }, { "code": "# Import modulesimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox # Adjust illustrationfig, ax = plt.subplots()fig.subplots_adjust(bottom=0.2) t = np.arange(-4.0, 4.0, 0.01)l, = ax.plot(t, np.zeros_like(t), lw=2) # Function to plot graph# according to expressiondef visualizeGraph(expr): ydata = eval(expr) l.set_ydata(ydata) ax.relim() ax.autoscale_view() plt.draw() # Adding TextBox to graphgraphBox = fig.add_axes([0.1, 0.05, 0.8, 0.075])txtBox = TextBox(graphBox, \"Plot: \")txtBox.on_submit(visualizeGraph)txtBox.set_val(\"t**5\") # Plot graphplt.show()", "e": 1230, "s": 622, "text": null }, { "code": null, "e": 1238, "s": 1230, "text": "Output:" }, { "code": null, "e": 1251, "s": 1238, "text": "Explanation:" }, { "code": null, "e": 1405, "s": 1251, "text": "In the above program, we created a graph for t2 as by default graph. In txtBox labelled as Plot: we can enter the formula we want to view the graph for. " }, { "code": null, "e": 1420, "s": 1405, "text": "varshagumber28" }, { "code": null, "e": 1427, "s": 1420, "text": "Picked" }, { "code": null, "e": 1445, "s": 1427, "text": "Python-matplotlib" }, { "code": null, "e": 1452, "s": 1445, "text": "Python" } ]
How to map, reduce and filter a Set element using JavaScript ?
08 May, 2020 The map(), reduce() and filter() are array functions that transform the array according to the applied function and return the updated array. They are used to write simple, short and clean codes for modifying an array instead of using the loops. map() method: It applies a given function on all the elements of the array and returns the updated array. It is the simpler and shorter code instead of a loop. The map is similar to the following code:arr = new Array(1, 2, 3, 6, 5, 4);for(int i = 0; i < 6; i++) { arr[i] *= 3;}Syntax:array.map(function_to_be_applied)array.map(function (args) { // code; }) Example:function triple(n){ return n*3;} arr = new Array(1, 2, 3, 6, 5, 4); var new_arr = arr.map(triple)console.log(new_arr);Output: [ 3, 6, 9, 18, 15, 12 ] arr = new Array(1, 2, 3, 6, 5, 4);for(int i = 0; i < 6; i++) { arr[i] *= 3;} Syntax: array.map(function_to_be_applied) array.map(function (args) { // code; }) Example: function triple(n){ return n*3;} arr = new Array(1, 2, 3, 6, 5, 4); var new_arr = arr.map(triple)console.log(new_arr); Output: [ 3, 6, 9, 18, 15, 12 ] reduce() method: It reduces all the elements of the array to a single value by repeatedly applying a function. It is an alternative of using a loop and updating the result for every scanned element. Reduce can be used in place of the following code:arr = new Array(1, 2, 3, 6, 5, 4);result = 1for(int i = 0; i < 6; i++) { result = result * arr[i];}Syntax:array.reduce(function_to_be_applied)array.reduce(function (args) { // code; }) Example:function product(a, b){ return a * b;}arr = new Array(1, 2, 3, 6, 5, 4); var product_of_arr = arr.reduce(product)console.log(product_of_arr)Output:720 arr = new Array(1, 2, 3, 6, 5, 4);result = 1for(int i = 0; i < 6; i++) { result = result * arr[i];} Syntax: array.reduce(function_to_be_applied) array.reduce(function (args) { // code; }) Example: function product(a, b){ return a * b;}arr = new Array(1, 2, 3, 6, 5, 4); var product_of_arr = arr.reduce(product)console.log(product_of_arr) Output: 720 filter() method: It filters the elements of the array that return false for the applied condition and returns the array which contains elements that satisfy the applied condition. It is a simpler and shorter code instead of the below code using a loop:arr = new Array(1, 2, 3, 6, 5, 4);new_arr = {}for(int i = 0; i < 6; i++) { if(arr[i] % 2 == 0) { new_arr.push(arr[i]); }}Syntax:array.filter(function_to_be_applied)array.filter(function (args) { // condition; }) Example:arr = new Array(1, 2, 3, 6, 5, 4);var new_arr = arr.filter(function (x){ return x % 2==0;}); console.log(new_arr)Output:[ 2, 6, 4 ] arr = new Array(1, 2, 3, 6, 5, 4);new_arr = {}for(int i = 0; i < 6; i++) { if(arr[i] % 2 == 0) { new_arr.push(arr[i]); }} Syntax: array.filter(function_to_be_applied) array.filter(function (args) { // condition; }) Example: arr = new Array(1, 2, 3, 6, 5, 4);var new_arr = arr.filter(function (x){ return x % 2==0;}); console.log(new_arr) Output: [ 2, 6, 4 ] JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 May, 2020" }, { "code": null, "e": 274, "s": 28, "text": "The map(), reduce() and filter() are array functions that transform the array according to the applied function and return the updated array. They are used to write simple, short and clean codes for modifying an array instead of using the loops." }, { "code": null, "e": 805, "s": 274, "text": "map() method: It applies a given function on all the elements of the array and returns the updated array. It is the simpler and shorter code instead of a loop. The map is similar to the following code:arr = new Array(1, 2, 3, 6, 5, 4);for(int i = 0; i < 6; i++) { arr[i] *= 3;}Syntax:array.map(function_to_be_applied)array.map(function (args) {\n // code;\n})\nExample:function triple(n){ return n*3;} arr = new Array(1, 2, 3, 6, 5, 4); var new_arr = arr.map(triple)console.log(new_arr);Output: \n[ 3, 6, 9, 18, 15, 12 ]\n" }, { "code": "arr = new Array(1, 2, 3, 6, 5, 4);for(int i = 0; i < 6; i++) { arr[i] *= 3;}", "e": 885, "s": 805, "text": null }, { "code": null, "e": 893, "s": 885, "text": "Syntax:" }, { "code": null, "e": 927, "s": 893, "text": "array.map(function_to_be_applied)" }, { "code": null, "e": 972, "s": 927, "text": "array.map(function (args) {\n // code;\n})\n" }, { "code": null, "e": 981, "s": 972, "text": "Example:" }, { "code": "function triple(n){ return n*3;} arr = new Array(1, 2, 3, 6, 5, 4); var new_arr = arr.map(triple)console.log(new_arr);", "e": 1107, "s": 981, "text": null }, { "code": null, "e": 1141, "s": 1107, "text": "Output: \n[ 3, 6, 9, 18, 15, 12 ]\n" }, { "code": null, "e": 1745, "s": 1141, "text": "reduce() method: It reduces all the elements of the array to a single value by repeatedly applying a function. It is an alternative of using a loop and updating the result for every scanned element. Reduce can be used in place of the following code:arr = new Array(1, 2, 3, 6, 5, 4);result = 1for(int i = 0; i < 6; i++) { result = result * arr[i];}Syntax:array.reduce(function_to_be_applied)array.reduce(function (args) {\n // code;\n})\nExample:function product(a, b){ return a * b;}arr = new Array(1, 2, 3, 6, 5, 4); var product_of_arr = arr.reduce(product)console.log(product_of_arr)Output:720" }, { "code": "arr = new Array(1, 2, 3, 6, 5, 4);result = 1for(int i = 0; i < 6; i++) { result = result * arr[i];}", "e": 1848, "s": 1745, "text": null }, { "code": null, "e": 1856, "s": 1848, "text": "Syntax:" }, { "code": null, "e": 1893, "s": 1856, "text": "array.reduce(function_to_be_applied)" }, { "code": null, "e": 1941, "s": 1893, "text": "array.reduce(function (args) {\n // code;\n})\n" }, { "code": null, "e": 1950, "s": 1941, "text": "Example:" }, { "code": "function product(a, b){ return a * b;}arr = new Array(1, 2, 3, 6, 5, 4); var product_of_arr = arr.reduce(product)console.log(product_of_arr)", "e": 2095, "s": 1950, "text": null }, { "code": null, "e": 2103, "s": 2095, "text": "Output:" }, { "code": null, "e": 2107, "s": 2103, "text": "720" }, { "code": null, "e": 2744, "s": 2107, "text": "filter() method: It filters the elements of the array that return false for the applied condition and returns the array which contains elements that satisfy the applied condition. It is a simpler and shorter code instead of the below code using a loop:arr = new Array(1, 2, 3, 6, 5, 4);new_arr = {}for(int i = 0; i < 6; i++) { if(arr[i] % 2 == 0) { new_arr.push(arr[i]); }}Syntax:array.filter(function_to_be_applied)array.filter(function (args) {\n // condition;\n})\nExample:arr = new Array(1, 2, 3, 6, 5, 4);var new_arr = arr.filter(function (x){ return x % 2==0;}); console.log(new_arr)Output:[ 2, 6, 4 ]" }, { "code": "arr = new Array(1, 2, 3, 6, 5, 4);new_arr = {}for(int i = 0; i < 6; i++) { if(arr[i] % 2 == 0) { new_arr.push(arr[i]); }}", "e": 2891, "s": 2744, "text": null }, { "code": null, "e": 2899, "s": 2891, "text": "Syntax:" }, { "code": null, "e": 2936, "s": 2899, "text": "array.filter(function_to_be_applied)" }, { "code": null, "e": 2989, "s": 2936, "text": "array.filter(function (args) {\n // condition;\n})\n" }, { "code": null, "e": 2998, "s": 2989, "text": "Example:" }, { "code": "arr = new Array(1, 2, 3, 6, 5, 4);var new_arr = arr.filter(function (x){ return x % 2==0;}); console.log(new_arr)", "e": 3116, "s": 2998, "text": null }, { "code": null, "e": 3124, "s": 3116, "text": "Output:" }, { "code": null, "e": 3136, "s": 3124, "text": "[ 2, 6, 4 ]" }, { "code": null, "e": 3152, "s": 3136, "text": "JavaScript-Misc" }, { "code": null, "e": 3159, "s": 3152, "text": "Picked" }, { "code": null, "e": 3170, "s": 3159, "text": "JavaScript" }, { "code": null, "e": 3187, "s": 3170, "text": "Web Technologies" }, { "code": null, "e": 3214, "s": 3187, "text": "Web technologies Questions" } ]
HashSet toString() method in Java with Example
24 Dec, 2018 The toString() method of Java HashSet is used to return a string representation of the elements of the Collection. The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation. Syntax: public String toString() Parameter The method does not take any parameters. Return This method returns a String representation of the collection. Below examples illustrate the toString() method: Example 1: // Java program to demonstrate// HashSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty HashSet HashSet<String> abs = new HashSet<String>(); // Use add() method // to add elements to the Collection abs.add("Welcome"); abs.add("To"); abs.add("Geeks"); abs.add("For"); abs.add("Geeks"); // Using toString() method System.out.println(abs.toString()); }} [Geeks, For, Welcome, To] Example 2: // Java program to demonstrate// HashSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty HashSet HashSet<Integer> abs = new HashSet<Integer>(); // Use add() method // to add elements to the Collection abs.add(10); abs.add(20); abs.add(30); abs.add(40); // Using toString() method System.out.println(abs.toString()); }} [20, 40, 10, 30] Java - util package Java-Collections Java-Functions java-hashset Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 143, "s": 28, "text": "The toString() method of Java HashSet is used to return a string representation of the elements of the Collection." }, { "code": null, "e": 438, "s": 143, "text": "The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation." }, { "code": null, "e": 446, "s": 438, "text": "Syntax:" }, { "code": null, "e": 471, "s": 446, "text": "public String toString()" }, { "code": null, "e": 522, "s": 471, "text": "Parameter The method does not take any parameters." }, { "code": null, "e": 592, "s": 522, "text": "Return This method returns a String representation of the collection." }, { "code": null, "e": 641, "s": 592, "text": "Below examples illustrate the toString() method:" }, { "code": null, "e": 652, "s": 641, "text": "Example 1:" }, { "code": "// Java program to demonstrate// HashSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty HashSet HashSet<String> abs = new HashSet<String>(); // Use add() method // to add elements to the Collection abs.add(\"Welcome\"); abs.add(\"To\"); abs.add(\"Geeks\"); abs.add(\"For\"); abs.add(\"Geeks\"); // Using toString() method System.out.println(abs.toString()); }}", "e": 1185, "s": 652, "text": null }, { "code": null, "e": 1212, "s": 1185, "text": "[Geeks, For, Welcome, To]\n" }, { "code": null, "e": 1223, "s": 1212, "text": "Example 2:" }, { "code": "// Java program to demonstrate// HashSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty HashSet HashSet<Integer> abs = new HashSet<Integer>(); // Use add() method // to add elements to the Collection abs.add(10); abs.add(20); abs.add(30); abs.add(40); // Using toString() method System.out.println(abs.toString()); }}", "e": 1716, "s": 1223, "text": null }, { "code": null, "e": 1734, "s": 1716, "text": "[20, 40, 10, 30]\n" }, { "code": null, "e": 1754, "s": 1734, "text": "Java - util package" }, { "code": null, "e": 1771, "s": 1754, "text": "Java-Collections" }, { "code": null, "e": 1786, "s": 1771, "text": "Java-Functions" }, { "code": null, "e": 1799, "s": 1786, "text": "java-hashset" }, { "code": null, "e": 1804, "s": 1799, "text": "Java" }, { "code": null, "e": 1809, "s": 1804, "text": "Java" }, { "code": null, "e": 1826, "s": 1809, "text": "Java-Collections" } ]
Understanding Activity Lifecycle to Retain UI Data when Back Pressed in Android
28 Jul, 2021 This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application. The official documentation states that onBackPressed() method is called when the activity has detected the user’s press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want. So, through this article, we will show you how you can override this method and retain the activity data. But before that, it is necessary to understand the Activity Lifecycle in Android. Refer to this article for a better understanding of the Activity Lifecycle in Android: Activity Lifecycle in Android with Demo App. This article has 4 parts: Create a template code to understand the navigation key events and linked Activity Lifecycle methods (Skip if you know Activity Lifecycle)Override the on back pressed methodTesting EditTextTesting TextView Create a template code to understand the navigation key events and linked Activity Lifecycle methods (Skip if you know Activity Lifecycle) Override the on back pressed method Testing EditText Testing TextView Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Override all the methods in Activity Lifecycle We implemented a Toast message in every method to understand which method is called when during the Activity Lifecycle. Now simply run the project on a device or an emulator. Kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext, "onCreate", Toast.LENGTH_SHORT).show() } } override fun onPause() { super.onPause() Toast.makeText(applicationContext, "onPause", Toast.LENGTH_SHORT).show() } override fun onStop() { super.onStop() Toast.makeText(applicationContext, "onStop", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Toast.makeText(applicationContext, "onDestroy", Toast.LENGTH_SHORT).show() } override fun onRestart() { super.onRestart() Toast.makeText(applicationContext, "onRestart", Toast.LENGTH_SHORT).show() } override fun onStart() { super.onStart() Toast.makeText(applicationContext, "onStart", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Toast.makeText(applicationContext, "onResume", Toast.LENGTH_SHORT).show() }} Step 3: Run the program When the application starts: onCreate, onStart, onResumeWhen App Overview Button is pressed: onPause, onStopWhen Home Button is pressed: onPause, onStopWhen Back Button is pressed: onPause, onStop, onDestroy When the application starts: onCreate, onStart, onResume When App Overview Button is pressed: onPause, onStop When Home Button is pressed: onPause, onStop When Back Button is pressed: onPause, onStop, onDestroy Output: Observation: We can see that in any case other than the back press, the activity is stopped. Basically, it is not destroyed and data is retained. However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states. But we do not want to lose this data. To retain the data, we need to override the back pressed method. Back pressed method by nature destroys the activity. We will make changes in such a way that the activity will stop but not destroy. Continue reading. Please read the comments in the code. Kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext, "onCreate", Toast.LENGTH_SHORT).show() } // Overriding onBackPressed method override fun onBackPressed() { // Implement this method to stop // the activity and go back this.moveTaskToBack(true) } override fun onPause() { super.onPause() Toast.makeText(applicationContext, "onPause", Toast.LENGTH_SHORT).show() } override fun onStop() { super.onStop() Toast.makeText(applicationContext, "onStop", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Toast.makeText(applicationContext, "onDestroy", Toast.LENGTH_SHORT).show() } override fun onRestart() { super.onRestart() Toast.makeText(applicationContext, "onRestart", Toast.LENGTH_SHORT).show() } override fun onStart() { super.onStart() Toast.makeText(applicationContext, "onStart", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Toast.makeText(applicationContext, "onResume", Toast.LENGTH_SHORT).show() }} Output: Now we can observe that on the back press, the activity will stop but not destroy. We shall now implement some UI for testing if this actually works. Keep reading. Step 1: Add EditText in the layout file (activity_main.xml) XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/et1" android:layout_width="match_parent" android:layout_height="50sp" android:textSize="25sp" android:inputType="text" android:layout_centerInParent="true"/> </RelativeLayout> For testing the EditText, we need not code anything in the main code other than what is specified in the previous (Override the on-back pressed method) code. Input: Type anything in the EditText and press the back button. Return back to the app and you will notice that text is retained in the EditText bar. Output: The text in the EditText is retained. This means our method works fine. We shall now test it on a TextView. Keep reading. Step 1: Add a TextView and a Button in the layout file (activity_main.xml) XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click the button" android:textSize="40sp" android:layout_centerInParent="true"/> <Button android:id="@+id/btn1" android:layout_below="@id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click" android:layout_centerHorizontal="true"/> </RelativeLayout> Step 2: Add functionality to these elements via the main code (MainActivity.kt) Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext, "onCreate", Toast.LENGTH_SHORT).show() // TextView and Button val tv1 = findViewById<TextView>(R.id.tv1) val btn1 = findViewById<Button>(R.id.btn1) // A code to increment a variable and // display it on TextView on Button Click var k = 0 btn1.setOnClickListener { tv1.text = k.toString() k++ } } override fun onBackPressed() { this.moveTaskToBack(true) } override fun onPause() { super.onPause() Toast.makeText(applicationContext, "onPause", Toast.LENGTH_SHORT).show() } override fun onStop() { super.onStop() Toast.makeText(applicationContext, "onStop", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Toast.makeText(applicationContext, "onDestroy", Toast.LENGTH_SHORT).show() } override fun onRestart() { super.onRestart() Toast.makeText(applicationContext, "onRestart", Toast.LENGTH_SHORT).show() } override fun onStart() { super.onStart() Toast.makeText(applicationContext, "onStart", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Toast.makeText(applicationContext, "onResume", Toast.LENGTH_SHORT).show() }} Input: Keep clicking the button, the number in TextView will keep incrementing. Now try the back button and open the app again. The text is retained in the TextView. Output: Our method works perfectly fine. Now use this method in your codes to retain the activity data. Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 449, "s": 28, "text": "This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application. The official documentation states that onBackPressed() method is called when the activity has detected the user’s press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want." }, { "code": null, "e": 769, "s": 449, "text": "So, through this article, we will show you how you can override this method and retain the activity data. But before that, it is necessary to understand the Activity Lifecycle in Android. Refer to this article for a better understanding of the Activity Lifecycle in Android: Activity Lifecycle in Android with Demo App." }, { "code": null, "e": 795, "s": 769, "text": "This article has 4 parts:" }, { "code": null, "e": 1001, "s": 795, "text": "Create a template code to understand the navigation key events and linked Activity Lifecycle methods (Skip if you know Activity Lifecycle)Override the on back pressed methodTesting EditTextTesting TextView" }, { "code": null, "e": 1140, "s": 1001, "text": "Create a template code to understand the navigation key events and linked Activity Lifecycle methods (Skip if you know Activity Lifecycle)" }, { "code": null, "e": 1176, "s": 1140, "text": "Override the on back pressed method" }, { "code": null, "e": 1193, "s": 1176, "text": "Testing EditText" }, { "code": null, "e": 1210, "s": 1193, "text": "Testing TextView" }, { "code": null, "e": 1257, "s": 1210, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 1496, "s": 1257, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 1551, "s": 1496, "text": "Step 2: Override all the methods in Activity Lifecycle" }, { "code": null, "e": 1726, "s": 1551, "text": "We implemented a Toast message in every method to understand which method is called when during the Activity Lifecycle. Now simply run the project on a device or an emulator." }, { "code": null, "e": 1733, "s": 1726, "text": "Kotlin" }, { "code": "class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext, \"onCreate\", Toast.LENGTH_SHORT).show() } } override fun onPause() { super.onPause() Toast.makeText(applicationContext, \"onPause\", Toast.LENGTH_SHORT).show() } override fun onStop() { super.onStop() Toast.makeText(applicationContext, \"onStop\", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Toast.makeText(applicationContext, \"onDestroy\", Toast.LENGTH_SHORT).show() } override fun onRestart() { super.onRestart() Toast.makeText(applicationContext, \"onRestart\", Toast.LENGTH_SHORT).show() } override fun onStart() { super.onStart() Toast.makeText(applicationContext, \"onStart\", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Toast.makeText(applicationContext, \"onResume\", Toast.LENGTH_SHORT).show() }}", "e": 2868, "s": 1733, "text": null }, { "code": null, "e": 2892, "s": 2868, "text": "Step 3: Run the program" }, { "code": null, "e": 3100, "s": 2892, "text": "When the application starts: onCreate, onStart, onResumeWhen App Overview Button is pressed: onPause, onStopWhen Home Button is pressed: onPause, onStopWhen Back Button is pressed: onPause, onStop, onDestroy" }, { "code": null, "e": 3157, "s": 3100, "text": "When the application starts: onCreate, onStart, onResume" }, { "code": null, "e": 3210, "s": 3157, "text": "When App Overview Button is pressed: onPause, onStop" }, { "code": null, "e": 3255, "s": 3210, "text": "When Home Button is pressed: onPause, onStop" }, { "code": null, "e": 3311, "s": 3255, "text": "When Back Button is pressed: onPause, onStop, onDestroy" }, { "code": null, "e": 3319, "s": 3311, "text": "Output:" }, { "code": null, "e": 3332, "s": 3319, "text": "Observation:" }, { "code": null, "e": 3636, "s": 3332, "text": "We can see that in any case other than the back press, the activity is stopped. Basically, it is not destroyed and data is retained. However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states." }, { "code": null, "e": 3890, "s": 3636, "text": "But we do not want to lose this data. To retain the data, we need to override the back pressed method. Back pressed method by nature destroys the activity. We will make changes in such a way that the activity will stop but not destroy. Continue reading." }, { "code": null, "e": 3928, "s": 3890, "text": "Please read the comments in the code." }, { "code": null, "e": 3935, "s": 3928, "text": "Kotlin" }, { "code": "class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext, \"onCreate\", Toast.LENGTH_SHORT).show() } // Overriding onBackPressed method override fun onBackPressed() { // Implement this method to stop // the activity and go back this.moveTaskToBack(true) } override fun onPause() { super.onPause() Toast.makeText(applicationContext, \"onPause\", Toast.LENGTH_SHORT).show() } override fun onStop() { super.onStop() Toast.makeText(applicationContext, \"onStop\", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Toast.makeText(applicationContext, \"onDestroy\", Toast.LENGTH_SHORT).show() } override fun onRestart() { super.onRestart() Toast.makeText(applicationContext, \"onRestart\", Toast.LENGTH_SHORT).show() } override fun onStart() { super.onStart() Toast.makeText(applicationContext, \"onStart\", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Toast.makeText(applicationContext, \"onResume\", Toast.LENGTH_SHORT).show() }}", "e": 5246, "s": 3935, "text": null }, { "code": null, "e": 5254, "s": 5246, "text": "Output:" }, { "code": null, "e": 5418, "s": 5254, "text": "Now we can observe that on the back press, the activity will stop but not destroy. We shall now implement some UI for testing if this actually works. Keep reading." }, { "code": null, "e": 5478, "s": 5418, "text": "Step 1: Add EditText in the layout file (activity_main.xml)" }, { "code": null, "e": 5482, "s": 5478, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <EditText android:id=\"@+id/et1\" android:layout_width=\"match_parent\" android:layout_height=\"50sp\" android:textSize=\"25sp\" android:inputType=\"text\" android:layout_centerInParent=\"true\"/> </RelativeLayout>", "e": 6043, "s": 5482, "text": null }, { "code": null, "e": 6201, "s": 6043, "text": "For testing the EditText, we need not code anything in the main code other than what is specified in the previous (Override the on-back pressed method) code." }, { "code": null, "e": 6208, "s": 6201, "text": "Input:" }, { "code": null, "e": 6351, "s": 6208, "text": "Type anything in the EditText and press the back button. Return back to the app and you will notice that text is retained in the EditText bar." }, { "code": null, "e": 6359, "s": 6351, "text": "Output:" }, { "code": null, "e": 6481, "s": 6359, "text": "The text in the EditText is retained. This means our method works fine. We shall now test it on a TextView. Keep reading." }, { "code": null, "e": 6556, "s": 6481, "text": "Step 1: Add a TextView and a Button in the layout file (activity_main.xml)" }, { "code": null, "e": 6560, "s": 6556, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/tv1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Click the button\" android:textSize=\"40sp\" android:layout_centerInParent=\"true\"/> <Button android:id=\"@+id/btn1\" android:layout_below=\"@id/tv1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Click\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>", "e": 7405, "s": 6560, "text": null }, { "code": null, "e": 7485, "s": 7405, "text": "Step 2: Add functionality to these elements via the main code (MainActivity.kt)" }, { "code": null, "e": 7492, "s": 7485, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext, \"onCreate\", Toast.LENGTH_SHORT).show() // TextView and Button val tv1 = findViewById<TextView>(R.id.tv1) val btn1 = findViewById<Button>(R.id.btn1) // A code to increment a variable and // display it on TextView on Button Click var k = 0 btn1.setOnClickListener { tv1.text = k.toString() k++ } } override fun onBackPressed() { this.moveTaskToBack(true) } override fun onPause() { super.onPause() Toast.makeText(applicationContext, \"onPause\", Toast.LENGTH_SHORT).show() } override fun onStop() { super.onStop() Toast.makeText(applicationContext, \"onStop\", Toast.LENGTH_SHORT).show() } override fun onDestroy() { super.onDestroy() Toast.makeText(applicationContext, \"onDestroy\", Toast.LENGTH_SHORT).show() } override fun onRestart() { super.onRestart() Toast.makeText(applicationContext, \"onRestart\", Toast.LENGTH_SHORT).show() } override fun onStart() { super.onStart() Toast.makeText(applicationContext, \"onStart\", Toast.LENGTH_SHORT).show() } override fun onResume() { super.onResume() Toast.makeText(applicationContext, \"onResume\", Toast.LENGTH_SHORT).show() }}", "e": 9186, "s": 7492, "text": null }, { "code": null, "e": 9193, "s": 9186, "text": "Input:" }, { "code": null, "e": 9352, "s": 9193, "text": "Keep clicking the button, the number in TextView will keep incrementing. Now try the back button and open the app again. The text is retained in the TextView." }, { "code": null, "e": 9360, "s": 9352, "text": "Output:" }, { "code": null, "e": 9456, "s": 9360, "text": "Our method works perfectly fine. Now use this method in your codes to retain the activity data." }, { "code": null, "e": 9471, "s": 9456, "text": "Kotlin Android" }, { "code": null, "e": 9479, "s": 9471, "text": "Android" }, { "code": null, "e": 9486, "s": 9479, "text": "Kotlin" }, { "code": null, "e": 9494, "s": 9486, "text": "Android" } ]
Matplotlib.pyplot.subplots_adjust() in Python
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. The subplots_adjust() function in pyplot module of matplotlib library is used to tune the subplot layout. Syntax: matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) Parameters: This method accept the following parameters that are described below: left : This parameter is the left side of the subplots of the figure. right : This parameter is the right side of the subplots of the figure. bottom : This parameter is the bottom of the subplots of the figure. top : This parameter is the top of the subplots of the figure. wspace : This parameter is the amount of width reserved for space between subplots expressed as a fraction of the average axis width. hspace : This parameter is the amount of height reserved for space between subplots expressed as a fraction of the average axis height. Below examples illustrate the matplotlib.pyplot.subplots_adjust() function in matplotlib.pyplot: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as plt x = [1, 12, 3, 9]y = [1, 4, 9, 16]labels = ['Geeks1', 'Geeks2', 'Geeks3', 'Geeks4'] plt.plot(x, y)plt.xticks(x, labels, rotation ='vertical') plt.margins(0.2)plt.subplots_adjust(bottom = 0.15) plt.title('matplotlib.pyplot.subplots_adjust() Example')plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox fig, ax = plt.subplots()plt.subplots_adjust(bottom = 0.2)t = np.arange(-2.0, 2.0, 0.001)s = np.sin(t)+np.cos(2 * t)initial_text = "sin(t) + cos(2t)"l, = plt.plot(t, s, lw = 2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.4, 0.05, 0.3, 0.075])text_box = TextBox(axbox, 'Formula Used : ', initial = initial_text) text_box.on_submit(submit) fig.suptitle('matplotlib.pyplot.subplots_adjust() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2020" }, { "code": null, "e": 357, "s": 52, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc." }, { "code": null, "e": 463, "s": 357, "text": "The subplots_adjust() function in pyplot module of matplotlib library is used to tune the subplot layout." }, { "code": null, "e": 577, "s": 463, "text": "Syntax: matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)" }, { "code": null, "e": 659, "s": 577, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 729, "s": 659, "text": "left : This parameter is the left side of the subplots of the figure." }, { "code": null, "e": 801, "s": 729, "text": "right : This parameter is the right side of the subplots of the figure." }, { "code": null, "e": 870, "s": 801, "text": "bottom : This parameter is the bottom of the subplots of the figure." }, { "code": null, "e": 933, "s": 870, "text": "top : This parameter is the top of the subplots of the figure." }, { "code": null, "e": 1067, "s": 933, "text": "wspace : This parameter is the amount of width reserved for space between subplots expressed as a fraction of the average axis width." }, { "code": null, "e": 1203, "s": 1067, "text": "hspace : This parameter is the amount of height reserved for space between subplots expressed as a fraction of the average axis height." }, { "code": null, "e": 1300, "s": 1203, "text": "Below examples illustrate the matplotlib.pyplot.subplots_adjust() function in matplotlib.pyplot:" }, { "code": null, "e": 1311, "s": 1300, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt x = [1, 12, 3, 9]y = [1, 4, 9, 16]labels = ['Geeks1', 'Geeks2', 'Geeks3', 'Geeks4'] plt.plot(x, y)plt.xticks(x, labels, rotation ='vertical') plt.margins(0.2)plt.subplots_adjust(bottom = 0.15) plt.title('matplotlib.pyplot.subplots_adjust() Example')plt.show()", "e": 1650, "s": 1311, "text": null }, { "code": null, "e": 1658, "s": 1650, "text": "Output:" }, { "code": null, "e": 1669, "s": 1658, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox fig, ax = plt.subplots()plt.subplots_adjust(bottom = 0.2)t = np.arange(-2.0, 2.0, 0.001)s = np.sin(t)+np.cos(2 * t)initial_text = \"sin(t) + cos(2t)\"l, = plt.plot(t, s, lw = 2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.4, 0.05, 0.3, 0.075])text_box = TextBox(axbox, 'Formula Used : ', initial = initial_text) text_box.on_submit(submit) fig.suptitle('matplotlib.pyplot.subplots_adjust() Example')plt.show()", "e": 2332, "s": 1669, "text": null }, { "code": null, "e": 2340, "s": 2332, "text": "Output:" }, { "code": null, "e": 2358, "s": 2340, "text": "Python-matplotlib" }, { "code": null, "e": 2365, "s": 2358, "text": "Python" }, { "code": null, "e": 2463, "s": 2365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2481, "s": 2463, "text": "Python Dictionary" }, { "code": null, "e": 2523, "s": 2481, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2555, "s": 2523, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2581, "s": 2555, "text": "Python String | replace()" }, { "code": null, "e": 2610, "s": 2581, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2637, "s": 2610, "text": "Python Classes and Objects" }, { "code": null, "e": 2658, "s": 2637, "text": "Python OOPs Concepts" }, { "code": null, "e": 2681, "s": 2658, "text": "Introduction To PYTHON" }, { "code": null, "e": 2712, "s": 2681, "text": "Python | os.path.join() method" } ]
Find the largest rectangle of 1’s with swapping of columns allowed
27 Dec, 2021 Given a matrix with 0 and 1’s, find the largest rectangle of all 1’s in the matrix. The rectangle can be formed by swapping any pair of columns of given matrix.Example: Input: bool mat[][] = { {0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0} }; Output: 6 The largest rectangle's area is 6. The rectangle can be formed by swapping column 2 with 3 The matrix after swapping will be 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 Input: bool mat[R][C] = { {0, 1, 0, 1, 0}, {0, 1, 1, 1, 1}, {1, 1, 1, 0, 1}, {1, 1, 1, 1, 1} }; Output: 9 The idea is to use an auxiliary matrix to store count of consecutive 1’s in every column. Once we have these counts, we sort all rows of auxiliary matrix in non-increasing order of counts. Finally traverse the sorted rows to find the maximum area. Note : After forming the auxiliary matrix each row becomes independent, hence we can swap or sort each row independently.It is because we can only swap columns, so we have made each row independent and find the max area of rectangle possible with row and column. Below are detailed steps for first example mentioned above.Step 1: First of all, calculate no. of consecutive 1’s in every column. An auxiliary array hist[][] is used to store the counts of consecutive 1’s. So for the above first example, contents of hist[R][C] would be 0 1 0 1 0 0 2 0 2 1 1 3 0 3 0 Time complexity of this step is O(R*C) Step 2: Sort the rows in non-increasing fashion. After sorting step the matrix hist[][] would be 1 1 0 0 0 2 2 1 0 0 3 3 1 0 0 This step can be done in O(R * (R + C)). Since we know that the values are in range from 0 to R, we can use counting sort for every row. The sorting is actually the swapping of columns. If we look at the 3rd row under step 2: 3 3 1 0 0 The sorted row corresponds to swapping the columns so that the column with the highest possible rectangle is placed first, after that comes the column that allows the second highest rectangle and so on. So, in the example there are 2 columns that can form a rectangle of height 3. That makes an area of 3*2=6. If we try to make the rectangle wider the height drops to 1, because there are no columns left that allow a higher rectangle on the 3rd row.Step 3: Traverse each row of hist[][] and check for the max area. Since every row is sorted by count of 1’s, current area can be calculated by multiplying column number with value in hist[i][j]. This step also takes O(R * C) time.Below is the implementation based of above idea. C++ Java Python3 C# Javascript // C++ program to find the largest rectangle of 1's with swapping// of columns allowed.#include <bits/stdc++.h>#define R 3#define C 5 using namespace std; // Returns area of the largest rectangle of 1'sint maxArea(bool mat[R][C]){ // An auxiliary array to store count of consecutive 1's // in every column. int hist[R + 1][C + 1]; // Step 1: Fill the auxiliary array hist[][] for (int i = 0; i < C; i++) { // First row in hist[][] is copy of first row in mat[][] hist[0][i] = mat[0][i]; // Fill remaining rows of hist[][] for (int j = 1; j < R; j++) hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; } // Step 2: Sort columns of hist[][] in non-increasing order for (int i = 0; i < R; i++) { int count[R + 1] = { 0 }; // counting occurrence for (int j = 0; j < C; j++) count[hist[i][j]]++; // Traverse the count array from right side int col_no = 0; for (int j = R; j >= 0; j--) { if (count[j] > 0) { for (int k = 0; k < count[j]; k++) { hist[i][col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[][] to find maximum area int curr_area, max_area = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i, j) can // be obtained by multiplying column number // with value of hist[i][j] curr_area = (j + 1) * hist[i][j]; if (curr_area > max_area) max_area = curr_area; } } return max_area;} // Driver programint main(){ bool mat[R][C] = { { 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0 } }; cout << "Area of the largest rectangle is " << maxArea(mat); return 0;} // Java program to find the largest rectangle of// 1's with swapping of columns allowed.class GFG { static final int R = 3; static final int C = 5; // Returns area of the largest rectangle of 1's static int maxArea(int mat[][]) { // An auxiliary array to store count of consecutive 1's // in every column. int hist[][] = new int[R + 1][C + 1]; // Step 1: Fill the auxiliary array hist[][] for (int i = 0; i < C; i++) { // First row in hist[][] is copy of first row in mat[][] hist[0][i] = mat[0][i]; // Fill remaining rows of hist[][] for (int j = 1; j < R; j++) { hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; } } // Step 2: Sort rows of hist[][] in non-increasing order for (int i = 0; i < R; i++) { int count[] = new int[R + 1]; // counting occurrence for (int j = 0; j < C; j++) { count[hist[i][j]]++; } // Traverse the count array from right side int col_no = 0; for (int j = R; j >= 0; j--) { if (count[j] > 0) { for (int k = 0; k < count[j]; k++) { hist[i][col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[][] to find maximum area int curr_area, max_area = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i, j) can // be obtained by multiplying column number // with value of hist[i][j] curr_area = (j + 1) * hist[i][j]; if (curr_area > max_area) { max_area = curr_area; } } } return max_area; } // Driver Code public static void main(String[] args) { int mat[][] = {{0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0}}; System.out.println("Area of the largest rectangle is " + maxArea(mat)); }} // This code is contributed by PrinciRaj1992 # Python 3 program to find the largest# rectangle of 1's with swapping# of columns allowed. R = 3C = 5 # Returns area of the largest# rectangle of 1'sdef maxArea(mat): # An auxiliary array to store count # of consecutive 1's in every column. hist = [[0 for i in range(C + 1)] for i in range(R + 1)] # Step 1: Fill the auxiliary array hist[][] for i in range(0, C, 1): # First row in hist[][] is copy of # first row in mat[][] hist[0][i] = mat[0][i] # Fill remaining rows of hist[][] for j in range(1, R, 1): if ((mat[j][i] == 0)): hist[j][i] = 0 else: hist[j][i] = hist[j - 1][i] + 1 # Step 2: Sort rows of hist[][] in # non-increasing order for i in range(0, R, 1): count = [0 for i in range(R + 1)] # counting occurrence for j in range(0, C, 1): count[hist[i][j]] += 1 # Traverse the count array from # right side col_no = 0 j = R while(j >= 0): if (count[j] > 0): for k in range(0, count[j], 1): hist[i][col_no] = j col_no += 1 j -= 1 # Step 3: Traverse the sorted hist[][] # to find maximum area max_area = 0 for i in range(0, R, 1): for j in range(0, C, 1): # Since values are in decreasing order, # The area ending with cell (i, j) can # be obtained by multiplying column number # with value of hist[i][j] curr_area = (j + 1) * hist[i][j] if (curr_area > max_area): max_area = curr_area return max_area # Driver Codeif __name__ == '__main__': mat = [[0, 1, 0, 1, 0], [0, 1, 0, 1, 1], [1, 1, 0, 1, 0]] print("Area of the largest rectangle is", maxArea(mat)) # This code is contributed by# Shashank_Sharma // C# program to find the largest rectangle of// 1's with swapping of columns allowed.using System; class GFG{ static readonly int R = 3; static readonly int C = 5; // Returns area of the largest // rectangle of 1's static int maxArea(int [,]mat) { // An auxiliary array to store count // of consecutive 1's in every column. int [,]hist = new int[R + 1, C + 1]; // Step 1: Fill the auxiliary array hist[,] for (int i = 0; i < C; i++) { // First row in hist[,] is copy of // first row in mat[,] hist[0, i] = mat[0, i]; // Fill remaining rows of hist[,] for (int j = 1; j < R; j++) { hist[j, i] = (mat[j, i] == 0) ? 0 : hist[j - 1, i] + 1; } } // Step 2: Sort rows of hist[,] // in non-increasing order for (int i = 0; i < R; i++) { int []count = new int[R + 1]; // counting occurrence for (int j = 0; j < C; j++) { count[hist[i, j]]++; } // Traverse the count array from right side int col_no = 0; for (int j = R; j >= 0; j--) { if (count[j] > 0) { for (int k = 0; k < count[j]; k++) { hist[i, col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[,] // to find maximum area int curr_area, max_area = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i, j) can // be obtained by multiplying column number // with value of hist[i,j] curr_area = (j + 1) * hist[i, j]; if (curr_area > max_area) { max_area = curr_area; } } } return max_area; } // Driver Code public static void Main() { int [,]mat = {{0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0}}; Console.WriteLine("Area of the largest rectangle is " + maxArea(mat)); }} //This code is contributed by 29AjayKumar <script> // JavaScript program to find the largest rectangle of// 1's with swapping of columns allowed.var R = 3;var C = 5;// Returns area of the largest// rectangle of 1'sfunction maxArea(mat){ // An auxiliary array to store count // of consecutive 1's in every column. var hist = Array.from(Array(R+1), ()=>Array(C+1)); // Step 1: Fill the auxiliary array hist[,] for (var i = 0; i < C; i++) { // First row in hist[,] is copy of // first row in mat[,] hist[0][i] = mat[0][i]; // Fill remaining rows of hist[,] for (var j = 1; j < R; j++) { hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; } } // Step 2: Sort rows of hist[,] // in non-increasing order for (var i = 0; i < R; i++) { var count = Array(R+1).fill(0); // counting occurrence for (var j = 0; j < C; j++) { count[hist[i][j]]++; } // Traverse the count array from right side var col_no = 0; for (var j = R; j >= 0; j--) { if (count[j] > 0) { for (var k = 0; k < count[j]; k++) { hist[i][col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[,] // to find maximum area var curr_area, max_area = 0; for (var i = 0; i < R; i++) { for (var j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i][j) can // be obtained by multiplying column number // with value of hist[i,j] curr_area = (j + 1) * hist[i][j]; if (curr_area > max_area) { max_area = curr_area; } } } return max_area;}// Driver Codevar mat = [[0, 1, 0, 1, 0], [0, 1, 0, 1, 1], [1, 1, 0, 1, 0]];document.write("Area of the largest rectangle is " + maxArea(mat)); </script> Output: Area of the largest rectangle is 6 Time complexity of above solution is O(R * (R + C)) where R is number of rows and C is number of columns in input matrix. Extra space: O(R * C)This article is contributed by Shivprasad Choudhary. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above chirag dawra mjmj Shashank_Sharma princiraj1992 29AjayKumar deesha_chavan rrrtnx jayparekh0408 Directi square-rectangle Arrays Matrix Directi Arrays Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Dec, 2021" }, { "code": null, "e": 223, "s": 52, "text": "Given a matrix with 0 and 1’s, find the largest rectangle of all 1’s in the matrix. The rectangle can be formed by swapping any pair of columns of given matrix.Example: " }, { "code": null, "e": 756, "s": 223, "text": "Input: bool mat[][] = { {0, 1, 0, 1, 0},\n {0, 1, 0, 1, 1},\n {1, 1, 0, 1, 0}\n };\nOutput: 6\nThe largest rectangle's area is 6. The rectangle \ncan be formed by swapping column 2 with 3\nThe matrix after swapping will be\n 0 0 1 1 0\n 0 0 1 1 1\n 1 0 1 1 0\n\n\nInput: bool mat[R][C] = { {0, 1, 0, 1, 0},\n {0, 1, 1, 1, 1},\n {1, 1, 1, 0, 1},\n {1, 1, 1, 1, 1}\n };\nOutput: 9" }, { "code": null, "e": 1541, "s": 758, "text": "The idea is to use an auxiliary matrix to store count of consecutive 1’s in every column. Once we have these counts, we sort all rows of auxiliary matrix in non-increasing order of counts. Finally traverse the sorted rows to find the maximum area. Note : After forming the auxiliary matrix each row becomes independent, hence we can swap or sort each row independently.It is because we can only swap columns, so we have made each row independent and find the max area of rectangle possible with row and column. Below are detailed steps for first example mentioned above.Step 1: First of all, calculate no. of consecutive 1’s in every column. An auxiliary array hist[][] is used to store the counts of consecutive 1’s. So for the above first example, contents of hist[R][C] would be " }, { "code": null, "e": 1583, "s": 1541, "text": " 0 1 0 1 0\n 0 2 0 2 1\n 1 3 0 3 0" }, { "code": null, "e": 1720, "s": 1583, "text": "Time complexity of this step is O(R*C) Step 2: Sort the rows in non-increasing fashion. After sorting step the matrix hist[][] would be " }, { "code": null, "e": 1762, "s": 1720, "text": " 1 1 0 0 0\n 2 2 1 0 0\n 3 3 1 0 0" }, { "code": null, "e": 2729, "s": 1762, "text": "This step can be done in O(R * (R + C)). Since we know that the values are in range from 0 to R, we can use counting sort for every row. The sorting is actually the swapping of columns. If we look at the 3rd row under step 2: 3 3 1 0 0 The sorted row corresponds to swapping the columns so that the column with the highest possible rectangle is placed first, after that comes the column that allows the second highest rectangle and so on. So, in the example there are 2 columns that can form a rectangle of height 3. That makes an area of 3*2=6. If we try to make the rectangle wider the height drops to 1, because there are no columns left that allow a higher rectangle on the 3rd row.Step 3: Traverse each row of hist[][] and check for the max area. Since every row is sorted by count of 1’s, current area can be calculated by multiplying column number with value in hist[i][j]. This step also takes O(R * C) time.Below is the implementation based of above idea. " }, { "code": null, "e": 2733, "s": 2729, "text": "C++" }, { "code": null, "e": 2738, "s": 2733, "text": "Java" }, { "code": null, "e": 2746, "s": 2738, "text": "Python3" }, { "code": null, "e": 2749, "s": 2746, "text": "C#" }, { "code": null, "e": 2760, "s": 2749, "text": "Javascript" }, { "code": "// C++ program to find the largest rectangle of 1's with swapping// of columns allowed.#include <bits/stdc++.h>#define R 3#define C 5 using namespace std; // Returns area of the largest rectangle of 1'sint maxArea(bool mat[R][C]){ // An auxiliary array to store count of consecutive 1's // in every column. int hist[R + 1][C + 1]; // Step 1: Fill the auxiliary array hist[][] for (int i = 0; i < C; i++) { // First row in hist[][] is copy of first row in mat[][] hist[0][i] = mat[0][i]; // Fill remaining rows of hist[][] for (int j = 1; j < R; j++) hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; } // Step 2: Sort columns of hist[][] in non-increasing order for (int i = 0; i < R; i++) { int count[R + 1] = { 0 }; // counting occurrence for (int j = 0; j < C; j++) count[hist[i][j]]++; // Traverse the count array from right side int col_no = 0; for (int j = R; j >= 0; j--) { if (count[j] > 0) { for (int k = 0; k < count[j]; k++) { hist[i][col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[][] to find maximum area int curr_area, max_area = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i, j) can // be obtained by multiplying column number // with value of hist[i][j] curr_area = (j + 1) * hist[i][j]; if (curr_area > max_area) max_area = curr_area; } } return max_area;} // Driver programint main(){ bool mat[R][C] = { { 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0 } }; cout << \"Area of the largest rectangle is \" << maxArea(mat); return 0;}", "e": 4714, "s": 2760, "text": null }, { "code": "// Java program to find the largest rectangle of// 1's with swapping of columns allowed.class GFG { static final int R = 3; static final int C = 5; // Returns area of the largest rectangle of 1's static int maxArea(int mat[][]) { // An auxiliary array to store count of consecutive 1's // in every column. int hist[][] = new int[R + 1][C + 1]; // Step 1: Fill the auxiliary array hist[][] for (int i = 0; i < C; i++) { // First row in hist[][] is copy of first row in mat[][] hist[0][i] = mat[0][i]; // Fill remaining rows of hist[][] for (int j = 1; j < R; j++) { hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; } } // Step 2: Sort rows of hist[][] in non-increasing order for (int i = 0; i < R; i++) { int count[] = new int[R + 1]; // counting occurrence for (int j = 0; j < C; j++) { count[hist[i][j]]++; } // Traverse the count array from right side int col_no = 0; for (int j = R; j >= 0; j--) { if (count[j] > 0) { for (int k = 0; k < count[j]; k++) { hist[i][col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[][] to find maximum area int curr_area, max_area = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i, j) can // be obtained by multiplying column number // with value of hist[i][j] curr_area = (j + 1) * hist[i][j]; if (curr_area > max_area) { max_area = curr_area; } } } return max_area; } // Driver Code public static void main(String[] args) { int mat[][] = {{0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0}}; System.out.println(\"Area of the largest rectangle is \" + maxArea(mat)); }} // This code is contributed by PrinciRaj1992", "e": 7116, "s": 4714, "text": null }, { "code": "# Python 3 program to find the largest# rectangle of 1's with swapping# of columns allowed. R = 3C = 5 # Returns area of the largest# rectangle of 1'sdef maxArea(mat): # An auxiliary array to store count # of consecutive 1's in every column. hist = [[0 for i in range(C + 1)] for i in range(R + 1)] # Step 1: Fill the auxiliary array hist[][] for i in range(0, C, 1): # First row in hist[][] is copy of # first row in mat[][] hist[0][i] = mat[0][i] # Fill remaining rows of hist[][] for j in range(1, R, 1): if ((mat[j][i] == 0)): hist[j][i] = 0 else: hist[j][i] = hist[j - 1][i] + 1 # Step 2: Sort rows of hist[][] in # non-increasing order for i in range(0, R, 1): count = [0 for i in range(R + 1)] # counting occurrence for j in range(0, C, 1): count[hist[i][j]] += 1 # Traverse the count array from # right side col_no = 0 j = R while(j >= 0): if (count[j] > 0): for k in range(0, count[j], 1): hist[i][col_no] = j col_no += 1 j -= 1 # Step 3: Traverse the sorted hist[][] # to find maximum area max_area = 0 for i in range(0, R, 1): for j in range(0, C, 1): # Since values are in decreasing order, # The area ending with cell (i, j) can # be obtained by multiplying column number # with value of hist[i][j] curr_area = (j + 1) * hist[i][j] if (curr_area > max_area): max_area = curr_area return max_area # Driver Codeif __name__ == '__main__': mat = [[0, 1, 0, 1, 0], [0, 1, 0, 1, 1], [1, 1, 0, 1, 0]] print(\"Area of the largest rectangle is\", maxArea(mat)) # This code is contributed by# Shashank_Sharma", "e": 9104, "s": 7116, "text": null }, { "code": "// C# program to find the largest rectangle of// 1's with swapping of columns allowed.using System; class GFG{ static readonly int R = 3; static readonly int C = 5; // Returns area of the largest // rectangle of 1's static int maxArea(int [,]mat) { // An auxiliary array to store count // of consecutive 1's in every column. int [,]hist = new int[R + 1, C + 1]; // Step 1: Fill the auxiliary array hist[,] for (int i = 0; i < C; i++) { // First row in hist[,] is copy of // first row in mat[,] hist[0, i] = mat[0, i]; // Fill remaining rows of hist[,] for (int j = 1; j < R; j++) { hist[j, i] = (mat[j, i] == 0) ? 0 : hist[j - 1, i] + 1; } } // Step 2: Sort rows of hist[,] // in non-increasing order for (int i = 0; i < R; i++) { int []count = new int[R + 1]; // counting occurrence for (int j = 0; j < C; j++) { count[hist[i, j]]++; } // Traverse the count array from right side int col_no = 0; for (int j = R; j >= 0; j--) { if (count[j] > 0) { for (int k = 0; k < count[j]; k++) { hist[i, col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[,] // to find maximum area int curr_area, max_area = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i, j) can // be obtained by multiplying column number // with value of hist[i,j] curr_area = (j + 1) * hist[i, j]; if (curr_area > max_area) { max_area = curr_area; } } } return max_area; } // Driver Code public static void Main() { int [,]mat = {{0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0}}; Console.WriteLine(\"Area of the largest rectangle is \" + maxArea(mat)); }} //This code is contributed by 29AjayKumar", "e": 11610, "s": 9104, "text": null }, { "code": "<script> // JavaScript program to find the largest rectangle of// 1's with swapping of columns allowed.var R = 3;var C = 5;// Returns area of the largest// rectangle of 1'sfunction maxArea(mat){ // An auxiliary array to store count // of consecutive 1's in every column. var hist = Array.from(Array(R+1), ()=>Array(C+1)); // Step 1: Fill the auxiliary array hist[,] for (var i = 0; i < C; i++) { // First row in hist[,] is copy of // first row in mat[,] hist[0][i] = mat[0][i]; // Fill remaining rows of hist[,] for (var j = 1; j < R; j++) { hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; } } // Step 2: Sort rows of hist[,] // in non-increasing order for (var i = 0; i < R; i++) { var count = Array(R+1).fill(0); // counting occurrence for (var j = 0; j < C; j++) { count[hist[i][j]]++; } // Traverse the count array from right side var col_no = 0; for (var j = R; j >= 0; j--) { if (count[j] > 0) { for (var k = 0; k < count[j]; k++) { hist[i][col_no] = j; col_no++; } } } } // Step 3: Traverse the sorted hist[,] // to find maximum area var curr_area, max_area = 0; for (var i = 0; i < R; i++) { for (var j = 0; j < C; j++) { // Since values are in decreasing order, // The area ending with cell (i][j) can // be obtained by multiplying column number // with value of hist[i,j] curr_area = (j + 1) * hist[i][j]; if (curr_area > max_area) { max_area = curr_area; } } } return max_area;}// Driver Codevar mat = [[0, 1, 0, 1, 0], [0, 1, 0, 1, 1], [1, 1, 0, 1, 0]];document.write(\"Area of the largest rectangle is \" + maxArea(mat)); </script>", "e": 13688, "s": 11610, "text": null }, { "code": null, "e": 13697, "s": 13688, "text": "Output: " }, { "code": null, "e": 13732, "s": 13697, "text": "Area of the largest rectangle is 6" }, { "code": null, "e": 14053, "s": 13732, "text": "Time complexity of above solution is O(R * (R + C)) where R is number of rows and C is number of columns in input matrix. Extra space: O(R * C)This article is contributed by Shivprasad Choudhary. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 14066, "s": 14053, "text": "chirag dawra" }, { "code": null, "e": 14071, "s": 14066, "text": "mjmj" }, { "code": null, "e": 14087, "s": 14071, "text": "Shashank_Sharma" }, { "code": null, "e": 14101, "s": 14087, "text": "princiraj1992" }, { "code": null, "e": 14113, "s": 14101, "text": "29AjayKumar" }, { "code": null, "e": 14127, "s": 14113, "text": "deesha_chavan" }, { "code": null, "e": 14134, "s": 14127, "text": "rrrtnx" }, { "code": null, "e": 14148, "s": 14134, "text": "jayparekh0408" }, { "code": null, "e": 14156, "s": 14148, "text": "Directi" }, { "code": null, "e": 14173, "s": 14156, "text": "square-rectangle" }, { "code": null, "e": 14180, "s": 14173, "text": "Arrays" }, { "code": null, "e": 14187, "s": 14180, "text": "Matrix" }, { "code": null, "e": 14195, "s": 14187, "text": "Directi" }, { "code": null, "e": 14202, "s": 14195, "text": "Arrays" }, { "code": null, "e": 14209, "s": 14202, "text": "Matrix" } ]
How to compute the eigenvalues and right eigenvectors of a given square array using NumPY?
02 Sep, 2020 In this article, we will discuss how to compute the eigenvalues and right eigenvectors of a given square array using NumPy library. Example: Suppose we have a matrix as: [[1,2], [2,3]] Eigenvalue we get from this matrix or square array is: [-0.23606798 4.23606798] Eigenvectors of this matrix are: [[-0.85065081 -0.52573111], [ 0.52573111 -0.85065081]] To know how they are calculated mathematically see this Calculation of EigenValues and EigenVectors. In the below examples, we have used numpy.linalg.eig() to find eigenvalues and eigenvectors for the given square array. Syntax: numpy.linalg.eig() Parameter: An square array. Return: It will return two values first is eigenvalues and second is eigenvectors. Example 1: Python3 # importing numpy libraryimport numpy as np # create numpy 2d-arraym = np.array([[1, 2], [2, 3]]) print("Printing the Original square array:\n", m) # finding eigenvalues and eigenvectorsw, v = np.linalg.eig(m) # printing eigen valuesprint("Printing the Eigen values of the given square array:\n", w) # printing eigen vectorsprint("Printing Right eigenvectors of the given square array:\n" v) Output: Printing the Original square array: [[1 2] [2 3]] Printing the Eigen values of the given square array: [-0.23606798 4.23606798] Printing Right eigenvectors of the given square array: [[-0.85065081 -0.52573111] [ 0.52573111 -0.85065081]] Example 2: Python3 # importing numpy libraryimport numpy as np # create numpy 2d-arraym = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]]) print("Printing the Original square array:\n", m) # finding eigenvalues and eigenvectorsw, v = np.linalg.eig(m) # printing eigen valuesprint("Printing the Eigen values of the given square array:\n", w) # printing eigen vectorsprint("Printing Right eigenvectors of the given square array:\n", v) Output: Printing the Original square array: [[1 2 3] [2 3 4] [4 5 6]] Printing the Eigen values of the given square array: [ 1.08309519e+01 -8.30951895e-01 1.01486082e-16] Printing Right eigenvectors of the given square array: [[ 0.34416959 0.72770285 0.40824829] [ 0.49532111 0.27580256 -0.81649658] [ 0.79762415 -0.62799801 0.40824829]] Python numpy-Linear Algebra Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 161, "s": 28, "text": "In this article, we will discuss how to compute the eigenvalues and right eigenvectors of a given square array using NumPy library. " }, { "code": null, "e": 170, "s": 161, "text": "Example:" }, { "code": null, "e": 390, "s": 170, "text": "Suppose we have a matrix as: \n[[1,2],\n[2,3]] \n\nEigenvalue we get from this matrix or square array is: \n[-0.23606798 4.23606798]\n\nEigenvectors of this matrix are: \n[[-0.85065081 -0.52573111], \n[ 0.52573111 -0.85065081]] " }, { "code": null, "e": 612, "s": 390, "text": "To know how they are calculated mathematically see this Calculation of EigenValues and EigenVectors. In the below examples, we have used numpy.linalg.eig() to find eigenvalues and eigenvectors for the given square array. " }, { "code": null, "e": 639, "s": 612, "text": "Syntax: numpy.linalg.eig()" }, { "code": null, "e": 667, "s": 639, "text": "Parameter: An square array." }, { "code": null, "e": 750, "s": 667, "text": "Return: It will return two values first is eigenvalues and second is eigenvectors." }, { "code": null, "e": 761, "s": 750, "text": "Example 1:" }, { "code": null, "e": 769, "s": 761, "text": "Python3" }, { "code": "# importing numpy libraryimport numpy as np # create numpy 2d-arraym = np.array([[1, 2], [2, 3]]) print(\"Printing the Original square array:\\n\", m) # finding eigenvalues and eigenvectorsw, v = np.linalg.eig(m) # printing eigen valuesprint(\"Printing the Eigen values of the given square array:\\n\", w) # printing eigen vectorsprint(\"Printing Right eigenvectors of the given square array:\\n\" v)", "e": 1194, "s": 769, "text": null }, { "code": null, "e": 1202, "s": 1194, "text": "Output:" }, { "code": null, "e": 1445, "s": 1202, "text": "Printing the Original square array:\n [[1 2]\n [2 3]]\nPrinting the Eigen values of the given square array:\n [-0.23606798 4.23606798]\nPrinting Right eigenvectors of the given square array:\n [[-0.85065081 -0.52573111]\n [ 0.52573111 -0.85065081]]" }, { "code": null, "e": 1456, "s": 1445, "text": "Example 2:" }, { "code": null, "e": 1464, "s": 1456, "text": "Python3" }, { "code": "# importing numpy libraryimport numpy as np # create numpy 2d-arraym = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]]) print(\"Printing the Original square array:\\n\", m) # finding eigenvalues and eigenvectorsw, v = np.linalg.eig(m) # printing eigen valuesprint(\"Printing the Eigen values of the given square array:\\n\", w) # printing eigen vectorsprint(\"Printing Right eigenvectors of the given square array:\\n\", v)", "e": 1920, "s": 1464, "text": null }, { "code": null, "e": 1928, "s": 1920, "text": "Output:" }, { "code": null, "e": 2271, "s": 1928, "text": "Printing the Original square array:\n [[1 2 3]\n [2 3 4]\n [4 5 6]]\nPrinting the Eigen values of the given square array:\n [ 1.08309519e+01 -8.30951895e-01 1.01486082e-16]\nPrinting Right eigenvectors of the given square array:\n [[ 0.34416959 0.72770285 0.40824829]\n [ 0.49532111 0.27580256 -0.81649658]\n [ 0.79762415 -0.62799801 0.40824829]]" }, { "code": null, "e": 2299, "s": 2271, "text": "Python numpy-Linear Algebra" }, { "code": null, "e": 2312, "s": 2299, "text": "Python-numpy" }, { "code": null, "e": 2319, "s": 2312, "text": "Python" } ]
Microsoft Azure – Starting & Stopping a Azure Kubernetes Service Cluster
01 Jun, 2021 In this article, we will learn how to stop and start Azure Kubernetes Service(AKS) clusters. You can stop your entire Azure Kubernetes Service cluster to save costs. To follow along, you will need an existing Azure Kubernetes service that is running. To use start and stop for AKS, we need the AKS preview extension for the Azure CLI. It can be installed using the below command: extension add --name aks-preview Let’s make sure that we have the latest version of that using the below command: az extension update --name aks-preview Next, we need to register the start/stop preview feature using the below command: az feature register --namespace "Microsoft.ContainereService" --name "StartStopPreview" This can take a while. After a couple of minutes, check if the feature is registered with the below command: az feature list -o table --query "[?contains(name,'Microsoft.ContainereService/StartStopPreview')].{Name:name, State:properties.state}" Now we need to refresh the container resource provider using the below command: az provider register --namespace Microsoft.ContainerService That’s all the preview stuff out of the way. Now, it could be that you don’t need to do all of this when this feature is generally available. Let’s stop our AKS cluster with the below command: az aks stop --name YOUR_CLUSTE_NAME --resource-group YOUR_RESOURCE_GROUP It’s as simple as that. This will result in something like below if we use the below command: az aks show The power state is stopped, so the cluster is stopped. We can just as easily start it up again using the below command: az aks start --name YOUR_CLUSTE_NAME --resource-group YOUR_RESOURCE_GROUP We’ll use AKS show to check if it is running as shown below: Stopping an Azure Kubernetes Service cluster is a great way to save money. You can easily start and stop AKS with an Azure CLI command, which you can, for instance, automate to stop when this surface isn’t used and start during business hours. azure-cloud-instances azure-kubernetes-services Cloud-Computing Microsoft Azure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Microsoft Azure - KQL Query to Get the VM Computer Properties Microsoft Azure - Resource Tagging and Best Practices Microsoft Azure - Mount Azure Storage in Container App In App Service Microsoft Azure - Choosing a Partition Key in Cosmos DB Microsoft Azure - Map a Network File Share to Azure Windows VM How Microsoft Azure Works? Microsoft Azure - Query System Event Log Data Using Azure KQL Microsoft Azure - Deletion of Snapshots using PowerShell Script Microsoft Azure - Azure Firewall Flow Logs From Select Source IP Microsoft Azure - Cloning Web Apps using Azure App Services
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 280, "s": 28, "text": "In this article, we will learn how to stop and start Azure Kubernetes Service(AKS) clusters. You can stop your entire Azure Kubernetes Service cluster to save costs. To follow along, you will need an existing Azure Kubernetes service that is running. " }, { "code": null, "e": 410, "s": 280, "text": "To use start and stop for AKS, we need the AKS preview extension for the Azure CLI. It can be installed using the below command:" }, { "code": null, "e": 443, "s": 410, "text": "extension add --name aks-preview" }, { "code": null, "e": 524, "s": 443, "text": "Let’s make sure that we have the latest version of that using the below command:" }, { "code": null, "e": 563, "s": 524, "text": "az extension update --name aks-preview" }, { "code": null, "e": 645, "s": 563, "text": "Next, we need to register the start/stop preview feature using the below command:" }, { "code": null, "e": 733, "s": 645, "text": "az feature register --namespace \"Microsoft.ContainereService\" --name \"StartStopPreview\"" }, { "code": null, "e": 843, "s": 733, "text": " This can take a while. After a couple of minutes, check if the feature is registered with the below command:" }, { "code": null, "e": 988, "s": 843, "text": "az feature list -o table --query \n \"[?contains(name,'Microsoft.ContainereService/StartStopPreview')].{Name:name,\n State:properties.state}\"" }, { "code": null, "e": 1068, "s": 988, "text": "Now we need to refresh the container resource provider using the below command:" }, { "code": null, "e": 1128, "s": 1068, "text": "az provider register --namespace Microsoft.ContainerService" }, { "code": null, "e": 1270, "s": 1128, "text": "That’s all the preview stuff out of the way. Now, it could be that you don’t need to do all of this when this feature is generally available." }, { "code": null, "e": 1321, "s": 1270, "text": "Let’s stop our AKS cluster with the below command:" }, { "code": null, "e": 1394, "s": 1321, "text": "az aks stop --name YOUR_CLUSTE_NAME --resource-group YOUR_RESOURCE_GROUP" }, { "code": null, "e": 1488, "s": 1394, "text": "It’s as simple as that. This will result in something like below if we use the below command:" }, { "code": null, "e": 1500, "s": 1488, "text": "az aks show" }, { "code": null, "e": 1555, "s": 1500, "text": "The power state is stopped, so the cluster is stopped." }, { "code": null, "e": 1620, "s": 1555, "text": "We can just as easily start it up again using the below command:" }, { "code": null, "e": 1694, "s": 1620, "text": "az aks start --name YOUR_CLUSTE_NAME --resource-group YOUR_RESOURCE_GROUP" }, { "code": null, "e": 1755, "s": 1694, "text": "We’ll use AKS show to check if it is running as shown below:" }, { "code": null, "e": 2000, "s": 1755, "text": "Stopping an Azure Kubernetes Service cluster is a great way to save money. You can easily start and stop AKS with an Azure CLI command, which you can, for instance, automate to stop when this surface isn’t used and start during business hours. " }, { "code": null, "e": 2022, "s": 2000, "text": "azure-cloud-instances" }, { "code": null, "e": 2048, "s": 2022, "text": "azure-kubernetes-services" }, { "code": null, "e": 2064, "s": 2048, "text": "Cloud-Computing" }, { "code": null, "e": 2080, "s": 2064, "text": "Microsoft Azure" }, { "code": null, "e": 2178, "s": 2080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2240, "s": 2178, "text": "Microsoft Azure - KQL Query to Get the VM Computer Properties" }, { "code": null, "e": 2294, "s": 2240, "text": "Microsoft Azure - Resource Tagging and Best Practices" }, { "code": null, "e": 2364, "s": 2294, "text": "Microsoft Azure - Mount Azure Storage in Container App In App Service" }, { "code": null, "e": 2420, "s": 2364, "text": "Microsoft Azure - Choosing a Partition Key in Cosmos DB" }, { "code": null, "e": 2483, "s": 2420, "text": "Microsoft Azure - Map a Network File Share to Azure Windows VM" }, { "code": null, "e": 2510, "s": 2483, "text": "How Microsoft Azure Works?" }, { "code": null, "e": 2572, "s": 2510, "text": "Microsoft Azure - Query System Event Log Data Using Azure KQL" }, { "code": null, "e": 2636, "s": 2572, "text": "Microsoft Azure - Deletion of Snapshots using PowerShell Script" }, { "code": null, "e": 2701, "s": 2636, "text": "Microsoft Azure - Azure Firewall Flow Logs From Select Source IP" } ]
How to Convert Array to Set in JavaScript?
31 Jul, 2019 The task is to convert a JavaScript Array to a Set with the help of JavaScript. we’re going to discuss few techniques. Approach: Take the JavaScript array into a variable. Use the new keyword to create a new set and pass the JavaScript array as it first and only argument. This will automatically create the set of the provided array. Example 1: In this example, the array is converted into set using the same approach defined above. <!DOCTYPE HTML><html> <head> <title> JavaScript | Convert Array to Set. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;" id="h1"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var A = [1, 1, 2, 2, 2, 2, 5, 5]; up.innerHTML = "Click on the button to convert"+ " the array to set.<br>" + "Array - [" + A + "]"; function GFG_Fun() { var set = new Set(A); down.innerHTML = JSON.stringify([...set]); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, the array is converted into set using a bit approach than above. <!DOCTYPE HTML><html> <head> <title> JavaScript | Convert Array to Set. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;" id="h1"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var A = ["A", "A", "Computer Science", "portal", "for", "for", "Geeks", "Geeks"]; up.innerHTML = "Click on the button to convert "+ "the array to set.<br>" + "Array - [" + A + "]"; function GFG_Fun() { var set = new Set(A); down.innerHTML = JSON.stringify([...set.keys()]); } </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.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2019" }, { "code": null, "e": 147, "s": 28, "text": "The task is to convert a JavaScript Array to a Set with the help of JavaScript. we’re going to discuss few techniques." }, { "code": null, "e": 157, "s": 147, "text": "Approach:" }, { "code": null, "e": 200, "s": 157, "text": "Take the JavaScript array into a variable." }, { "code": null, "e": 301, "s": 200, "text": "Use the new keyword to create a new set and pass the JavaScript array as it first and only argument." }, { "code": null, "e": 363, "s": 301, "text": "This will automatically create the set of the provided array." }, { "code": null, "e": 462, "s": 363, "text": "Example 1: In this example, the array is converted into set using the same approach defined above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Convert Array to Set. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\" id=\"h1\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var A = [1, 1, 2, 2, 2, 2, 5, 5]; up.innerHTML = \"Click on the button to convert\"+ \" the array to set.<br>\" + \"Array - [\" + A + \"]\"; function GFG_Fun() { var set = new Set(A); down.innerHTML = JSON.stringify([...set]); } </script></body> </html>", "e": 1419, "s": 462, "text": null }, { "code": null, "e": 1427, "s": 1419, "text": "Output:" }, { "code": null, "e": 1458, "s": 1427, "text": "Before clicking on the button:" }, { "code": null, "e": 1488, "s": 1458, "text": "After clicking on the button:" }, { "code": null, "e": 1581, "s": 1488, "text": "Example 2: In this example, the array is converted into set using a bit approach than above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Convert Array to Set. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\" id=\"h1\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var A = [\"A\", \"A\", \"Computer Science\", \"portal\", \"for\", \"for\", \"Geeks\", \"Geeks\"]; up.innerHTML = \"Click on the button to convert \"+ \"the array to set.<br>\" + \"Array - [\" + A + \"]\"; function GFG_Fun() { var set = new Set(A); down.innerHTML = JSON.stringify([...set.keys()]); } </script></body> </html>", "e": 2606, "s": 1581, "text": null }, { "code": null, "e": 2614, "s": 2606, "text": "Output:" }, { "code": null, "e": 2645, "s": 2614, "text": "Before clicking on the button:" }, { "code": null, "e": 2675, "s": 2645, "text": "After clicking on the button:" }, { "code": null, "e": 2691, "s": 2675, "text": "JavaScript-Misc" }, { "code": null, "e": 2702, "s": 2691, "text": "JavaScript" }, { "code": null, "e": 2719, "s": 2702, "text": "Web Technologies" } ]
Residual, BottleNeck, Inverted Residual, Linear BottleNeck, MBConv Explained | by Francesco Zuppichini | Towards Data Science
An interactive version is available here All these blocks have been implemented in my library glasses Keeping track of names in modern Deep Learning is hard. Today we’ll see different blocks used in modern CNN architecture such as ResNet, MobileNet, EfficientNet, and their implementation in PyTorch! Before we do anything, let’s create a general conv — norm — act layer torch.Size([1, 64, 56, 56]) Residual connections were used in ResNet proposed in Deep Residual Learning for Image Recognition and let’s also cite Schmidhuber lab’s work on Highway networks. The idea is to add your input to your output, output = layer(input) + input. The following image may help you visualize it. But, I mean it is just a + operator. The residual operation improves the ability of a gradient to propagate across multiplier layers permitting to effectively train networks with more than a hundred layers. In PyTorch, we can easily create a ResidualAdd Layer Sometimes your residual hasn’t the same output’s dimension, so we cannot add them. We can project the input using a conv in the shortcut (the black arrow with the +) to match your output’s feature Bottlenecks blocks were also introduced in Deep Residual Learning for Image Recognition. A BottleNeck block takes an input of size BxCxHxW, it first reduces it to BxC/rxHxW using an inexpensive 1x1 conv, then applies a 3x3 conv and finally remaps the output to the same feature dimension as the input, BxCxHxW using again a 1x1 conv. This is faster than using three 3x3 convs. Since the input is reduced first, this is why we called it "BottleNeck". The following figure visualizes the block, we used r=4 as in the original implementation The first two convs are followed by batchnorm and a non-linear activation, while the last non-linearity is applied after the addition. In PyTorch Notice that we apply shortcut only if the input and output features are different. In practice a stride=2 is used in the middle convolution when we wish to reduce the spatial dimension. Linear BottleNecks were introduced in MobileNetV2: Inverted Residuals and Linear Bottlenecks. A Linear BottleNeck Block is a BottleNeck Block without the last activation. In the paper, section 3.2 they go into details about why having non-linearity before the output hurt performance. In a nutshell, the non-linearity function, line ReLU that sets everything < 0 to 0, destroys information. They have empirically shown that this is true when the input’s channels are less than the output’s. So, remove the nn.ReLU in the BottleNeck and you have it. Inverted Residuals were introduced, again, in MobileNetV2: Inverted Residuals and Linear Bottlenecks. Inverted Residual blocks are inverted BottleNeck layers. They expand features with the first conv instead of reducing them. The following image should make this clear So we go from BxCxHxW to -> BxCexHxW -> BxCexHxW -> BxCxHxW, where e is the expansion ratio and it is set to 4. Instead of going wide -> narrow -> wide as in normal bottleneck block, they do the opposite, narrow -> wide -> narrow. In PyTorch this is trivial In MobileNet residual connections are only applied when the input and output features match, don't ask me why, if you know it please comment :) So you should do something like So after MobileNetV2, its building blocks were referred as MBConv. A MBConv is a Inverted Linear BottleNeck layer with Depth-Wise Separable Convolution. Depth-Wise Separable Convolutions adopt a trick to splint a normal 3x3 conv in two convs to reduce the number of parameters. The first one applies a single 3x3 filter to each input’s channels, the other applies a 1x1 filter to all the channels. If you do your match, this is the same thing as doing a normal 3x3 conv but you save parameters. This is also kind of stupid because it is way slower than a normal 3x3 on the current hardware we have. The following picture shows the idea The different colors in the channels represent one individual filter applied per channel In PyTorch: The first convolution is usually called depth while the second point. Let's count the parameters sum(p.numel() for p in DepthWiseSeparableConv(32, 64).parameters() if p.requires_grad) Out: 2432 Let’s see a normal Conv2d sum(p.numel() for p in nn.Conv2d(32, 64, kernel_size=3).parameters() if p.requires_grad) Out: 18496 That’s a big difference So, let’s create a full MBConv. There are a couple of MBConv’s important details, normalization is applied to both depth and point convolution and non-linearity only in the depth convolution (remember linear bottlenecks). The applied ReLU6 non-linearity. Putting everything together A slighly modified version of this block, with Squeeze and Excitation is used in EfficientNet. Fused Inverted Residuals were introduced in EfficientNetV2: Smaller Models and Faster Training to make MBConv faster. So basically, since Depthwise convolutions are slow, they fused the first and second conv in a single 3x3 conv (section 3.2). Now you should know the difference between all these blocks and the reasoning behind them! I highly recommend reading the paper related to them, you can’t go wrong with that. For a more detailed guide to ResNet, check out Residual Networks: Implementing ResNet in Pytorch
[ { "code": null, "e": 213, "s": 172, "text": "An interactive version is available here" }, { "code": null, "e": 274, "s": 213, "text": "All these blocks have been implemented in my library glasses" }, { "code": null, "e": 473, "s": 274, "text": "Keeping track of names in modern Deep Learning is hard. Today we’ll see different blocks used in modern CNN architecture such as ResNet, MobileNet, EfficientNet, and their implementation in PyTorch!" }, { "code": null, "e": 543, "s": 473, "text": "Before we do anything, let’s create a general conv — norm — act layer" }, { "code": null, "e": 571, "s": 543, "text": "torch.Size([1, 64, 56, 56])" }, { "code": null, "e": 1064, "s": 571, "text": "Residual connections were used in ResNet proposed in Deep Residual Learning for Image Recognition and let’s also cite Schmidhuber lab’s work on Highway networks. The idea is to add your input to your output, output = layer(input) + input. The following image may help you visualize it. But, I mean it is just a + operator. The residual operation improves the ability of a gradient to propagate across multiplier layers permitting to effectively train networks with more than a hundred layers." }, { "code": null, "e": 1117, "s": 1064, "text": "In PyTorch, we can easily create a ResidualAdd Layer" }, { "code": null, "e": 1314, "s": 1117, "text": "Sometimes your residual hasn’t the same output’s dimension, so we cannot add them. We can project the input using a conv in the shortcut (the black arrow with the +) to match your output’s feature" }, { "code": null, "e": 1853, "s": 1314, "text": "Bottlenecks blocks were also introduced in Deep Residual Learning for Image Recognition. A BottleNeck block takes an input of size BxCxHxW, it first reduces it to BxC/rxHxW using an inexpensive 1x1 conv, then applies a 3x3 conv and finally remaps the output to the same feature dimension as the input, BxCxHxW using again a 1x1 conv. This is faster than using three 3x3 convs. Since the input is reduced first, this is why we called it \"BottleNeck\". The following figure visualizes the block, we used r=4 as in the original implementation" }, { "code": null, "e": 1999, "s": 1853, "text": "The first two convs are followed by batchnorm and a non-linear activation, while the last non-linearity is applied after the addition. In PyTorch" }, { "code": null, "e": 2082, "s": 1999, "text": "Notice that we apply shortcut only if the input and output features are different." }, { "code": null, "e": 2185, "s": 2082, "text": "In practice a stride=2 is used in the middle convolution when we wish to reduce the spatial dimension." }, { "code": null, "e": 2734, "s": 2185, "text": "Linear BottleNecks were introduced in MobileNetV2: Inverted Residuals and Linear Bottlenecks. A Linear BottleNeck Block is a BottleNeck Block without the last activation. In the paper, section 3.2 they go into details about why having non-linearity before the output hurt performance. In a nutshell, the non-linearity function, line ReLU that sets everything < 0 to 0, destroys information. They have empirically shown that this is true when the input’s channels are less than the output’s. So, remove the nn.ReLU in the BottleNeck and you have it." }, { "code": null, "e": 3003, "s": 2734, "text": "Inverted Residuals were introduced, again, in MobileNetV2: Inverted Residuals and Linear Bottlenecks. Inverted Residual blocks are inverted BottleNeck layers. They expand features with the first conv instead of reducing them. The following image should make this clear" }, { "code": null, "e": 3261, "s": 3003, "text": "So we go from BxCxHxW to -> BxCexHxW -> BxCexHxW -> BxCxHxW, where e is the expansion ratio and it is set to 4. Instead of going wide -> narrow -> wide as in normal bottleneck block, they do the opposite, narrow -> wide -> narrow. In PyTorch this is trivial" }, { "code": null, "e": 3437, "s": 3261, "text": "In MobileNet residual connections are only applied when the input and output features match, don't ask me why, if you know it please comment :) So you should do something like" }, { "code": null, "e": 3590, "s": 3437, "text": "So after MobileNetV2, its building blocks were referred as MBConv. A MBConv is a Inverted Linear BottleNeck layer with Depth-Wise Separable Convolution." }, { "code": null, "e": 3932, "s": 3590, "text": "Depth-Wise Separable Convolutions adopt a trick to splint a normal 3x3 conv in two convs to reduce the number of parameters. The first one applies a single 3x3 filter to each input’s channels, the other applies a 1x1 filter to all the channels. If you do your match, this is the same thing as doing a normal 3x3 conv but you save parameters." }, { "code": null, "e": 4036, "s": 3932, "text": "This is also kind of stupid because it is way slower than a normal 3x3 on the current hardware we have." }, { "code": null, "e": 4073, "s": 4036, "text": "The following picture shows the idea" }, { "code": null, "e": 4162, "s": 4073, "text": "The different colors in the channels represent one individual filter applied per channel" }, { "code": null, "e": 4174, "s": 4162, "text": "In PyTorch:" }, { "code": null, "e": 4271, "s": 4174, "text": "The first convolution is usually called depth while the second point. Let's count the parameters" }, { "code": null, "e": 4359, "s": 4271, "text": "sum(p.numel() for p in DepthWiseSeparableConv(32, 64).parameters() if p.requires_grad) " }, { "code": null, "e": 4369, "s": 4359, "text": "Out: 2432" }, { "code": null, "e": 4395, "s": 4369, "text": "Let’s see a normal Conv2d" }, { "code": null, "e": 4484, "s": 4395, "text": "sum(p.numel() for p in nn.Conv2d(32, 64, kernel_size=3).parameters() if p.requires_grad)" }, { "code": null, "e": 4495, "s": 4484, "text": "Out: 18496" }, { "code": null, "e": 4519, "s": 4495, "text": "That’s a big difference" }, { "code": null, "e": 4802, "s": 4519, "text": "So, let’s create a full MBConv. There are a couple of MBConv’s important details, normalization is applied to both depth and point convolution and non-linearity only in the depth convolution (remember linear bottlenecks). The applied ReLU6 non-linearity. Putting everything together" }, { "code": null, "e": 4897, "s": 4802, "text": "A slighly modified version of this block, with Squeeze and Excitation is used in EfficientNet." }, { "code": null, "e": 5141, "s": 4897, "text": "Fused Inverted Residuals were introduced in EfficientNetV2: Smaller Models and Faster Training to make MBConv faster. So basically, since Depthwise convolutions are slow, they fused the first and second conv in a single 3x3 conv (section 3.2)." }, { "code": null, "e": 5316, "s": 5141, "text": "Now you should know the difference between all these blocks and the reasoning behind them! I highly recommend reading the paper related to them, you can’t go wrong with that." } ]
Count number of triplets (a, b, c) from first N natural numbers such that a * b + c = N - GeeksforGeeks
03 May, 2021 Given an integer N, the task is to count the triplets (a, b, c) from the first N natural numbers such that a * b + c = N. Examples: Input: N = 3Output: 3 Explanation: Triplets of the form a * b + c = N are { (1, 1, 2), (1, 2, 1), (2, 1, 1) } Therefore, the required output is 3. Input: N = 100Output: 473 Approach: The problem can be solved based on the following observation: For every possible pairs (a, b), If a * b < N, then only c exists. Therefore, count the pairs (a, b) whose product is less than N. Follow the steps below to solve the problem: Initialize a variable, say cntTriplets, to store the count of triplets of first N natural numbers that satisfy the given condition. Iterate over the range [1, N – 1] using variable i and check if N % i == 0 or not. If found to be true, then update cntTriplets += (N / i) – 1. Otherwise, update cntTriplets += (N / i). Finally, print the value of cntTriplets. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of// triplets (a, b, c) with a * b + c = Nint findCntTriplet(int N){ // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N int cntTriplet = 0; // Iterate over the range [1, N] for (int i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += N / i; } else { // Update cntTriplet cntTriplet += (N / i) - 1; } } return cntTriplet;} // Driver Codeint main(){ int N = 3; cout << findCntTriplet(N); return 0;} // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the count of // triplets (a, b, c) with a * b + c = N static int findCntTriplet(int N) { // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N int cntTriplet = 0; // Iterate over the range [1, N] for (int i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += N / i; } else { // Update cntTriplet cntTriplet += (N / i) - 1; } } return cntTriplet; } // Driver code public static void main(String[] args) { int N = 3; System.out.println(findCntTriplet(N)); }} // This code is contributed by susmitakundugoaldanga # Python program to implement# the above approach # Function to find the count of# triplets (a, b, c) with a * b + c = Ndef findCntTriplet(N): # Stores count of triplets of 1st # N natural numbers which are of # the form a * b + c = N cntTriplet = 0; # Iterate over the range [1, N] for i in range(1, N): # If N is divisible by i if (N % i != 0): # Update cntTriplet cntTriplet += N // i; else: # Update cntTriplet cntTriplet += (N // i) - 1; return cntTriplet; # Driver codeif __name__ == '__main__': N = 3; print(findCntTriplet(N)); # This code is contributed by 29AjayKumar // C# program to implement// the above approachusing System;class GFG{ // Function to find the count of // triplets (a, b, c) with a * b + c = N static int findCntTriplet(int N) { // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N int cntTriplet = 0; // Iterate over the range [1, N] for (int i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += N / i; } else { // Update cntTriplet cntTriplet += (N / i) - 1; } } return cntTriplet; } // Driver code public static void Main(String[] args) { int N = 3; Console.WriteLine(findCntTriplet(N)); }} // This code is contributed by 29AjayKumar <script> // javascript program for the above approach // Function to find the count of // triplets (a, b, c) with a * b + c = N function findCntTriplet(N) { // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N let cntTriplet = 0; // Iterate over the range [1, N] for (let i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += Math.floor(N / i); } else { // Update cntTriplet cntTriplet += Math.floor(N / i) - 1; } } return cntTriplet; } // Driver Code let N = 3; document.write(findCntTriplet(N)); </script> 3 Time Complexity: O(N)Auxiliary Space: O(1) susmitakundugoaldanga 29AjayKumar souravghosh0416 divisibility Greedy Mathematical Searching Searching Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Huffman Coding | Greedy Algo-3 Activity Selection Problem | Greedy Algo-1 Coin Change | DP-7 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25483, "s": 25455, "text": "\n03 May, 2021" }, { "code": null, "e": 25605, "s": 25483, "text": "Given an integer N, the task is to count the triplets (a, b, c) from the first N natural numbers such that a * b + c = N." }, { "code": null, "e": 25615, "s": 25605, "text": "Examples:" }, { "code": null, "e": 25762, "s": 25615, "text": "Input: N = 3Output: 3 Explanation: Triplets of the form a * b + c = N are { (1, 1, 2), (1, 2, 1), (2, 1, 1) } Therefore, the required output is 3." }, { "code": null, "e": 25788, "s": 25762, "text": "Input: N = 100Output: 473" }, { "code": null, "e": 25860, "s": 25788, "text": "Approach: The problem can be solved based on the following observation:" }, { "code": null, "e": 25991, "s": 25860, "text": "For every possible pairs (a, b), If a * b < N, then only c exists. Therefore, count the pairs (a, b) whose product is less than N." }, { "code": null, "e": 26036, "s": 25991, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 26168, "s": 26036, "text": "Initialize a variable, say cntTriplets, to store the count of triplets of first N natural numbers that satisfy the given condition." }, { "code": null, "e": 26312, "s": 26168, "text": "Iterate over the range [1, N – 1] using variable i and check if N % i == 0 or not. If found to be true, then update cntTriplets += (N / i) – 1." }, { "code": null, "e": 26354, "s": 26312, "text": "Otherwise, update cntTriplets += (N / i)." }, { "code": null, "e": 26395, "s": 26354, "text": "Finally, print the value of cntTriplets." }, { "code": null, "e": 26446, "s": 26395, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26450, "s": 26446, "text": "C++" }, { "code": null, "e": 26455, "s": 26450, "text": "Java" }, { "code": null, "e": 26463, "s": 26455, "text": "Python3" }, { "code": null, "e": 26466, "s": 26463, "text": "C#" }, { "code": null, "e": 26477, "s": 26466, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of// triplets (a, b, c) with a * b + c = Nint findCntTriplet(int N){ // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N int cntTriplet = 0; // Iterate over the range [1, N] for (int i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += N / i; } else { // Update cntTriplet cntTriplet += (N / i) - 1; } } return cntTriplet;} // Driver Codeint main(){ int N = 3; cout << findCntTriplet(N); return 0;}", "e": 27206, "s": 26477, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the count of // triplets (a, b, c) with a * b + c = N static int findCntTriplet(int N) { // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N int cntTriplet = 0; // Iterate over the range [1, N] for (int i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += N / i; } else { // Update cntTriplet cntTriplet += (N / i) - 1; } } return cntTriplet; } // Driver code public static void main(String[] args) { int N = 3; System.out.println(findCntTriplet(N)); }} // This code is contributed by susmitakundugoaldanga", "e": 28014, "s": 27206, "text": null }, { "code": "# Python program to implement# the above approach # Function to find the count of# triplets (a, b, c) with a * b + c = Ndef findCntTriplet(N): # Stores count of triplets of 1st # N natural numbers which are of # the form a * b + c = N cntTriplet = 0; # Iterate over the range [1, N] for i in range(1, N): # If N is divisible by i if (N % i != 0): # Update cntTriplet cntTriplet += N // i; else: # Update cntTriplet cntTriplet += (N // i) - 1; return cntTriplet; # Driver codeif __name__ == '__main__': N = 3; print(findCntTriplet(N)); # This code is contributed by 29AjayKumar", "e": 28691, "s": 28014, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to find the count of // triplets (a, b, c) with a * b + c = N static int findCntTriplet(int N) { // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N int cntTriplet = 0; // Iterate over the range [1, N] for (int i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += N / i; } else { // Update cntTriplet cntTriplet += (N / i) - 1; } } return cntTriplet; } // Driver code public static void Main(String[] args) { int N = 3; Console.WriteLine(findCntTriplet(N)); }} // This code is contributed by 29AjayKumar", "e": 29480, "s": 28691, "text": null }, { "code": "<script> // javascript program for the above approach // Function to find the count of // triplets (a, b, c) with a * b + c = N function findCntTriplet(N) { // Stores count of triplets of 1st // N natural numbers which are of // the form a * b + c = N let cntTriplet = 0; // Iterate over the range [1, N] for (let i = 1; i < N; i++) { // If N is divisible by i if (N % i != 0) { // Update cntTriplet cntTriplet += Math.floor(N / i); } else { // Update cntTriplet cntTriplet += Math.floor(N / i) - 1; } } return cntTriplet; } // Driver Code let N = 3; document.write(findCntTriplet(N)); </script>", "e": 30193, "s": 29480, "text": null }, { "code": null, "e": 30195, "s": 30193, "text": "3" }, { "code": null, "e": 30240, "s": 30197, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 30262, "s": 30240, "text": "susmitakundugoaldanga" }, { "code": null, "e": 30274, "s": 30262, "text": "29AjayKumar" }, { "code": null, "e": 30290, "s": 30274, "text": "souravghosh0416" }, { "code": null, "e": 30303, "s": 30290, "text": "divisibility" }, { "code": null, "e": 30310, "s": 30303, "text": "Greedy" }, { "code": null, "e": 30323, "s": 30310, "text": "Mathematical" }, { "code": null, "e": 30333, "s": 30323, "text": "Searching" }, { "code": null, "e": 30343, "s": 30333, "text": "Searching" }, { "code": null, "e": 30350, "s": 30343, "text": "Greedy" }, { "code": null, "e": 30363, "s": 30350, "text": "Mathematical" }, { "code": null, "e": 30461, "s": 30363, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30470, "s": 30461, "text": "Comments" }, { "code": null, "e": 30483, "s": 30470, "text": "Old Comments" }, { "code": null, "e": 30514, "s": 30483, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 30557, "s": 30514, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 30576, "s": 30557, "text": "Coin Change | DP-7" }, { "code": null, "e": 30604, "s": 30576, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 30685, "s": 30604, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 30715, "s": 30685, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30730, "s": 30715, "text": "C++ Data Types" }, { "code": null, "e": 30773, "s": 30730, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 30792, "s": 30773, "text": "Coin Change | DP-7" } ]
What does the repr() function do in Python Object Oriented Programming?
The official Python documentation says __repr__() is used to compute the “official” string representation of an object. The repr() built-in function uses __repr__() to display the object. __repr__() returns a printable representation of the object, one of the ways possible to create this object. __repr__() is more useful for developers while __str__() is for end users. The following code shows how __repr__() is used. class Point: def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return 'Point(x=%s, y=%s)' % (self.x, self.y) p = Point(3, 4) print p This gives the output Point(x=3, y=4) Lets consider another example of use of repr() function and create a datetime object − >>> import datetime >>> today = datetime.datetime.now() When I use the built-in function repr() to display today − >>> repr(today) 'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)' We can see that this returned a string but this string is the “official” representation of a datetime object which means that using this “official” string representation we can reconstruct the object − >>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)') datetime.datetime(2012, 3, 14, 9, 21, 58, 130922) The eval() built-in function accepts a string and converts it to a datetime object.
[ { "code": null, "e": 1436, "s": 1062, "text": "The official Python documentation says __repr__() is used to compute the “official” string representation of an object. The repr() built-in function uses __repr__() to display the object. __repr__() returns a printable representation of the object, one of the ways possible to create this object. __repr__() is more useful for developers while __str__() is for end users." }, { "code": null, "e": 1485, "s": 1436, "text": "The following code shows how __repr__() is used." }, { "code": null, "e": 1658, "s": 1485, "text": "class Point:\n\n def __init__(self, x, y):\n\n self.x, self.y = x, y\n\n def __repr__(self):\n\n return 'Point(x=%s, y=%s)' % (self.x, self.y)\n\np = Point(3, 4)\n\nprint p" }, { "code": null, "e": 1680, "s": 1658, "text": "This gives the output" }, { "code": null, "e": 1696, "s": 1680, "text": "Point(x=3, y=4)" }, { "code": null, "e": 1783, "s": 1696, "text": "Lets consider another example of use of repr() function and create a datetime object −" }, { "code": null, "e": 1839, "s": 1783, "text": ">>> import datetime\n>>> today = datetime.datetime.now()" }, { "code": null, "e": 1898, "s": 1839, "text": "When I use the built-in function repr() to display today −" }, { "code": null, "e": 1966, "s": 1898, "text": ">>> repr(today)\n'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'" }, { "code": null, "e": 2168, "s": 1966, "text": "We can see that this returned a string but this string is the “official” representation of a datetime object which means that using this “official” string representation we can reconstruct the object −" }, { "code": null, "e": 2280, "s": 2168, "text": ">>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)')\ndatetime.datetime(2012, 3, 14, 9, 21, 58, 130922)" }, { "code": null, "e": 2364, "s": 2280, "text": "The eval() built-in function accepts a string and converts it to a datetime object." } ]
Change the ratio between width and height of an image using Python - Pillow - GeeksforGeeks
23 Dec, 2020 Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. This module is not preloaded with Python. So to install it execute the following command in the command-line: pip install pillow To change the ratio of height and width we will add or subtract any random value from them. Image.open(fp, mode=’r’) method: This method is used to open the image. Image.resize(size, resample=0) method: This method is used to resize the image. Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original). We will first take an image. Then we will find its height and width. Then we will add and subtract any random number from them to change the ratio. Then we will save the image. Example: Image Used: Python3 # Python program to change the ratio of height and# width of an image from PIL import Image # Taking image as inputimg = Image.open('logo.png') # Getting height and width of the imageheight = img.size[0]width = img.size[1] # Printing ratio before conversionprint('Ratio before conversion:', width/height) # Changing the height and width of the imagewidth = width + 25height = height - 25 # Resizing the imageimg = img.resize((width ,height), Image.ANTIALIAS) # Printing the ratio after conversionprint('Ratio after conversion:', width/height) # Saving the resized imageimg.save('Resized Image.png') Output: Ratio before conversion: 1.0 Ratio after conversion: 1.25 Output Image: Picked Python-pil Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Dec, 2020" }, { "code": null, "e": 24611, "s": 24292, "text": "Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. This module is not preloaded with Python. So to install it execute the following command in the command-line:" }, { "code": null, "e": 24630, "s": 24611, "text": "pip install pillow" }, { "code": null, "e": 24722, "s": 24630, "text": "To change the ratio of height and width we will add or subtract any random value from them." }, { "code": null, "e": 24794, "s": 24722, "text": "Image.open(fp, mode=’r’) method: This method is used to open the image." }, { "code": null, "e": 25096, "s": 24794, "text": "Image.resize(size, resample=0) method: This method is used to resize the image. Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original)." }, { "code": null, "e": 25125, "s": 25096, "text": "We will first take an image." }, { "code": null, "e": 25165, "s": 25125, "text": "Then we will find its height and width." }, { "code": null, "e": 25244, "s": 25165, "text": "Then we will add and subtract any random number from them to change the ratio." }, { "code": null, "e": 25273, "s": 25244, "text": "Then we will save the image." }, { "code": null, "e": 25282, "s": 25273, "text": "Example:" }, { "code": null, "e": 25294, "s": 25282, "text": "Image Used:" }, { "code": null, "e": 25302, "s": 25294, "text": "Python3" }, { "code": "# Python program to change the ratio of height and# width of an image from PIL import Image # Taking image as inputimg = Image.open('logo.png') # Getting height and width of the imageheight = img.size[0]width = img.size[1] # Printing ratio before conversionprint('Ratio before conversion:', width/height) # Changing the height and width of the imagewidth = width + 25height = height - 25 # Resizing the imageimg = img.resize((width ,height), Image.ANTIALIAS) # Printing the ratio after conversionprint('Ratio after conversion:', width/height) # Saving the resized imageimg.save('Resized Image.png')", "e": 25908, "s": 25302, "text": null }, { "code": null, "e": 25916, "s": 25908, "text": "Output:" }, { "code": null, "e": 25974, "s": 25916, "text": "Ratio before conversion: 1.0\nRatio after conversion: 1.25" }, { "code": null, "e": 25988, "s": 25974, "text": "Output Image:" }, { "code": null, "e": 25995, "s": 25988, "text": "Picked" }, { "code": null, "e": 26006, "s": 25995, "text": "Python-pil" }, { "code": null, "e": 26030, "s": 26006, "text": "Technical Scripter 2020" }, { "code": null, "e": 26037, "s": 26030, "text": "Python" }, { "code": null, "e": 26056, "s": 26037, "text": "Technical Scripter" }, { "code": null, "e": 26154, "s": 26056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26163, "s": 26154, "text": "Comments" }, { "code": null, "e": 26176, "s": 26163, "text": "Old Comments" }, { "code": null, "e": 26208, "s": 26176, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26250, "s": 26208, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26305, "s": 26250, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26361, "s": 26305, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26403, "s": 26361, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26425, "s": 26403, "text": "Defaultdict in Python" }, { "code": null, "e": 26464, "s": 26425, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26495, "s": 26464, "text": "Python | os.path.join() method" }, { "code": null, "e": 26524, "s": 26495, "text": "Create a directory in Python" } ]
Normal Probability Plot in R using ggplot2 - GeeksforGeeks
14 Jan, 2022 A normal probability plot is a graphical representation of the data. A normal probability plot is used to check if the given data set is normally distributed or not. It is used to compare a data set with the normal distribution. If a given data set is normally distributed then it will reside in a shape like a straight line. In this article, we are going to use ggplot2 with qqplotr to plot and check if the dataset is normally distributed using qqplot only. Install the following necessary libraries by pasting them in r console install.packages(“ggplot2”) install.packages(“qqplotr”) Create a random data set with a different mean and standard deviation that you want to plot. Plotting data using stat_qq_point() method. Plotting data points with line using stat_qq_line() function. Given below is a proper implementation using the above approach Example 1: Plotting data using stat_qq_point() method. R # importing libraries library(ggplot2) library(qqplotr) # creating random data random_values = rnorm(500, mean = 90, sd = 50) # plotting data without line and labels ggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2) Output: Fig. 1 Plotting Data points. Example 2: Plotting data points with line using stat_qq_line() function. R # importing libraries library(ggplot2) library(qqplotr) # creating random data random_values = rnorm(500, mean = 90, sd = 50) # plotting data with proper labels # And adding line with proper properties ggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2,color = "red") + stat_qq_line(color="green") + xlab("x-axis") + ylab("y-axis") Output: Fig. 2 Adding normal line adnanirshad158 Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R R - if statement
[ { "code": null, "e": 25314, "s": 25283, "text": " \n14 Jan, 2022\n" }, { "code": null, "e": 25640, "s": 25314, "text": "A normal probability plot is a graphical representation of the data. A normal probability plot is used to check if the given data set is normally distributed or not. It is used to compare a data set with the normal distribution. If a given data set is normally distributed then it will reside in a shape like a straight line." }, { "code": null, "e": 25774, "s": 25640, "text": "In this article, we are going to use ggplot2 with qqplotr to plot and check if the dataset is normally distributed using qqplot only." }, { "code": null, "e": 25845, "s": 25774, "text": "Install the following necessary libraries by pasting them in r console" }, { "code": null, "e": 25873, "s": 25845, "text": "install.packages(“ggplot2”)" }, { "code": null, "e": 25901, "s": 25873, "text": "install.packages(“qqplotr”)" }, { "code": null, "e": 25994, "s": 25901, "text": "Create a random data set with a different mean and standard deviation that you want to plot." }, { "code": null, "e": 26038, "s": 25994, "text": "Plotting data using stat_qq_point() method." }, { "code": null, "e": 26100, "s": 26038, "text": "Plotting data points with line using stat_qq_line() function." }, { "code": null, "e": 26165, "s": 26100, "text": "Given below is a proper implementation using the above approach " }, { "code": null, "e": 26220, "s": 26165, "text": "Example 1: Plotting data using stat_qq_point() method." }, { "code": null, "e": 26222, "s": 26220, "text": "R" }, { "code": "\n\n\n\n\n\n\n# importing libraries\nlibrary(ggplot2)\nlibrary(qqplotr)\n \n# creating random data\nrandom_values = rnorm(500, mean = 90, sd = 50)\n \n# plotting data without line and labels\nggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2)\n\n\n\n\n\n", "e": 26487, "s": 26232, "text": null }, { "code": null, "e": 26495, "s": 26487, "text": "Output:" }, { "code": null, "e": 26524, "s": 26495, "text": "Fig. 1 Plotting Data points." }, { "code": null, "e": 26597, "s": 26524, "text": "Example 2: Plotting data points with line using stat_qq_line() function." }, { "code": null, "e": 26599, "s": 26597, "text": "R" }, { "code": "\n\n\n\n\n\n\n# importing libraries\nlibrary(ggplot2)\nlibrary(qqplotr)\n \n# creating random data\nrandom_values = rnorm(500, mean = 90, sd = 50)\n \n# plotting data with proper labels \n# And adding line with proper properties\nggplot(mapping = aes(sample = random_values)) \n+ stat_qq_point(size = 2,color = \"red\") \n+ stat_qq_line(color=\"green\") \n+ xlab(\"x-axis\") + ylab(\"y-axis\")\n\n\n\n\n\n", "e": 26982, "s": 26609, "text": null }, { "code": null, "e": 26990, "s": 26982, "text": "Output:" }, { "code": null, "e": 27016, "s": 26990, "text": "Fig. 2 Adding normal line" }, { "code": null, "e": 27031, "s": 27016, "text": "adnanirshad158" }, { "code": null, "e": 27040, "s": 27031, "text": "\nPicked\n" }, { "code": null, "e": 27051, "s": 27040, "text": "\nR-Charts\n" }, { "code": null, "e": 27062, "s": 27051, "text": "\nR-Graphs\n" }, { "code": null, "e": 27072, "s": 27062, "text": "\nR-plots\n" }, { "code": null, "e": 27085, "s": 27072, "text": "\nR Language\n" }, { "code": null, "e": 27290, "s": 27085, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27342, "s": 27290, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27380, "s": 27342, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27415, "s": 27380, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27473, "s": 27415, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27522, "s": 27473, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27559, "s": 27522, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 27585, "s": 27559, "text": "Time Series Analysis in R" }, { "code": null, "e": 27635, "s": 27585, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27678, "s": 27635, "text": "Replace Specific Characters in String in R" } ]
SWING - GridLayout Class
The class GridLayout arranges the components in a rectangular grid. Following is the declaration for java.awt.GridLayout class − public class GridLayout extends Object implements LayoutManager, Serializable GridLayout() Creates a grid layout with a default of one column per component, in a single row. GridLayout(int rows, int cols) Creates a grid layout with the specified number of rows and columns. GridLayout(int rows, int cols, int hgap, int vgap) Creates a grid layout with the specified number of rows and columns. void addLayoutComponent(String name, Component comp) Adds the specified component with the specified name to the layout. int getColumns() Gets the number of columns in this layout. int getHgap() Gets the horizontal gap between the components. int getRows() Gets the number of rows in this layout. int getVgap() Gets the vertical gap between the components. void layoutContainer(Container parent) Lays out the specified container using this layout. Dimension minimumLayoutSize(Container parent) Determines the minimum size of the container argument using this grid layout. Dimension preferredLayoutSize(Container parent) Determines the preferred size of the container argument using this grid layout. void removeLayoutComponent(Component comp) Removes the specified component from the layout. void setColumns(int cols) Sets the number of columns in this layout to the specified value. void setHgap(int hgap) Sets the horizontal gap between the components to the specified value. void setRows(int rows) Sets the number of rows in this layout to the specified value. void setVgap(int vgap) Sets the vertical gap between the components to the specified value. String toString() Returns the string representation of this grid layout's values. This class inherits methods from the following class − java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingLayoutDemo.java package com.tutorialspoint.gui; import javax.swing.*; public class SwingLayoutDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; private JLabel msglabel; public SwingLayoutDemo(){ prepareGUI(); } public static void main(String[] args){ SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); swingLayoutDemo.showGridLayoutDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showGridLayoutDemo(){ headerLabel.setText("Layout in action: GridLayout"); JPanel panel = new JPanel(); panel.setBackground(Color.darkGray); panel.setSize(300,300); GridLayout layout = new GridLayout(0,3); layout.setHgap(10); layout.setVgap(10); panel.setLayout(layout); panel.add(new JButton("Button 1")); panel.add(new JButton("Button 2")); panel.add(new JButton("Button 3")); panel.add(new JButton("Button 4")); panel.add(new JButton("Button 5")); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo Verify the following output. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1831, "s": 1763, "text": "The class GridLayout arranges the components in a rectangular grid." }, { "code": null, "e": 1892, "s": 1831, "text": "Following is the declaration for java.awt.GridLayout class −" }, { "code": null, "e": 1980, "s": 1892, "text": "public class GridLayout\n extends Object\n implements LayoutManager, Serializable\n" }, { "code": null, "e": 1993, "s": 1980, "text": "GridLayout()" }, { "code": null, "e": 2076, "s": 1993, "text": "Creates a grid layout with a default of one column per component, in a single row." }, { "code": null, "e": 2107, "s": 2076, "text": "GridLayout(int rows, int cols)" }, { "code": null, "e": 2176, "s": 2107, "text": "Creates a grid layout with the specified number of rows and columns." }, { "code": null, "e": 2227, "s": 2176, "text": "GridLayout(int rows, int cols, int hgap, int vgap)" }, { "code": null, "e": 2296, "s": 2227, "text": "Creates a grid layout with the specified number of rows and columns." }, { "code": null, "e": 2349, "s": 2296, "text": "void addLayoutComponent(String name, Component comp)" }, { "code": null, "e": 2417, "s": 2349, "text": "Adds the specified component with the specified name to the layout." }, { "code": null, "e": 2434, "s": 2417, "text": "int getColumns()" }, { "code": null, "e": 2477, "s": 2434, "text": "Gets the number of columns in this layout." }, { "code": null, "e": 2491, "s": 2477, "text": "int getHgap()" }, { "code": null, "e": 2539, "s": 2491, "text": "Gets the horizontal gap between the components." }, { "code": null, "e": 2553, "s": 2539, "text": "int getRows()" }, { "code": null, "e": 2593, "s": 2553, "text": "Gets the number of rows in this layout." }, { "code": null, "e": 2607, "s": 2593, "text": "int getVgap()" }, { "code": null, "e": 2653, "s": 2607, "text": "Gets the vertical gap between the components." }, { "code": null, "e": 2692, "s": 2653, "text": "void layoutContainer(Container parent)" }, { "code": null, "e": 2744, "s": 2692, "text": "Lays out the specified container using this layout." }, { "code": null, "e": 2790, "s": 2744, "text": "Dimension minimumLayoutSize(Container parent)" }, { "code": null, "e": 2868, "s": 2790, "text": "Determines the minimum size of the container argument using this grid layout." }, { "code": null, "e": 2916, "s": 2868, "text": "Dimension preferredLayoutSize(Container parent)" }, { "code": null, "e": 2996, "s": 2916, "text": "Determines the preferred size of the container argument using this grid layout." }, { "code": null, "e": 3039, "s": 2996, "text": "void removeLayoutComponent(Component comp)" }, { "code": null, "e": 3088, "s": 3039, "text": "Removes the specified component from the layout." }, { "code": null, "e": 3114, "s": 3088, "text": "void setColumns(int cols)" }, { "code": null, "e": 3180, "s": 3114, "text": "Sets the number of columns in this layout to the specified value." }, { "code": null, "e": 3203, "s": 3180, "text": "void setHgap(int hgap)" }, { "code": null, "e": 3274, "s": 3203, "text": "Sets the horizontal gap between the components to the specified value." }, { "code": null, "e": 3297, "s": 3274, "text": "void setRows(int rows)" }, { "code": null, "e": 3360, "s": 3297, "text": "Sets the number of rows in this layout to the specified value." }, { "code": null, "e": 3383, "s": 3360, "text": "void setVgap(int vgap)" }, { "code": null, "e": 3452, "s": 3383, "text": "Sets the vertical gap between the components to the specified value." }, { "code": null, "e": 3470, "s": 3452, "text": "String toString()" }, { "code": null, "e": 3534, "s": 3470, "text": "Returns the string representation of this grid layout's values." }, { "code": null, "e": 3589, "s": 3534, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 3606, "s": 3589, "text": "java.lang.Object" }, { "code": null, "e": 3722, "s": 3606, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 3743, "s": 3722, "text": "SwingLayoutDemo.java" }, { "code": null, "e": 5579, "s": 3743, "text": "package com.tutorialspoint.gui;\n\nimport javax.swing.*;\n\npublic class SwingLayoutDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n private JLabel msglabel;\n \n public SwingLayoutDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); \n swingLayoutDemo.showGridLayoutDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showGridLayoutDemo(){\n headerLabel.setText(\"Layout in action: GridLayout\"); \n \n JPanel panel = new JPanel();\n panel.setBackground(Color.darkGray);\n panel.setSize(300,300);\n GridLayout layout = new GridLayout(0,3);\n layout.setHgap(10);\n layout.setVgap(10);\n \n panel.setLayout(layout); \n panel.add(new JButton(\"Button 1\"));\n panel.add(new JButton(\"Button 2\")); \n panel.add(new JButton(\"Button 3\")); \n panel.add(new JButton(\"Button 4\")); \n panel.add(new JButton(\"Button 5\")); \n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 5675, "s": 5579, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 5735, "s": 5675, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingLayoutDemo.java\n" }, { "code": null, "e": 5840, "s": 5735, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 5894, "s": 5840, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingLayoutDemo\n" }, { "code": null, "e": 5923, "s": 5894, "text": "Verify the following output." }, { "code": null, "e": 5958, "s": 5923, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5978, "s": 5958, "text": " Pranjal Srivastava" }, { "code": null, "e": 6011, "s": 5978, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 6031, "s": 6011, "text": " Pranjal Srivastava" }, { "code": null, "e": 6066, "s": 6031, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6102, "s": 6066, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6137, "s": 6102, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6150, "s": 6137, "text": " Travis Rose" }, { "code": null, "e": 6183, "s": 6150, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6196, "s": 6183, "text": " Travis Rose" }, { "code": null, "e": 6203, "s": 6196, "text": " Print" }, { "code": null, "e": 6214, "s": 6203, "text": " Add Notes" } ]
How to randomize and shuffle array of numbers in Java?
At first, create an integer array − int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200}; Now, create a Random class object − Random rand = new Random(); Loop until the length of the array and shuffle the elements − for (int i = 0; i < arr.length; ++i) { int index = rand.nextInt(arr.length - i); int tmp = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = arr[index]; arr[index] = tmp; } Live Demo import java.util.Arrays; import java.util.Random; public class Demo { public static void main(String[] args) { int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200}; System.out.println("The integer array = "+Arrays.toString(arr)); Random rand = new Random(); for(int i = 0; i < arr.length; ++i) { int index = rand.nextInt(arr.length - i); int tmp = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = arr[index]; arr[index] = tmp; } System.out.println("Shuffle integer array = "+Arrays.toString(arr)); } } The integer array = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200] Shuffle integer array = [160, 100, 20, 60, 140, 200, 120, 40, 80, 180]
[ { "code": null, "e": 1098, "s": 1062, "text": "At first, create an integer array −" }, { "code": null, "e": 1158, "s": 1098, "text": "int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};" }, { "code": null, "e": 1194, "s": 1158, "text": "Now, create a Random class object −" }, { "code": null, "e": 1222, "s": 1194, "text": "Random rand = new Random();" }, { "code": null, "e": 1284, "s": 1222, "text": "Loop until the length of the array and shuffle the elements −" }, { "code": null, "e": 1470, "s": 1284, "text": "for (int i = 0; i < arr.length; ++i) {\n int index = rand.nextInt(arr.length - i);\n int tmp = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = arr[index];\n arr[index] = tmp;\n}" }, { "code": null, "e": 1481, "s": 1470, "text": " Live Demo" }, { "code": null, "e": 2069, "s": 1481, "text": "import java.util.Arrays;\nimport java.util.Random;\npublic class Demo {\n public static void main(String[] args) {\n int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};\n System.out.println(\"The integer array = \"+Arrays.toString(arr));\n Random rand = new Random();\n for(int i = 0; i < arr.length; ++i) {\n int index = rand.nextInt(arr.length - i);\n int tmp = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = arr[index];\n arr[index] = tmp;\n }\n System.out.println(\"Shuffle integer array = \"+Arrays.toString(arr));\n }\n}" }, { "code": null, "e": 2207, "s": 2069, "text": "The integer array = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]\nShuffle integer array = [160, 100, 20, 60, 140, 200, 120, 40, 80, 180]" } ]
MySQL WHERE Clause
The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition. Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.! Below is a selection from the "Customers" table in the Northwind sample database: The following SQL statement selects all the customers from "Mexico": SQL requires single quotes around text values (most database systems will also allow double quotes). However, numeric fields should not be enclosed in quotes: The following operators can be used in the WHERE clause: Select all records where the City column has the value "Berlin". SELECT * FROM Customers = ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 44, "s": 0, "text": "The WHERE clause is used to filter records." }, { "code": null, "e": 122, "s": 44, "text": "It is used to extract only those records that fulfill a specified \ncondition." }, { "code": null, "e": 226, "s": 122, "text": "Note: The WHERE clause is not only used in \nSELECT statements, it is also used in UPDATE,\nDELETE, etc.!" }, { "code": null, "e": 308, "s": 226, "text": "Below is a selection from the \"Customers\" table in the Northwind sample database:" }, { "code": null, "e": 379, "s": 308, "text": "The following SQL statement selects all the customers from \n\"Mexico\":" }, { "code": null, "e": 481, "s": 379, "text": "SQL requires single quotes around text values (most database systems will \nalso allow double quotes)." }, { "code": null, "e": 539, "s": 481, "text": "However, numeric fields should not be enclosed in quotes:" }, { "code": null, "e": 596, "s": 539, "text": "The following operators can be used in the WHERE clause:" }, { "code": null, "e": 661, "s": 596, "text": "Select all records where the City column has the value \"Berlin\"." }, { "code": null, "e": 692, "s": 661, "text": "SELECT * FROM Customers\n = ;\n" }, { "code": null, "e": 711, "s": 692, "text": "Start the Exercise" }, { "code": null, "e": 744, "s": 711, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 786, "s": 744, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 893, "s": 786, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 912, "s": 893, "text": "[email protected]" } ]
How to list all users in the Mongo shell?
In order to list all users in the Mongo shell, use the getUsers() method or show command. Case 1 − Using getUsers() The syntax is as follows − db.getUsers(); Case 2 − Using show command The syntax is as follows − show users; Let us implement both the syntaxes in order to list all users in the Mongo shell. Case 1 − The first query is as follows − > db.getUsers(); The following is the output − [ { "_id" : "test.John", "user" : "John", "db" : "test", "roles" : [ { "role" : "readWrite", "db" : "test" }, { "role" : "dbAdmin", "db" : "test" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }, { "_id" : "test.admin", "user" : "admin", "db" : "test", "roles" : [ { "role" : "root", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } ] Case 2 − The second query is as follows − > show users; The following is the output − { "_id" : "test.John", "user" : "John", "db" : "test", "roles" : [ { "role" : "readWrite", "db" : "test" }, { "role" : "dbAdmin", "db" : "test" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } { "_id" : "test.admin", "user" : "admin", "db" : "test", "roles" : [ { "role" : "root", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }
[ { "code": null, "e": 1152, "s": 1062, "text": "In order to list all users in the Mongo shell, use the getUsers() method or show command." }, { "code": null, "e": 1178, "s": 1152, "text": "Case 1 − Using getUsers()" }, { "code": null, "e": 1205, "s": 1178, "text": "The syntax is as follows −" }, { "code": null, "e": 1220, "s": 1205, "text": "db.getUsers();" }, { "code": null, "e": 1248, "s": 1220, "text": "Case 2 − Using show command" }, { "code": null, "e": 1275, "s": 1248, "text": "The syntax is as follows −" }, { "code": null, "e": 1287, "s": 1275, "text": "show users;" }, { "code": null, "e": 1369, "s": 1287, "text": "Let us implement both the syntaxes in order to list all users in the Mongo shell." }, { "code": null, "e": 1410, "s": 1369, "text": "Case 1 − The first query is as follows −" }, { "code": null, "e": 1427, "s": 1410, "text": "> db.getUsers();" }, { "code": null, "e": 1457, "s": 1427, "text": "The following is the output −" }, { "code": null, "e": 2081, "s": 1457, "text": "[\n {\n \"_id\" : \"test.John\",\n \"user\" : \"John\",\n \"db\" : \"test\",\n \"roles\" : [\n {\n \"role\" : \"readWrite\",\n \"db\" : \"test\"\n },\n {\n \"role\" : \"dbAdmin\",\n \"db\" : \"test\"\n }\n ],\n \"mechanisms\" : [\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\"\n ]\n },\n {\n \"_id\" : \"test.admin\",\n \"user\" : \"admin\",\n \"db\" : \"test\",\n \"roles\" : [\n {\n \"role\" : \"root\",\n \"db\" : \"admin\"\n }\n ],\n \"mechanisms\" : [\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\"\n ]\n }\n]" }, { "code": null, "e": 2123, "s": 2081, "text": "Case 2 − The second query is as follows −" }, { "code": null, "e": 2137, "s": 2123, "text": "> show users;" }, { "code": null, "e": 2167, "s": 2137, "text": "The following is the output −" }, { "code": null, "e": 2684, "s": 2167, "text": "{\n \"_id\" : \"test.John\",\n \"user\" : \"John\",\n \"db\" : \"test\",\n \"roles\" : [\n {\n \"role\" : \"readWrite\",\n \"db\" : \"test\"\n },\n {\n \"role\" : \"dbAdmin\",\n \"db\" : \"test\"\n }\n ],\n \"mechanisms\" : [\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\"\n ]\n}\n{\n \"_id\" : \"test.admin\",\n \"user\" : \"admin\",\n \"db\" : \"test\",\n \"roles\" : [\n {\n \"role\" : \"root\",\n \"db\" : \"admin\"\n }\n ],\n \"mechanisms\" : [\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\"\n ]\n}" } ]
Tryit Editor v3.6 - Show Python
f = open("demofile.txt", "r")
[]
Extracting Speech from Video using Python | by Behic Guven | Towards Data Science
In this post, I will show you how to extract speeches from a video recording file. After recognizing the speeches we will convert them into a text document. This will be a simple machine learning project, that will help you to understand some basics of the Google Speech Recognition library. Speech Recognition is a popular topic under machine learning concepts. Speech Recognition is getting used more in many fields. For example, the subtitles that we see on Netflix shows or YouTube videos are created mostly by machines using Artificial Intelligence. Other great examples of speech recognizers are personal voice assistants such as Google’s Home Mini, Amazon Alexa, Apple’s Siri. Getting Started Step 1: Import Libraries Step 2: Video to Audio Conversion Step 3: Speech Recognition Final Step: Exporting Result As you can understand from the title, we will need a video recording for this project. It can even be a recording of yourself speaking to the camera. Using a library called MoviePy, we will extract the audio from the video recording. And in the next step, we will convert that audio file into text using Google’s speech recognition library. If you are ready, let’s get started by installing the libraries! We are going to use two libraries for this project: Speech Recognition MoviePy Before importing them to our project file, we have to install them. Installing a module library is very easy in python. You can even install a couple of libraries in one line of code. Write the following line in your terminal window: pip install SpeechRecognition moviepy Yes, that was it. SpeechRecognition module supports multiple recognition APIs, and Google Speech API is one of them. You can learn more about the module from here. MoviePy is a library that can read and write all the most common audio and video formats, including GIF. If you are having issues when installing moviepy library, try by installing ffmpeg. Ffmpeg is a leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created. Now, we should get to writing code in our code editor. We will start by importing the libraries. import speech_recognition as sr import moviepy.editor as mp Yes, that’s all we need to get the task done. Without losing any time let’s move to the next step. In this step, we will something really cool, which is converting our video recording into an audio file. There are many video formats, some of them can be listed as: MP4 (mp4, m4a, m4v, f4v, f4a, m4b, m4r, f4b, mov) 3GP (3gp, 3gp2, 3g2, 3gpp, 3gpp2) OGG (ogg, oga, ogv, ogx) WMV (wmv, wma, asf*) We should know our video’s format to do the conversion without any problem. Besides the video format, it’s also a good practice to know some audio formats. Here are some of them: MP3 AAC WMA AC3 (Dolby Digital) Now, we have some idea about both formats. It’s time to do the conversion using MoviePy library. You will not believe how easy it is. clip = mp.VideoFileClip(r”video_recording.mov”) clip.audio.write_audiofile(r”converted.wav”) I recommend converting it to wav format. It works great with the speech recognition library, which will be covered in the next step. towardsdatascience.com First, let’s define the recognizer. r = sr.Recognizer() Now let’s import the audio file that was created in the previous step (Step 2). audio = sr.AudioFile("converted.wav") Perfect! Here comes the best part, which is recognizing the speech in an audio file. The recognizer will try to understand the speech and convert it to a text format. with audio as source: audio_file = r.record(source)result = r.recognize_google(audio_file) Well done! The hard work is completed. In this step, we will just export the recognized speech into a text document. This will help you to store your work. I’ve also added a print(“ready!”) at the end of the code. So that we know when the file is ready and the work is completed. # exporting the result with open('recognized.txt',mode ='w') as file: file.write("Recognized Speech:") file.write("\n") file.write(result) print("ready!") Just started my journey on YouTube, I will be demonstrating Machine Learning, Data Science, Artificial Intelligence and more projects for you. Enjoy! lifexplorer.medium.com Congrats! You have created a program that converts a video into an audio file and then extracts the speech from that audio. And lastly, exporting the recognized speech into a text document. Hoping that you enjoyed reading this post and working on the project. I am glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. Feel free to contact me if you have any questions while implementing the code. Follow my blog and Towards Data Science to stay inspired.
[ { "code": null, "e": 855, "s": 171, "text": "In this post, I will show you how to extract speeches from a video recording file. After recognizing the speeches we will convert them into a text document. This will be a simple machine learning project, that will help you to understand some basics of the Google Speech Recognition library. Speech Recognition is a popular topic under machine learning concepts. Speech Recognition is getting used more in many fields. For example, the subtitles that we see on Netflix shows or YouTube videos are created mostly by machines using Artificial Intelligence. Other great examples of speech recognizers are personal voice assistants such as Google’s Home Mini, Amazon Alexa, Apple’s Siri." }, { "code": null, "e": 871, "s": 855, "text": "Getting Started" }, { "code": null, "e": 896, "s": 871, "text": "Step 1: Import Libraries" }, { "code": null, "e": 930, "s": 896, "text": "Step 2: Video to Audio Conversion" }, { "code": null, "e": 957, "s": 930, "text": "Step 3: Speech Recognition" }, { "code": null, "e": 986, "s": 957, "text": "Final Step: Exporting Result" }, { "code": null, "e": 1392, "s": 986, "text": "As you can understand from the title, we will need a video recording for this project. It can even be a recording of yourself speaking to the camera. Using a library called MoviePy, we will extract the audio from the video recording. And in the next step, we will convert that audio file into text using Google’s speech recognition library. If you are ready, let’s get started by installing the libraries!" }, { "code": null, "e": 1444, "s": 1392, "text": "We are going to use two libraries for this project:" }, { "code": null, "e": 1463, "s": 1444, "text": "Speech Recognition" }, { "code": null, "e": 1471, "s": 1463, "text": "MoviePy" }, { "code": null, "e": 1705, "s": 1471, "text": "Before importing them to our project file, we have to install them. Installing a module library is very easy in python. You can even install a couple of libraries in one line of code. Write the following line in your terminal window:" }, { "code": null, "e": 1743, "s": 1705, "text": "pip install SpeechRecognition moviepy" }, { "code": null, "e": 1907, "s": 1743, "text": "Yes, that was it. SpeechRecognition module supports multiple recognition APIs, and Google Speech API is one of them. You can learn more about the module from here." }, { "code": null, "e": 2269, "s": 1907, "text": "MoviePy is a library that can read and write all the most common audio and video formats, including GIF. If you are having issues when installing moviepy library, try by installing ffmpeg. Ffmpeg is a leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created." }, { "code": null, "e": 2366, "s": 2269, "text": "Now, we should get to writing code in our code editor. We will start by importing the libraries." }, { "code": null, "e": 2426, "s": 2366, "text": "import speech_recognition as sr import moviepy.editor as mp" }, { "code": null, "e": 2525, "s": 2426, "text": "Yes, that’s all we need to get the task done. Without losing any time let’s move to the next step." }, { "code": null, "e": 2691, "s": 2525, "text": "In this step, we will something really cool, which is converting our video recording into an audio file. There are many video formats, some of them can be listed as:" }, { "code": null, "e": 2741, "s": 2691, "text": "MP4 (mp4, m4a, m4v, f4v, f4a, m4b, m4r, f4b, mov)" }, { "code": null, "e": 2775, "s": 2741, "text": "3GP (3gp, 3gp2, 3g2, 3gpp, 3gpp2)" }, { "code": null, "e": 2800, "s": 2775, "text": "OGG (ogg, oga, ogv, ogx)" }, { "code": null, "e": 2821, "s": 2800, "text": "WMV (wmv, wma, asf*)" }, { "code": null, "e": 3000, "s": 2821, "text": "We should know our video’s format to do the conversion without any problem. Besides the video format, it’s also a good practice to know some audio formats. Here are some of them:" }, { "code": null, "e": 3004, "s": 3000, "text": "MP3" }, { "code": null, "e": 3008, "s": 3004, "text": "AAC" }, { "code": null, "e": 3012, "s": 3008, "text": "WMA" }, { "code": null, "e": 3032, "s": 3012, "text": "AC3 (Dolby Digital)" }, { "code": null, "e": 3166, "s": 3032, "text": "Now, we have some idea about both formats. It’s time to do the conversion using MoviePy library. You will not believe how easy it is." }, { "code": null, "e": 3260, "s": 3166, "text": "clip = mp.VideoFileClip(r”video_recording.mov”) clip.audio.write_audiofile(r”converted.wav”)" }, { "code": null, "e": 3393, "s": 3260, "text": "I recommend converting it to wav format. It works great with the speech recognition library, which will be covered in the next step." }, { "code": null, "e": 3416, "s": 3393, "text": "towardsdatascience.com" }, { "code": null, "e": 3452, "s": 3416, "text": "First, let’s define the recognizer." }, { "code": null, "e": 3472, "s": 3452, "text": "r = sr.Recognizer()" }, { "code": null, "e": 3552, "s": 3472, "text": "Now let’s import the audio file that was created in the previous step (Step 2)." }, { "code": null, "e": 3590, "s": 3552, "text": "audio = sr.AudioFile(\"converted.wav\")" }, { "code": null, "e": 3757, "s": 3590, "text": "Perfect! Here comes the best part, which is recognizing the speech in an audio file. The recognizer will try to understand the speech and convert it to a text format." }, { "code": null, "e": 3849, "s": 3757, "text": "with audio as source: audio_file = r.record(source)result = r.recognize_google(audio_file)" }, { "code": null, "e": 4129, "s": 3849, "text": "Well done! The hard work is completed. In this step, we will just export the recognized speech into a text document. This will help you to store your work. I’ve also added a print(“ready!”) at the end of the code. So that we know when the file is ready and the work is completed." }, { "code": null, "e": 4296, "s": 4129, "text": "# exporting the result with open('recognized.txt',mode ='w') as file: file.write(\"Recognized Speech:\") file.write(\"\\n\") file.write(result) print(\"ready!\")" }, { "code": null, "e": 4446, "s": 4296, "text": "Just started my journey on YouTube, I will be demonstrating Machine Learning, Data Science, Artificial Intelligence and more projects for you. Enjoy!" }, { "code": null, "e": 4469, "s": 4446, "text": "lifexplorer.medium.com" }, { "code": null, "e": 4877, "s": 4469, "text": "Congrats! You have created a program that converts a video into an audio file and then extracts the speech from that audio. And lastly, exporting the recognized speech into a text document. Hoping that you enjoyed reading this post and working on the project. I am glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills." }, { "code": null, "e": 4956, "s": 4877, "text": "Feel free to contact me if you have any questions while implementing the code." } ]
VBScript Debug Objects
The Debug Objects are global objects that can send output to a script debugger. Here, the debugger what we refer to is Microsoft Script Debugger. The Debug objects cannot be created like other objects but can be used when we are debugging. The following methods are supported by Debug Objects. These methods or objects have no effect if the script is NOT executed in debug mode. The Methods supported by Debug Objects are discussed in detail. The Write method sends strings to the immediate window of the Microsoft Script Debugger at run-time. If the script is not executed in debug mode, then the Write method has no effect. Write Debug.Write([str1 [, str2 [, ... [, strN]]]]) <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim counter counter = 42 Debug.Write "The value of counter is " & counter </script> </body> </html> The Writeline method is very similar to Write method. The WriteLine method sends strings, followed by a newline character, to the immediate window of the Microsoft Script Debugger at run time. If the script is not executed in debug mode, then the WriteLine method has no effect. Debug.WriteLine([str1 [, str2 [, ... [, strN]]]]) <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim counter counter = 42 Debug.WriteLine "The value of counter is " & counter </script> </body> </html> To enable script in debug mode, following actions to be performed by the user − On the Tools menu, click Internet Options. On the Tools menu, click Internet Options. In the Internet Options dialog box, click the Advanced tab. In the Internet Options dialog box, click the Advanced tab. In the Browsing category, clear the Disable script debugging check box. In the Browsing category, clear the Disable script debugging check box. Click OK. Click OK. Exit and restart Internet Explorer. Exit and restart Internet Explorer. 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2226, "s": 2080, "text": "The Debug Objects are global objects that can send output to a script debugger. Here, the debugger what we refer to is Microsoft Script Debugger." }, { "code": null, "e": 2320, "s": 2226, "text": "The Debug objects cannot be created like other objects but can be used when we are debugging." }, { "code": null, "e": 2523, "s": 2320, "text": "The following methods are supported by Debug Objects. These methods or objects have no effect if the script is NOT executed in debug mode. The Methods supported by Debug Objects are discussed in detail." }, { "code": null, "e": 2706, "s": 2523, "text": "The Write method sends strings to the immediate window of the Microsoft Script Debugger at run-time. If the script is not executed in debug mode, then the Write method has no effect." }, { "code": null, "e": 2759, "s": 2706, "text": "Write Debug.Write([str1 [, str2 [, ... [, strN]]]])\n" }, { "code": null, "e": 2996, "s": 2759, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim counter\n counter = 42\n Debug.Write \"The value of counter is \" & counter\n \n </script>\n </body>\n</html>" }, { "code": null, "e": 3275, "s": 2996, "text": "The Writeline method is very similar to Write method. The WriteLine method sends strings, followed by a newline character, to the immediate window of the Microsoft Script Debugger at run time. If the script is not executed in debug mode, then the WriteLine method has no effect." }, { "code": null, "e": 3326, "s": 3275, "text": "Debug.WriteLine([str1 [, str2 [, ... [, strN]]]])\n" }, { "code": null, "e": 3567, "s": 3326, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim counter\n counter = 42\n Debug.WriteLine \"The value of counter is \" & counter\n \n </script>\n </body>\n</html>" }, { "code": null, "e": 3647, "s": 3567, "text": "To enable script in debug mode, following actions to be performed by the user −" }, { "code": null, "e": 3690, "s": 3647, "text": "On the Tools menu, click Internet Options." }, { "code": null, "e": 3733, "s": 3690, "text": "On the Tools menu, click Internet Options." }, { "code": null, "e": 3793, "s": 3733, "text": "In the Internet Options dialog box, click the Advanced tab." }, { "code": null, "e": 3853, "s": 3793, "text": "In the Internet Options dialog box, click the Advanced tab." }, { "code": null, "e": 3925, "s": 3853, "text": "In the Browsing category, clear the Disable script debugging check box." }, { "code": null, "e": 3997, "s": 3925, "text": "In the Browsing category, clear the Disable script debugging check box." }, { "code": null, "e": 4007, "s": 3997, "text": "Click OK." }, { "code": null, "e": 4017, "s": 4007, "text": "Click OK." }, { "code": null, "e": 4053, "s": 4017, "text": "Exit and restart Internet Explorer." }, { "code": null, "e": 4089, "s": 4053, "text": "Exit and restart Internet Explorer." }, { "code": null, "e": 4122, "s": 4089, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 4139, "s": 4122, "text": " Frahaan Hussain" }, { "code": null, "e": 4146, "s": 4139, "text": " Print" }, { "code": null, "e": 4157, "s": 4146, "text": " Add Notes" } ]
C Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers) - GeeksforGeeks
21 Dec, 2021 Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Output: Sum found between indexes 2 and 4 Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7 Output: Sum found between indexes 1 and 4 Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7 Input: arr[] = {1, 4}, sum = 0 Output: No subarray found There is no subarray with 0 sum There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray. Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm: Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray. Traverse the array from start to end. From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum. For every index in inner loop update sum = sum + array[j] If the sum is equal to the given sum then print the subarray. C /* C program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // Try all subarrays starting // with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { printf( "Sum found between indexes %d and %d", i, j - 1); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } printf("No subarray found"); return 0;} // Driver codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;} Output : Sum found between indexes 1 and 4 Complexity Analysis: Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2) Space Complexity: O(1). As constant extra space is required. Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm: Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop. Create three variables, l=0, sum = 0 Traverse the array from start to end. Update the variable sum by adding current element, sum = sum + array[i] If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++. If the sum is equal to given sum, print the subarray and break the loop. C /* C efficient program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { printf( "Sum found between indexes %d and %d", start, i - 1); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray printf("No subarray found"); return 0;} // Driver codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;} Output : Sum found between indexes 1 and 4 Complexity Analysis: Time Complexity : O(n). Only one traversal of the array is required. So the time complexity is O(n). Space Complexity: O(1). As constant extra space is required. Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details! Amazon Facebook FactSet Google Morgan Stanley sliding-window subarray subarray-sum Visa Zoho Arrays C Programs Zoho Morgan Stanley Amazon FactSet Visa Google Facebook sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Building Heap from Array Trapping Rain Water Reversal algorithm for array rotation Program to find sum of elements in a given array Strings in C Arrow operator -> in C/C++ with Examples UDP Server-Client implementation in C C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24796, "s": 24768, "text": "\n21 Dec, 2021" }, { "code": null, "e": 24914, "s": 24796, "text": "Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : " }, { "code": null, "e": 25303, "s": 24914, "text": "Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33\nOutput: Sum found between indexes 2 and 4\nSum of elements between indices\n2 and 4 is 20 + 3 + 10 = 33\n\nInput: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7\nOutput: Sum found between indexes 1 and 4\nSum of elements between indices\n1 and 4 is 4 + 0 + 0 + 3 = 7\n\nInput: arr[] = {1, 4}, sum = 0\nOutput: No subarray found\nThere is no subarray with 0 sum" }, { "code": null, "e": 25419, "s": 25303, "text": "There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray. " }, { "code": null, "e": 25704, "s": 25419, "text": "Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm: " }, { "code": null, "e": 26001, "s": 25704, "text": "Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray." }, { "code": null, "e": 26039, "s": 26001, "text": "Traverse the array from start to end." }, { "code": null, "e": 26181, "s": 26039, "text": "From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum." }, { "code": null, "e": 26239, "s": 26181, "text": "For every index in inner loop update sum = sum + array[j]" }, { "code": null, "e": 26301, "s": 26239, "text": "If the sum is equal to the given sum then print the subarray." }, { "code": null, "e": 26303, "s": 26301, "text": "C" }, { "code": "/* C program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // Try all subarrays starting // with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { printf( \"Sum found between indexes %d and %d\", i, j - 1); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } printf(\"No subarray found\"); return 0;} // Driver codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}", "e": 27343, "s": 26303, "text": null }, { "code": null, "e": 27352, "s": 27343, "text": "Output :" }, { "code": null, "e": 27386, "s": 27352, "text": "Sum found between indexes 1 and 4" }, { "code": null, "e": 27409, "s": 27386, "text": "Complexity Analysis: " }, { "code": null, "e": 27523, "s": 27409, "text": "Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2)" }, { "code": null, "e": 27584, "s": 27523, "text": "Space Complexity: O(1). As constant extra space is required." }, { "code": null, "e": 28064, "s": 27584, "text": "Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm: " }, { "code": null, "e": 28393, "s": 28064, "text": "Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop." }, { "code": null, "e": 28430, "s": 28393, "text": "Create three variables, l=0, sum = 0" }, { "code": null, "e": 28468, "s": 28430, "text": "Traverse the array from start to end." }, { "code": null, "e": 28540, "s": 28468, "text": "Update the variable sum by adding current element, sum = sum + array[i]" }, { "code": null, "e": 28653, "s": 28540, "text": "If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++." }, { "code": null, "e": 28726, "s": 28653, "text": "If the sum is equal to given sum, print the subarray and break the loop." }, { "code": null, "e": 28728, "s": 28726, "text": "C" }, { "code": "/* C efficient program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { printf( \"Sum found between indexes %d and %d\", start, i - 1); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray printf(\"No subarray found\"); return 0;} // Driver codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}", "e": 30150, "s": 28728, "text": null }, { "code": null, "e": 30159, "s": 30150, "text": "Output :" }, { "code": null, "e": 30193, "s": 30159, "text": "Sum found between indexes 1 and 4" }, { "code": null, "e": 30216, "s": 30193, "text": "Complexity Analysis: " }, { "code": null, "e": 30317, "s": 30216, "text": "Time Complexity : O(n). Only one traversal of the array is required. So the time complexity is O(n)." }, { "code": null, "e": 30378, "s": 30317, "text": "Space Complexity: O(1). As constant extra space is required." }, { "code": null, "e": 30488, "s": 30378, "text": "Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details!" }, { "code": null, "e": 30495, "s": 30488, "text": "Amazon" }, { "code": null, "e": 30504, "s": 30495, "text": "Facebook" }, { "code": null, "e": 30512, "s": 30504, "text": "FactSet" }, { "code": null, "e": 30519, "s": 30512, "text": "Google" }, { "code": null, "e": 30534, "s": 30519, "text": "Morgan Stanley" }, { "code": null, "e": 30549, "s": 30534, "text": "sliding-window" }, { "code": null, "e": 30558, "s": 30549, "text": "subarray" }, { "code": null, "e": 30571, "s": 30558, "text": "subarray-sum" }, { "code": null, "e": 30576, "s": 30571, "text": "Visa" }, { "code": null, "e": 30581, "s": 30576, "text": "Zoho" }, { "code": null, "e": 30588, "s": 30581, "text": "Arrays" }, { "code": null, "e": 30599, "s": 30588, "text": "C Programs" }, { "code": null, "e": 30604, "s": 30599, "text": "Zoho" }, { "code": null, "e": 30619, "s": 30604, "text": "Morgan Stanley" }, { "code": null, "e": 30626, "s": 30619, "text": "Amazon" }, { "code": null, "e": 30634, "s": 30626, "text": "FactSet" }, { "code": null, "e": 30639, "s": 30634, "text": "Visa" }, { "code": null, "e": 30646, "s": 30639, "text": "Google" }, { "code": null, "e": 30655, "s": 30646, "text": "Facebook" }, { "code": null, "e": 30670, "s": 30655, "text": "sliding-window" }, { "code": null, "e": 30677, "s": 30670, "text": "Arrays" }, { "code": null, "e": 30775, "s": 30677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30800, "s": 30775, "text": "Window Sliding Technique" }, { "code": null, "e": 30825, "s": 30800, "text": "Building Heap from Array" }, { "code": null, "e": 30845, "s": 30825, "text": "Trapping Rain Water" }, { "code": null, "e": 30883, "s": 30845, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30932, "s": 30883, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30945, "s": 30932, "text": "Strings in C" }, { "code": null, "e": 30986, "s": 30945, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31024, "s": 30986, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31065, "s": 31024, "text": "C Program to read contents of Whole File" } ]
Map size() Method in Java With Examples
05 Sep, 2020 Map size() method in Java is used to get the total number entries i.e, key-value pair. So this method is useful when you want total entries present on the map. If the map contains more than Integer.MAX_VALUE elements return Integer.MAX_VALUE. Syntax: int size(); Parameter: This method does not take any parameter. Return value: This method returns the number of key-value mappings in this map. Example 1: For non-generic input Java // Java program to illustrate// the Map size() Methodimport java.util.*; public class MapSizeExample { // Main Method public static void main(String[] args) { Map map = new HashMap(); // Adding key-values map.put(1, "Amit"); map.put(5, "Rahul"); map.put(2, "Jai"); map.put(6, "Amit"); // using the method System.out.println("Size of the map is : " + map.size()); }} Output: Size of the map is : 4 Example 2: For Generic Input Java // Java program to illustrate// the Map size() Methodimport java.util.*; class MapSizeExample { // Main Method public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); map.put(4, "four"); // using the method System.out.println("Size of map is :" + map.size()); }} Output: Size of the map is : 4 Java-Collections java-map Java-Map-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Sep, 2020" }, { "code": null, "e": 297, "s": 54, "text": "Map size() method in Java is used to get the total number entries i.e, key-value pair. So this method is useful when you want total entries present on the map. If the map contains more than Integer.MAX_VALUE elements return Integer.MAX_VALUE." }, { "code": null, "e": 305, "s": 297, "text": "Syntax:" }, { "code": null, "e": 317, "s": 305, "text": "int size();" }, { "code": null, "e": 369, "s": 317, "text": "Parameter: This method does not take any parameter." }, { "code": null, "e": 449, "s": 369, "text": "Return value: This method returns the number of key-value mappings in this map." }, { "code": null, "e": 482, "s": 449, "text": "Example 1: For non-generic input" }, { "code": null, "e": 487, "s": 482, "text": "Java" }, { "code": "// Java program to illustrate// the Map size() Methodimport java.util.*; public class MapSizeExample { // Main Method public static void main(String[] args) { Map map = new HashMap(); // Adding key-values map.put(1, \"Amit\"); map.put(5, \"Rahul\"); map.put(2, \"Jai\"); map.put(6, \"Amit\"); // using the method System.out.println(\"Size of the map is : \" + map.size()); }}", "e": 974, "s": 487, "text": null }, { "code": null, "e": 982, "s": 974, "text": "Output:" }, { "code": null, "e": 1005, "s": 982, "text": "Size of the map is : 4" }, { "code": null, "e": 1034, "s": 1005, "text": "Example 2: For Generic Input" }, { "code": null, "e": 1039, "s": 1034, "text": "Java" }, { "code": "// Java program to illustrate// the Map size() Methodimport java.util.*; class MapSizeExample { // Main Method public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, \"one\"); map.put(2, \"two\"); map.put(3, \"three\"); map.put(4, \"four\"); // using the method System.out.println(\"Size of map is :\" + map.size()); }}", "e": 1522, "s": 1039, "text": null }, { "code": null, "e": 1530, "s": 1522, "text": "Output:" }, { "code": null, "e": 1553, "s": 1530, "text": "Size of the map is : 4" }, { "code": null, "e": 1570, "s": 1553, "text": "Java-Collections" }, { "code": null, "e": 1579, "s": 1570, "text": "java-map" }, { "code": null, "e": 1597, "s": 1579, "text": "Java-Map-Programs" }, { "code": null, "e": 1602, "s": 1597, "text": "Java" }, { "code": null, "e": 1607, "s": 1602, "text": "Java" }, { "code": null, "e": 1624, "s": 1607, "text": "Java-Collections" } ]
Python | Convert String to Tuple
21 Nov, 2019 Interconversion of data types is very common problem one can face while programming. There can be a problem in which we need to convert a string of integers to a tuple. Let’s discuss certain ways in which this can be done. Method #1 : Using map() + int + split() + tuple()This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple. # Python3 code to demonstrate working of# Convert String to Tuple# using map() + tuple() + int + split() # initialize stringtest_str = "1, -5, 4, 6, 7" # printing original string print("The original string : " + str(test_str)) # Convert String to Tuple# using map() + tuple() + int + split()res = tuple(map(int, test_str.split(', '))) # printing resultprint("Tuple after getting conversion from String : " + str(res)) The original string : 1, -5, 4, 6, 7 Tuple after getting conversion from String : (1, -5, 4, 6, 7) Method #2 : Using eval()This is the shorthand to perform this task. This converts the string to desired tuple internally. # Python3 code to demonstrate working of# Convert String to Tuple# Using eval() # initialize stringtest_str = "1, -5, 4, 6, 7" # printing original string print("The original string : " + str(test_str)) # Convert String to Tuple# Using eval()res = eval(test_str) # printing resultprint("Tuple after getting conversion from String : " + str(res)) The original string : 1, -5, 4, 6, 7 Tuple after getting conversion from String : (1, -5, 4, 6, 7) Python string-programs Python tuple-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": "\n21 Nov, 2019" }, { "code": null, "e": 251, "s": 28, "text": "Interconversion of data types is very common problem one can face while programming. There can be a problem in which we need to convert a string of integers to a tuple. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 470, "s": 251, "text": "Method #1 : Using map() + int + split() + tuple()This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple." }, { "code": "# Python3 code to demonstrate working of# Convert String to Tuple# using map() + tuple() + int + split() # initialize stringtest_str = \"1, -5, 4, 6, 7\" # printing original string print(\"The original string : \" + str(test_str)) # Convert String to Tuple# using map() + tuple() + int + split()res = tuple(map(int, test_str.split(', '))) # printing resultprint(\"Tuple after getting conversion from String : \" + str(res))", "e": 892, "s": 470, "text": null }, { "code": null, "e": 992, "s": 892, "text": "The original string : 1, -5, 4, 6, 7\nTuple after getting conversion from String : (1, -5, 4, 6, 7)\n" }, { "code": null, "e": 1116, "s": 994, "text": "Method #2 : Using eval()This is the shorthand to perform this task. This converts the string to desired tuple internally." }, { "code": "# Python3 code to demonstrate working of# Convert String to Tuple# Using eval() # initialize stringtest_str = \"1, -5, 4, 6, 7\" # printing original string print(\"The original string : \" + str(test_str)) # Convert String to Tuple# Using eval()res = eval(test_str) # printing resultprint(\"Tuple after getting conversion from String : \" + str(res))", "e": 1465, "s": 1116, "text": null }, { "code": null, "e": 1565, "s": 1465, "text": "The original string : 1, -5, 4, 6, 7\nTuple after getting conversion from String : (1, -5, 4, 6, 7)\n" }, { "code": null, "e": 1588, "s": 1565, "text": "Python string-programs" }, { "code": null, "e": 1610, "s": 1588, "text": "Python tuple-programs" }, { "code": null, "e": 1617, "s": 1610, "text": "Python" }, { "code": null, "e": 1633, "s": 1617, "text": "Python Programs" } ]
Output of C programs | Set 44 (Structure & Union)
14 Oct, 2020 Prerequisite: Structure and UnionQUE.1 What is the output of this program? C #include <stdio.h>struct sample { int a = 0; char b = 'A'; float c = 10.5;};int main(){ struct sample s; printf("%d, %c, %f", s.a, s.b, s.c); return 0;} OPTION a) Error b) 0, A, 10.5 c) 0, A, 10.500000 d) No Error, No Output Answer: a Explanation: Error: Can not initialize members here. We can only declare members inside the structure, initialization of member with declaration is not allowed in structure declaration.QUE.2 What is the output of this program? C #include <stdio.h>int main(){ struct bitfield { signed int a : 3; unsigned int b : 13; unsigned int c : 1; }; struct bitfield bit1 = { 2, 14, 1 }; printf("%ld", sizeof(bit1)); return 0;} OPTION a) 4 b) 6 c) 8 d) 12 Answer: a Explanation: struct bitfield bit1={2, 14, 1}; when we initialize it it will take only one value the will be int and size of int is 4QUE. 3 What is the output of this program? C #include <stdio.h>int main(){ typedef struct tag { char str[10]; int a; } har; har h1, h2 = { "IHelp", 10 }; h1 = h2; h1.str[1] = 'h'; printf("%s, %d", h1.str, h1.a); return 0;} OPTION a) ERROR b) IHelp, 10 c) IHelp, 0 d) Ihelp, 10 Answer : d Explanation : It is possible to copy one structure variable into another like h1 = h2. Hence value of h2. str is assigned to h1.str.QUE.4 What is the output? C #include <stdio.h> struct sample { int a;} sample; int main(){ sample.a = 100; printf("%d", sample.a); return 0;} OPTION a) 0 b) 100 c) ERROR d) Warning Answer Answer : b Explanation : This type of declaration is allowed in c.QUE.5 what is output of this program? C #include <stdio.h>int main(){ union test { int i; int j; }; union test var = 10; printf("%d, %d\n", var.i, var.j);} OPTION a) 10, 10 b) 10, 0 c) 0, 10 d) Compile Error Answer : d Explanation : Error: Invalid Initialization. You cannot initialize an union variable like this.Next Quiz onStructure and UnionThis article is contributed by Ajay Puri(ajay0007). 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. BhagyaRana C-Output C-Structure & Union Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Oct, 2020" }, { "code": null, "e": 130, "s": 54, "text": "Prerequisite: Structure and UnionQUE.1 What is the output of this program? " }, { "code": null, "e": 132, "s": 130, "text": "C" }, { "code": "#include <stdio.h>struct sample { int a = 0; char b = 'A'; float c = 10.5;};int main(){ struct sample s; printf(\"%d, %c, %f\", s.a, s.b, s.c); return 0;}", "e": 303, "s": 132, "text": null }, { "code": null, "e": 376, "s": 303, "text": "OPTION a) Error b) 0, A, 10.5 c) 0, A, 10.500000 d) No Error, No Output " }, { "code": null, "e": 387, "s": 376, "text": "Answer: a\n" }, { "code": null, "e": 615, "s": 387, "text": "Explanation: Error: Can not initialize members here. We can only declare members inside the structure, initialization of member with declaration is not allowed in structure declaration.QUE.2 What is the output of this program? " }, { "code": null, "e": 617, "s": 615, "text": "C" }, { "code": "#include <stdio.h>int main(){ struct bitfield { signed int a : 3; unsigned int b : 13; unsigned int c : 1; }; struct bitfield bit1 = { 2, 14, 1 }; printf(\"%ld\", sizeof(bit1)); return 0;}", "e": 840, "s": 617, "text": null }, { "code": null, "e": 869, "s": 840, "text": "OPTION a) 4 b) 6 c) 8 d) 12 " }, { "code": null, "e": 881, "s": 869, "text": "Answer: a\n" }, { "code": null, "e": 1057, "s": 881, "text": "Explanation: struct bitfield bit1={2, 14, 1}; when we initialize it it will take only one value the will be int and size of int is 4QUE. 3 What is the output of this program? " }, { "code": null, "e": 1059, "s": 1057, "text": "C" }, { "code": "#include <stdio.h>int main(){ typedef struct tag { char str[10]; int a; } har; har h1, h2 = { \"IHelp\", 10 }; h1 = h2; h1.str[1] = 'h'; printf(\"%s, %d\", h1.str, h1.a); return 0;}", "e": 1273, "s": 1059, "text": null }, { "code": null, "e": 1328, "s": 1273, "text": "OPTION a) ERROR b) IHelp, 10 c) IHelp, 0 d) Ihelp, 10 " }, { "code": null, "e": 1340, "s": 1328, "text": "Answer : d\n" }, { "code": null, "e": 1499, "s": 1340, "text": "Explanation : It is possible to copy one structure variable into another like h1 = h2. Hence value of h2. str is assigned to h1.str.QUE.4 What is the output? " }, { "code": null, "e": 1501, "s": 1499, "text": "C" }, { "code": "#include <stdio.h> struct sample { int a;} sample; int main(){ sample.a = 100; printf(\"%d\", sample.a); return 0;}", "e": 1627, "s": 1501, "text": null }, { "code": null, "e": 1674, "s": 1627, "text": "OPTION a) 0 b) 100 c) ERROR d) Warning Answer " }, { "code": null, "e": 1686, "s": 1674, "text": "Answer : b\n" }, { "code": null, "e": 1780, "s": 1686, "text": "Explanation : This type of declaration is allowed in c.QUE.5 what is output of this program? " }, { "code": null, "e": 1782, "s": 1780, "text": "C" }, { "code": "#include <stdio.h>int main(){ union test { int i; int j; }; union test var = 10; printf(\"%d, %d\\n\", var.i, var.j);}", "e": 1925, "s": 1782, "text": null }, { "code": null, "e": 1977, "s": 1925, "text": "OPTION a) 10, 10 b) 10, 0 c) 0, 10 d) Compile Error" }, { "code": null, "e": 1989, "s": 1977, "text": "Answer : d\n" }, { "code": null, "e": 2546, "s": 1989, "text": "Explanation : Error: Invalid Initialization. You cannot initialize an union variable like this.Next Quiz onStructure and UnionThis article is contributed by Ajay Puri(ajay0007). 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." }, { "code": null, "e": 2557, "s": 2546, "text": "BhagyaRana" }, { "code": null, "e": 2566, "s": 2557, "text": "C-Output" }, { "code": null, "e": 2586, "s": 2566, "text": "C-Structure & Union" }, { "code": null, "e": 2601, "s": 2586, "text": "Program Output" } ]
Python | time.clock() method
27 Sep, 2019 Time module in Python provides various time related functions. time.clock() method of time module in Python is used to get the current processor time as a floating point number expressed in seconds.As, Most of the functions defined in time module call corresponding C library function. time.clock() method also call C library function of the same name to get the result. The precision of returned float value depends on the called C library function. Note: This method is deprecated since Python version 3.3 and will be removed in Python version 3.8. The behaviour of this method is platform dependent. Syntax: time.clock() Parameter: No parameter is required. Return type: This method returns a float value which represents the current processor time in seconds. Code #1: Use of time.clock() method to get current processor time # Python program to explain time.clock() method # importing time moduleimport time # Get the current processor# time in secondspro_time = time.clock() # print the current # processor timeprint("Current processor time (in seconds):", pro_time) Current processor time (in seconds): 0.042379 Code #2: Use of time.clock() method to get current processor time # Python program to explain time.clock() method # importing time module import time # Function to calculate factorial # of the given number def factorial(n): f = 1 for i in range(n, 1, -1): f = f * i return f # Get the current processor time# in seconds at the # beginning of the calculation # using time.clock() method start = time.clock() # print the processor time in seconds print("At the beginning of the calculation") print("Processor time (in seconds):", start, "\n") # Calculate factorial of all # numbers form 0 to 9 i = 0fact = [0] * 10; while i < 10: fact[i] = factorial(i) i = i + 1 # Print the calculated factorial for i in range(0, len(fact)): print("Factorial of % d:" % i, fact[i]) # Get the processor time# in seconds at the end # of the calculation # using time.clock() method end = time.clock() print("\nAt the end of the calculation") print("Processor time (in seconds):", end) print("Time elapsed during the calculation:", end - start) At the beginning of the calculation Processor time (in seconds): 0.03451 Factorial of 0: 1 Factorial of 1: 1 Factorial of 2: 2 Factorial of 3: 6 Factorial of 4: 24 Factorial of 5: 120 Factorial of 6: 720 Factorial of 7: 5040 Factorial of 8: 40320 Factorial of 9: 362880 At the end of the calculation Processor time (in seconds): 0.034715 Time elapsed during the calculation: 0.0002050000000000038 Reference: https://docs.python.org/3/library/time.html#time.clock python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 91, "s": 28, "text": "Time module in Python provides various time related functions." }, { "code": null, "e": 479, "s": 91, "text": "time.clock() method of time module in Python is used to get the current processor time as a floating point number expressed in seconds.As, Most of the functions defined in time module call corresponding C library function. time.clock() method also call C library function of the same name to get the result. The precision of returned float value depends on the called C library function." }, { "code": null, "e": 631, "s": 479, "text": "Note: This method is deprecated since Python version 3.3 and will be removed in Python version 3.8. The behaviour of this method is platform dependent." }, { "code": null, "e": 652, "s": 631, "text": "Syntax: time.clock()" }, { "code": null, "e": 689, "s": 652, "text": "Parameter: No parameter is required." }, { "code": null, "e": 792, "s": 689, "text": "Return type: This method returns a float value which represents the current processor time in seconds." }, { "code": null, "e": 858, "s": 792, "text": "Code #1: Use of time.clock() method to get current processor time" }, { "code": "# Python program to explain time.clock() method # importing time moduleimport time # Get the current processor# time in secondspro_time = time.clock() # print the current # processor timeprint(\"Current processor time (in seconds):\", pro_time)", "e": 1104, "s": 858, "text": null }, { "code": null, "e": 1151, "s": 1104, "text": "Current processor time (in seconds): 0.042379\n" }, { "code": null, "e": 1217, "s": 1151, "text": "Code #2: Use of time.clock() method to get current processor time" }, { "code": "# Python program to explain time.clock() method # importing time module import time # Function to calculate factorial # of the given number def factorial(n): f = 1 for i in range(n, 1, -1): f = f * i return f # Get the current processor time# in seconds at the # beginning of the calculation # using time.clock() method start = time.clock() # print the processor time in seconds print(\"At the beginning of the calculation\") print(\"Processor time (in seconds):\", start, \"\\n\") # Calculate factorial of all # numbers form 0 to 9 i = 0fact = [0] * 10; while i < 10: fact[i] = factorial(i) i = i + 1 # Print the calculated factorial for i in range(0, len(fact)): print(\"Factorial of % d:\" % i, fact[i]) # Get the processor time# in seconds at the end # of the calculation # using time.clock() method end = time.clock() print(\"\\nAt the end of the calculation\") print(\"Processor time (in seconds):\", end) print(\"Time elapsed during the calculation:\", end - start) ", "e": 2239, "s": 1217, "text": null }, { "code": null, "e": 2650, "s": 2239, "text": "At the beginning of the calculation\nProcessor time (in seconds): 0.03451 \n\nFactorial of 0: 1\nFactorial of 1: 1\nFactorial of 2: 2\nFactorial of 3: 6\nFactorial of 4: 24\nFactorial of 5: 120\nFactorial of 6: 720\nFactorial of 7: 5040\nFactorial of 8: 40320\nFactorial of 9: 362880\n\nAt the end of the calculation\nProcessor time (in seconds): 0.034715\nTime elapsed during the calculation: 0.0002050000000000038\n" }, { "code": null, "e": 2716, "s": 2650, "text": "Reference: https://docs.python.org/3/library/time.html#time.clock" }, { "code": null, "e": 2731, "s": 2716, "text": "python-utility" }, { "code": null, "e": 2738, "s": 2731, "text": "Python" } ]
Concept of setjump and longjump in C
02 Jun, 2017 “Setjump” and “Longjump” are defined in setjmp.h, a header file in C standard library. setjump(jmp_buf buf) : uses buf to remember current position and returns 0. longjump(jmp_buf buf, i) : Go back to place buf is pointing to and return i . // A simple C program to demonstrate working of setjmp() and longjmp()#include<stdio.h>#include<setjmp.h>jmp_buf buf;void func(){ printf("Welcome to GeeksforGeeks\n"); // Jump to the point setup by setjmp longjmp(buf, 1); printf("Geek2\n");} int main(){ // Setup jump position using buf and return 0 if (setjmp(buf)) printf("Geek3\n"); else { printf("Geek4\n"); func(); } return 0;} Output : Geek4 Welcome to GeeksforGeeks Geek3 The main feature of these function is to provide a way that deviates from standard call and return sequence. This is mainly used to implement exception handling in C. setjmp can be used like try (in languages like C++ and Java). The call to longjmp can be used like throw (Note that longjmp() transfers control to the point set by setjmp()). This article is contributed by Aditya Chatterjee.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C-Library CPP-Library C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2017" }, { "code": null, "e": 139, "s": 52, "text": "“Setjump” and “Longjump” are defined in setjmp.h, a header file in C standard library." }, { "code": null, "e": 215, "s": 139, "text": "setjump(jmp_buf buf) : uses buf to remember current position and returns 0." }, { "code": null, "e": 293, "s": 215, "text": "longjump(jmp_buf buf, i) : Go back to place buf is pointing to and return i ." }, { "code": "// A simple C program to demonstrate working of setjmp() and longjmp()#include<stdio.h>#include<setjmp.h>jmp_buf buf;void func(){ printf(\"Welcome to GeeksforGeeks\\n\"); // Jump to the point setup by setjmp longjmp(buf, 1); printf(\"Geek2\\n\");} int main(){ // Setup jump position using buf and return 0 if (setjmp(buf)) printf(\"Geek3\\n\"); else { printf(\"Geek4\\n\"); func(); } return 0;}", "e": 732, "s": 293, "text": null }, { "code": null, "e": 741, "s": 732, "text": "Output :" }, { "code": null, "e": 778, "s": 741, "text": "Geek4\nWelcome to GeeksforGeeks\nGeek3" }, { "code": null, "e": 1120, "s": 778, "text": "The main feature of these function is to provide a way that deviates from standard call and return sequence. This is mainly used to implement exception handling in C. setjmp can be used like try (in languages like C++ and Java). The call to longjmp can be used like throw (Note that longjmp() transfers control to the point set by setjmp())." }, { "code": null, "e": 1293, "s": 1120, "text": "This article is contributed by Aditya Chatterjee.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 1303, "s": 1293, "text": "C-Library" }, { "code": null, "e": 1315, "s": 1303, "text": "CPP-Library" }, { "code": null, "e": 1326, "s": 1315, "text": "C Language" }, { "code": null, "e": 1330, "s": 1326, "text": "C++" }, { "code": null, "e": 1334, "s": 1330, "text": "CPP" } ]
Print all distinct characters of a string in order (3 Methods)
25 Jun, 2022 Given a string, find the all distinct (or non-repeating characters) in it. For example, if the input string is “Geeks for Geeks”, then output should be ‘for’ and if input string is “Geeks Quiz”, then output should be ‘GksQuiz’.The distinct characters should be printed in same order as they appear in input string.Examples: Input : Geeks for Geeks Output : for Input : Hello Geeks Output : HoGks Method 1 (Simple : O(n2)) A Simple Solution is to run two loops. Start traversing from left side. For every character, check if it repeats or not. If the character doesn’t repeat, increment count of non-repeating characters. When the count becomes 1, return each character. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int main(){ string str = "GeeksforGeeks"; for (int i = 0; i < str.size(); i++) { int flag = 0; for (int j = 0; j < str.size(); j++) { // checking if two characters are equal if (str[i] == str[j] and i != j) { flag = 1; break; } } if (flag == 0) cout << str[i]; } return 0;} // This code is contributed by umadevi9616 import java.util.*; class GFG{ public static void main(String[] args){ String str = "GeeksforGeeks"; for (int i = 0; i < str.length(); i++) { int flag = 0; for (int j = 0; j < str.length(); j++) { // checking if two characters are equal if (str.charAt(i) == str.charAt(j) && i != j) { flag = 1; break; } } if (flag == 0) System.out.print(str.charAt(i)); }}} // This code is contributed by gauravrajput1 string="GeeksforGeeks" for i in range(0,len(string)): flag=0 for j in range(0,len(string)): #checking if two characters are equal if(string[i]==string[j] and i!=j): flag=1 break if(flag==0): print(string[i],end="") using System; public class GFG{ public static void Main(String[] args){ String str = "GeeksforGeeks"; for (int i = 0; i < str.Length; i++) { int flag = 0; for (int j = 0; j < str.Length; j++) { // checking if two characters are equal if (str[i] == str[j] && i != j) { flag = 1; break; } } if (flag == 0) Console.Write(str[i]); }}} // This code is contributed by gauravrajput1 <script> var str = "GeeksforGeeks"; for (var i = 0; i < str.length; i++) { var flag = 0; for (j = 0; j < str.length; j++) { // checking if two characters are equal if (str.charAt(i) == str.charAt(j) && i != j) { flag = 1; break; } } if (flag == 0) document.write(str.charAt(i)); } // This code is contributed by gauravrajput1</script> for Time Complexity: O(n2) Auxiliary Space: O(1) Method 2 (Efficient but requires two traversals: O(n)) Create an array count[] to store counts of characters.Traverse the input string str and do following for every character x = str[i]. Increment count[x].Traverse the input string again and do following for every character str[i]If count[x] is 1, then print the unique characterIf count[x] is greater than 1, then ignore the repeated character. Create an array count[] to store counts of characters. Traverse the input string str and do following for every character x = str[i]. Increment count[x]. Traverse the input string again and do following for every character str[i]If count[x] is 1, then print the unique characterIf count[x] is greater than 1, then ignore the repeated character. If count[x] is 1, then print the unique characterIf count[x] is greater than 1, then ignore the repeated character. If count[x] is 1, then print the unique character If count[x] is greater than 1, then ignore the repeated character. Below is the implementation of above idea. C++ Java Python3 C# Javascript // C++ program to print distinct characters of a// string.# include <iostream>using namespace std;# define NO_OF_CHARS 256 /* Print duplicates present in the passed string */void printDistinct(char *str){ // Create an array of size 256 and count of // every character in it int count[NO_OF_CHARS]; /* Count array with frequency of characters */ int i; for (i = 0; *(str+i); i++) if(*(str+i)!=' ') count[*(str+i)]++; int n = i; // Print characters having count more than 0 for (i = 0; i < n; i++) if (count[*(str+i)] == 1) cout<< str[i];} /* Driver program*/int main(){ char str[] = "GeeksforGeeks"; printDistinct(str); return 0;} // Java program to print distinct characters of a// string.public class GFG { static final int NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ static void printDistinct(String str) { // Create an array of size 256 and count of // every character in it int[] count = new int[NO_OF_CHARS]; /* Count array with frequency of characters */ int i; for (i = 0; i < str.length(); i++) if(str.charAt(i)!=' ') count[(int)str.charAt(i)]++; int n = i; // Print characters having count more than 0 for (i = 0; i < n; i++) if (count[(int)str.charAt(i)] == 1) System.out.print(str.charAt(i)); } /* Driver program*/ public static void main(String args[]) { String str = "GeeksforGeeks"; printDistinct(str); }}// This code is contributed by Sumit Ghosh # Python3 program to print distinct# characters of a string.NO_OF_CHARS = 256 # Print duplicates present in the# passed stringdef printDistinct(str): # Create an array of size 256 and # count of every character in it count = [0] * NO_OF_CHARS # Count array with frequency of # characters for i in range (len(str)): if(str[i] != ' '): count[ord(str[i])] += 1 n = i # Print characters having count # more than 0 for i in range(n): if (count[ord(str[i])] == 1): print (str[i], end = "") # Driver Codeif __name__ == "__main__": str = "GeeksforGeeks" printDistinct(str) # This code is contributed by ita_c // C# program to print distinct characters// of a string.using System; public class GFG { static int NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ static void printDistinct(String str) { // Create an array of size 256 and // count of every character in it int[] count = new int[NO_OF_CHARS]; /* Count array with frequency of characters */ int i; for (i = 0; i < str.Length; i++) if(str[i]!=' ') count[(int)str[i]]++; int n = i; // Print characters having count // more than 0 for (i = 0; i < n; i++) if (count[(int)str[i]] == 1) Console.Write(str[i]); } /* Driver program*/ public static void Main() { String str = "GeeksforGeeks"; printDistinct(str); }} // This code is contributed by parashar. <script>// Javascript program to print distinct characters of a// string. let NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ function printDistinct(str) { // Create an array of size 256 and count of // every character in it let count = new Array(NO_OF_CHARS); for(let i=0;i<NO_OF_CHARS;i++) { count[i]=0; } /* Count array with frequency of characters */ let i; for (i = 0; i < str.length; i++) if(str[i]!=' ') count[str[i].charCodeAt(0)]++; let n = i; // Print characters having count more than 0 for (i = 0; i < n; i++) if (count[str[i].charCodeAt(0)] == 1) document.write(str[i]); } /* Driver program*/ let str = "GeeksforGeeks"; printDistinct(str); // This code is contributed by rag2127</script> Output: for Time Complexity: O(n) Auxiliary Space: O(n) Method 3 (O(n) and requires one traversal) The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored using 8 bits). Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = nNow index[] has indexes of all distinct characters. Sort indexes and print characters using it. Note that this step takes O(1) time assuming number of characters are fixed (typically 256) Initialize all values in count[] as 0 and all values in index[] as n where n is length of string. Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = n Increment count[x]. If count[x] is 1, then store index of x in index[x], i.e., index[x] = i If count[x] is 2, then remove x from index[], i.e., index[x] = n Now index[] has indexes of all distinct characters. Sort indexes and print characters using it. Note that this step takes O(1) time assuming number of characters are fixed (typically 256) Below is the implementation of above idea. C++ Java Python C# Javascript // C++ program to find all distinct characters// in a string#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 256; // Function to print distinct characters in// given string str[]void printDistinct(string str){ int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int count[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // more than once, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int index[MAX_CHAR]; // Initialize counts of all characters and indexes // of distinct characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str[i]; ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below operations // take constant time. sort(index, index+MAX_CHAR); for (int i=0; i<MAX_CHAR && index[i] != n; i++) cout << str[index[i]];} // Driver codeint main(){ string str = "GeeksforGeeks"; printDistinct(str); return 0;} // Java program to print distinct characters of// a string.import java.util.Arrays; public class GFG { static final int MAX_CHAR = 256; // Function to print distinct characters in // given string str[] static void printDistinct(String str) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int[] count = new int[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // more than once, then it is going to store a // value (for example, length of string) that // cannot be a valid index in str[] int[] index = new int[MAX_CHAR]; // Initialize counts of all characters and // indexes of distinct characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any // index in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment // its count char x = str.charAt(i); ++count[x]; // If this is first occurrence, then set // value in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove it // from index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below // operations take constant time. Arrays.sort(index); for (int i = 0; i < MAX_CHAR && index[i] != n; i++) System.out.print(str.charAt(index[i])); } // Driver code public static void main(String args[]) { String str = "GeeksforGeeks"; printDistinct(str); }}// This code is contributed by Sumit Ghosh # Python3 program to find all distinct characters# in a String MAX_CHAR = 256 # Function to print distinct characters in# given Str[]def printDistinct(Str): n = len(Str) # count[x] is going to store count of # character 'x' in Str. If x is not present, # then it is going to store 0. count = [0 for i in range(MAX_CHAR)] # index[x] is going to store index of character # 'x' in Str. If x is not present or x is # more than once, then it is going to store a value # (for example, length of String) that cannot be # a valid index in Str[] index = [n for i in range(MAX_CHAR)] # Traverse the input String for i in range(n): # Find current character and increment its # count x = ord(Str[i]) count[x] += 1 # If this is first occurrence, then set value # in index as index of it. if (count[x] == 1 and x !=' '): index[x] = i # If character repeats, then remove it from # index[] if (count[x] == 2): index[x] = n # Since size of index is constant, below operations # take constant time. index=sorted(index) for i in range(MAX_CHAR): if index[i] == n: break print(Str[index[i]],end="") # Driver code Str = "GeeksforGeeks"printDistinct(Str) # This code is contributed by mohit kumar 29 // C# program to print distinct characters of// a string.using System; public class GFG { static int MAX_CHAR = 256; // Function to print distinct characters in // given string str[] static void printDistinct(string str) { int n = str.Length; // count[x] is going to store count of // character 'x' in str. If x is not // present, then it is going to store 0. int []count = new int[MAX_CHAR]; // index[x] is going to store index of // character 'x' in str. If x is not // present or x is more than once, then // it is going to store a value (for // example, length of string) that // cannot be a valid index in str[] int []index = new int[MAX_CHAR]; // Initialize counts of all characters // and indexes of distinct characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; // A value more than any index // in str[] index[i] = n; } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and // increment its count char x = str[i]; ++count[x]; // If this is first occurrence, then // set value in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove // it from index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below // operations take constant time. Array.Sort(index); for (int i = 0; i < MAX_CHAR && index[i] != n; i++) Console.Write(str[index[i]]); } // Driver code public static void Main() { string str = "GeeksforGeeks"; printDistinct(str); }} // This code is contributed by nitin mittal. <script>// Javascript program to print distinct characters of// a string. let MAX_CHAR = 256; // Function to print distinct characters in // given string str[] function printDistinct(str) { let n = str.length; // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. let count = new Array(MAX_CHAR); // index[x] is going to store index of character // 'x' in str. If x is not present or x is // more than once, then it is going to store a // value (for example, length of string) that // cannot be a valid index in str[] let index = new Array(MAX_CHAR); // Initialize counts of all characters and // indexes of distinct characters. for (let i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any // index in str[] } // Traverse the input string for (let i = 0; i < n; i++) { // Find current character and increment // its count let x = str[i].charCodeAt(0); ++count[x]; // If this is first occurrence, then set // value in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove it // from index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below // operations take constant time. index.sort(function(a,b){return a-b}); for (let i = 0; i < MAX_CHAR && index[i] != n; i++) document.write(str[index[i]]); } // Driver code let str = "GeeksforGeeks"; printDistinct(str); // This code is contributed by avanitrachhadiya2155</script> for Time Complexity: O(n) Auxiliary Space: O(n) This article is contributed by Aarti_Rathi and Afzal Ansari. 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. parashar nitin mittal ukasp mohit kumar 29 rag2127 avanitrachhadiya2155 geeky_bhaskar pulamolusaimohan umadevi9616 GauravRajput1 kapoorsagar226 simranarora5sos sachinvinod1904 Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jun, 2022" }, { "code": null, "e": 378, "s": 52, "text": "Given a string, find the all distinct (or non-repeating characters) in it. For example, if the input string is “Geeks for Geeks”, then output should be ‘for’ and if input string is “Geeks Quiz”, then output should be ‘GksQuiz’.The distinct characters should be printed in same order as they appear in input string.Examples: " }, { "code": null, "e": 453, "s": 378, "text": "Input : Geeks for Geeks\nOutput : for\n\nInput : Hello Geeks\nOutput : HoGks" }, { "code": null, "e": 729, "s": 455, "text": "Method 1 (Simple : O(n2)) A Simple Solution is to run two loops. Start traversing from left side. For every character, check if it repeats or not. If the character doesn’t repeat, increment count of non-repeating characters. When the count becomes 1, return each character." }, { "code": null, "e": 733, "s": 729, "text": "C++" }, { "code": null, "e": 738, "s": 733, "text": "Java" }, { "code": null, "e": 746, "s": 738, "text": "Python3" }, { "code": null, "e": 749, "s": 746, "text": "C#" }, { "code": null, "e": 760, "s": 749, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ string str = \"GeeksforGeeks\"; for (int i = 0; i < str.size(); i++) { int flag = 0; for (int j = 0; j < str.size(); j++) { // checking if two characters are equal if (str[i] == str[j] and i != j) { flag = 1; break; } } if (flag == 0) cout << str[i]; } return 0;} // This code is contributed by umadevi9616", "e": 1259, "s": 760, "text": null }, { "code": "import java.util.*; class GFG{ public static void main(String[] args){ String str = \"GeeksforGeeks\"; for (int i = 0; i < str.length(); i++) { int flag = 0; for (int j = 0; j < str.length(); j++) { // checking if two characters are equal if (str.charAt(i) == str.charAt(j) && i != j) { flag = 1; break; } } if (flag == 0) System.out.print(str.charAt(i)); }}} // This code is contributed by gauravrajput1", "e": 1795, "s": 1259, "text": null }, { "code": "string=\"GeeksforGeeks\" for i in range(0,len(string)): flag=0 for j in range(0,len(string)): #checking if two characters are equal if(string[i]==string[j] and i!=j): flag=1 break if(flag==0): print(string[i],end=\"\")", "e": 2062, "s": 1795, "text": null }, { "code": "using System; public class GFG{ public static void Main(String[] args){ String str = \"GeeksforGeeks\"; for (int i = 0; i < str.Length; i++) { int flag = 0; for (int j = 0; j < str.Length; j++) { // checking if two characters are equal if (str[i] == str[j] && i != j) { flag = 1; break; } } if (flag == 0) Console.Write(str[i]); }}} // This code is contributed by gauravrajput1", "e": 2571, "s": 2062, "text": null }, { "code": "<script> var str = \"GeeksforGeeks\"; for (var i = 0; i < str.length; i++) { var flag = 0; for (j = 0; j < str.length; j++) { // checking if two characters are equal if (str.charAt(i) == str.charAt(j) && i != j) { flag = 1; break; } } if (flag == 0) document.write(str.charAt(i)); } // This code is contributed by gauravrajput1</script>", "e": 3070, "s": 2571, "text": null }, { "code": null, "e": 3074, "s": 3070, "text": "for" }, { "code": null, "e": 3120, "s": 3074, "text": "Time Complexity: O(n2) Auxiliary Space: O(1) " }, { "code": null, "e": 3177, "s": 3120, "text": "Method 2 (Efficient but requires two traversals: O(n)) " }, { "code": null, "e": 3520, "s": 3177, "text": "Create an array count[] to store counts of characters.Traverse the input string str and do following for every character x = str[i]. Increment count[x].Traverse the input string again and do following for every character str[i]If count[x] is 1, then print the unique characterIf count[x] is greater than 1, then ignore the repeated character." }, { "code": null, "e": 3575, "s": 3520, "text": "Create an array count[] to store counts of characters." }, { "code": null, "e": 3674, "s": 3575, "text": "Traverse the input string str and do following for every character x = str[i]. Increment count[x]." }, { "code": null, "e": 3865, "s": 3674, "text": "Traverse the input string again and do following for every character str[i]If count[x] is 1, then print the unique characterIf count[x] is greater than 1, then ignore the repeated character." }, { "code": null, "e": 3981, "s": 3865, "text": "If count[x] is 1, then print the unique characterIf count[x] is greater than 1, then ignore the repeated character." }, { "code": null, "e": 4031, "s": 3981, "text": "If count[x] is 1, then print the unique character" }, { "code": null, "e": 4098, "s": 4031, "text": "If count[x] is greater than 1, then ignore the repeated character." }, { "code": null, "e": 4143, "s": 4098, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 4147, "s": 4143, "text": "C++" }, { "code": null, "e": 4152, "s": 4147, "text": "Java" }, { "code": null, "e": 4160, "s": 4152, "text": "Python3" }, { "code": null, "e": 4163, "s": 4160, "text": "C#" }, { "code": null, "e": 4174, "s": 4163, "text": "Javascript" }, { "code": "// C++ program to print distinct characters of a// string.# include <iostream>using namespace std;# define NO_OF_CHARS 256 /* Print duplicates present in the passed string */void printDistinct(char *str){ // Create an array of size 256 and count of // every character in it int count[NO_OF_CHARS]; /* Count array with frequency of characters */ int i; for (i = 0; *(str+i); i++) if(*(str+i)!=' ') count[*(str+i)]++; int n = i; // Print characters having count more than 0 for (i = 0; i < n; i++) if (count[*(str+i)] == 1) cout<< str[i];} /* Driver program*/int main(){ char str[] = \"GeeksforGeeks\"; printDistinct(str); return 0;}", "e": 4878, "s": 4174, "text": null }, { "code": "// Java program to print distinct characters of a// string.public class GFG { static final int NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ static void printDistinct(String str) { // Create an array of size 256 and count of // every character in it int[] count = new int[NO_OF_CHARS]; /* Count array with frequency of characters */ int i; for (i = 0; i < str.length(); i++) if(str.charAt(i)!=' ') count[(int)str.charAt(i)]++; int n = i; // Print characters having count more than 0 for (i = 0; i < n; i++) if (count[(int)str.charAt(i)] == 1) System.out.print(str.charAt(i)); } /* Driver program*/ public static void main(String args[]) { String str = \"GeeksforGeeks\"; printDistinct(str); }}// This code is contributed by Sumit Ghosh", "e": 5817, "s": 4878, "text": null }, { "code": "# Python3 program to print distinct# characters of a string.NO_OF_CHARS = 256 # Print duplicates present in the# passed stringdef printDistinct(str): # Create an array of size 256 and # count of every character in it count = [0] * NO_OF_CHARS # Count array with frequency of # characters for i in range (len(str)): if(str[i] != ' '): count[ord(str[i])] += 1 n = i # Print characters having count # more than 0 for i in range(n): if (count[ord(str[i])] == 1): print (str[i], end = \"\") # Driver Codeif __name__ == \"__main__\": str = \"GeeksforGeeks\" printDistinct(str) # This code is contributed by ita_c", "e": 6498, "s": 5817, "text": null }, { "code": "// C# program to print distinct characters// of a string.using System; public class GFG { static int NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ static void printDistinct(String str) { // Create an array of size 256 and // count of every character in it int[] count = new int[NO_OF_CHARS]; /* Count array with frequency of characters */ int i; for (i = 0; i < str.Length; i++) if(str[i]!=' ') count[(int)str[i]]++; int n = i; // Print characters having count // more than 0 for (i = 0; i < n; i++) if (count[(int)str[i]] == 1) Console.Write(str[i]); } /* Driver program*/ public static void Main() { String str = \"GeeksforGeeks\"; printDistinct(str); }} // This code is contributed by parashar.", "e": 7461, "s": 6498, "text": null }, { "code": "<script>// Javascript program to print distinct characters of a// string. let NO_OF_CHARS = 256; /* Print duplicates present in the passed string */ function printDistinct(str) { // Create an array of size 256 and count of // every character in it let count = new Array(NO_OF_CHARS); for(let i=0;i<NO_OF_CHARS;i++) { count[i]=0; } /* Count array with frequency of characters */ let i; for (i = 0; i < str.length; i++) if(str[i]!=' ') count[str[i].charCodeAt(0)]++; let n = i; // Print characters having count more than 0 for (i = 0; i < n; i++) if (count[str[i].charCodeAt(0)] == 1) document.write(str[i]); } /* Driver program*/ let str = \"GeeksforGeeks\"; printDistinct(str); // This code is contributed by rag2127</script>", "e": 8392, "s": 7461, "text": null }, { "code": null, "e": 8402, "s": 8392, "text": "Output: " }, { "code": null, "e": 8406, "s": 8402, "text": "for" }, { "code": null, "e": 8451, "s": 8406, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 8600, "s": 8451, "text": "Method 3 (O(n) and requires one traversal) The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored using 8 bits). " }, { "code": null, "e": 9118, "s": 8600, "text": "Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = nNow index[] has indexes of all distinct characters. Sort indexes and print characters using it. Note that this step takes O(1) time assuming number of characters are fixed (typically 256)" }, { "code": null, "e": 9216, "s": 9118, "text": "Initialize all values in count[] as 0 and all values in index[] as n where n is length of string." }, { "code": null, "e": 9450, "s": 9216, "text": "Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = n" }, { "code": null, "e": 9470, "s": 9450, "text": "Increment count[x]." }, { "code": null, "e": 9542, "s": 9470, "text": "If count[x] is 1, then store index of x in index[x], i.e., index[x] = i" }, { "code": null, "e": 9607, "s": 9542, "text": "If count[x] is 2, then remove x from index[], i.e., index[x] = n" }, { "code": null, "e": 9795, "s": 9607, "text": "Now index[] has indexes of all distinct characters. Sort indexes and print characters using it. Note that this step takes O(1) time assuming number of characters are fixed (typically 256)" }, { "code": null, "e": 9840, "s": 9795, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 9844, "s": 9840, "text": "C++" }, { "code": null, "e": 9849, "s": 9844, "text": "Java" }, { "code": null, "e": 9856, "s": 9849, "text": "Python" }, { "code": null, "e": 9859, "s": 9856, "text": "C#" }, { "code": null, "e": 9870, "s": 9859, "text": "Javascript" }, { "code": "// C++ program to find all distinct characters// in a string#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 256; // Function to print distinct characters in// given string str[]void printDistinct(string str){ int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int count[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // more than once, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int index[MAX_CHAR]; // Initialize counts of all characters and indexes // of distinct characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str[i]; ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below operations // take constant time. sort(index, index+MAX_CHAR); for (int i=0; i<MAX_CHAR && index[i] != n; i++) cout << str[index[i]];} // Driver codeint main(){ string str = \"GeeksforGeeks\"; printDistinct(str); return 0;}", "e": 11522, "s": 9870, "text": null }, { "code": "// Java program to print distinct characters of// a string.import java.util.Arrays; public class GFG { static final int MAX_CHAR = 256; // Function to print distinct characters in // given string str[] static void printDistinct(String str) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int[] count = new int[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // more than once, then it is going to store a // value (for example, length of string) that // cannot be a valid index in str[] int[] index = new int[MAX_CHAR]; // Initialize counts of all characters and // indexes of distinct characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any // index in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment // its count char x = str.charAt(i); ++count[x]; // If this is first occurrence, then set // value in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove it // from index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below // operations take constant time. Arrays.sort(index); for (int i = 0; i < MAX_CHAR && index[i] != n; i++) System.out.print(str.charAt(index[i])); } // Driver code public static void main(String args[]) { String str = \"GeeksforGeeks\"; printDistinct(str); }}// This code is contributed by Sumit Ghosh", "e": 13603, "s": 11522, "text": null }, { "code": "# Python3 program to find all distinct characters# in a String MAX_CHAR = 256 # Function to print distinct characters in# given Str[]def printDistinct(Str): n = len(Str) # count[x] is going to store count of # character 'x' in Str. If x is not present, # then it is going to store 0. count = [0 for i in range(MAX_CHAR)] # index[x] is going to store index of character # 'x' in Str. If x is not present or x is # more than once, then it is going to store a value # (for example, length of String) that cannot be # a valid index in Str[] index = [n for i in range(MAX_CHAR)] # Traverse the input String for i in range(n): # Find current character and increment its # count x = ord(Str[i]) count[x] += 1 # If this is first occurrence, then set value # in index as index of it. if (count[x] == 1 and x !=' '): index[x] = i # If character repeats, then remove it from # index[] if (count[x] == 2): index[x] = n # Since size of index is constant, below operations # take constant time. index=sorted(index) for i in range(MAX_CHAR): if index[i] == n: break print(Str[index[i]],end=\"\") # Driver code Str = \"GeeksforGeeks\"printDistinct(Str) # This code is contributed by mohit kumar 29", "e": 14968, "s": 13603, "text": null }, { "code": "// C# program to print distinct characters of// a string.using System; public class GFG { static int MAX_CHAR = 256; // Function to print distinct characters in // given string str[] static void printDistinct(string str) { int n = str.Length; // count[x] is going to store count of // character 'x' in str. If x is not // present, then it is going to store 0. int []count = new int[MAX_CHAR]; // index[x] is going to store index of // character 'x' in str. If x is not // present or x is more than once, then // it is going to store a value (for // example, length of string) that // cannot be a valid index in str[] int []index = new int[MAX_CHAR]; // Initialize counts of all characters // and indexes of distinct characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; // A value more than any index // in str[] index[i] = n; } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and // increment its count char x = str[i]; ++count[x]; // If this is first occurrence, then // set value in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove // it from index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below // operations take constant time. Array.Sort(index); for (int i = 0; i < MAX_CHAR && index[i] != n; i++) Console.Write(str[index[i]]); } // Driver code public static void Main() { string str = \"GeeksforGeeks\"; printDistinct(str); }} // This code is contributed by nitin mittal.", "e": 17013, "s": 14968, "text": null }, { "code": "<script>// Javascript program to print distinct characters of// a string. let MAX_CHAR = 256; // Function to print distinct characters in // given string str[] function printDistinct(str) { let n = str.length; // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. let count = new Array(MAX_CHAR); // index[x] is going to store index of character // 'x' in str. If x is not present or x is // more than once, then it is going to store a // value (for example, length of string) that // cannot be a valid index in str[] let index = new Array(MAX_CHAR); // Initialize counts of all characters and // indexes of distinct characters. for (let i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any // index in str[] } // Traverse the input string for (let i = 0; i < n; i++) { // Find current character and increment // its count let x = str[i].charCodeAt(0); ++count[x]; // If this is first occurrence, then set // value in index as index of it. if (count[x] == 1 && x !=' ') index[x] = i; // If character repeats, then remove it // from index[] if (count[x] == 2) index[x] = n; } // Since size of index is constant, below // operations take constant time. index.sort(function(a,b){return a-b}); for (let i = 0; i < MAX_CHAR && index[i] != n; i++) document.write(str[index[i]]); } // Driver code let str = \"GeeksforGeeks\"; printDistinct(str); // This code is contributed by avanitrachhadiya2155</script>", "e": 19037, "s": 17013, "text": null }, { "code": null, "e": 19041, "s": 19037, "text": "for" }, { "code": null, "e": 19086, "s": 19041, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 19528, "s": 19086, "text": "This article is contributed by Aarti_Rathi and Afzal Ansari. 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. " }, { "code": null, "e": 19537, "s": 19528, "text": "parashar" }, { "code": null, "e": 19550, "s": 19537, "text": "nitin mittal" }, { "code": null, "e": 19556, "s": 19550, "text": "ukasp" }, { "code": null, "e": 19571, "s": 19556, "text": "mohit kumar 29" }, { "code": null, "e": 19579, "s": 19571, "text": "rag2127" }, { "code": null, "e": 19600, "s": 19579, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19614, "s": 19600, "text": "geeky_bhaskar" }, { "code": null, "e": 19631, "s": 19614, "text": "pulamolusaimohan" }, { "code": null, "e": 19643, "s": 19631, "text": "umadevi9616" }, { "code": null, "e": 19657, "s": 19643, "text": "GauravRajput1" }, { "code": null, "e": 19672, "s": 19657, "text": "kapoorsagar226" }, { "code": null, "e": 19688, "s": 19672, "text": "simranarora5sos" }, { "code": null, "e": 19704, "s": 19688, "text": "sachinvinod1904" }, { "code": null, "e": 19724, "s": 19704, "text": "Dynamic Programming" }, { "code": null, "e": 19732, "s": 19724, "text": "Strings" }, { "code": null, "e": 19740, "s": 19732, "text": "Strings" }, { "code": null, "e": 19760, "s": 19740, "text": "Dynamic Programming" } ]
Data Hiding in Python
28 Oct, 2021 In this article, we will discuss data hiding in Python, starting from data hiding in general to data hiding in Python, along with the advantages and disadvantages of using data hiding in python. Data hiding is a concept which underlines the hiding of data or information from the user. It is one of the key aspects of Object-Oriented programming strategies. It includes object details such as data members, internal work. Data hiding excludes full data entry to class members and defends object integrity by preventing unintended changes. Data hiding also minimizes system complexity for increase robustness by limiting interdependencies between software requirements. Data hiding is also known as information hiding. In class, if we declare the data members as private so that no other class can access the data members, then it is a process of hiding data. Data Hiding in Python: The Python document introduces Data Hiding as isolating the user from a part of program implementation. Some objects in the module are kept internal, unseen, and unreachable to the user. Modules in the program are easy enough to understand how to use the application, but the client cannot know how the application functions. Thus, data hiding imparts security, along with discarding dependency. Data hiding in Python is the technique to defend access to specific users in the application. Python is applied in every technical area and has a user-friendly syntax and vast libraries. Data hiding in Python is performed using the __ double underscore before done prefix. This makes the class members non-public and isolated from the other classes. Example: Python3 class Solution: __privateCounter = 0 def sum(self): self.__privateCounter += 1 print(self.__privateCounter) count = Solution()count.sum()count.sum() # Here it will show error because it unable# to access private memberprint(count.__privateCount) Output: Traceback (most recent call last): File "/home/db01b918da68a3747044d44675be8872.py", line 11, in <module> print(count.__privateCount) AttributeError: 'Solution' object has no attribute '__privateCount' To rectify the error, we can access the private member through the class name : Python3 class Solution: __privateCounter = 0 def sum(self): self.__privateCounter += 1 print(self.__privateCounter) count = Solution()count.sum()count.sum() # Here we have accessed the private data# member through class name.print(count._Solution__privateCounter) Output: 1 2 2 It helps to prevent damage or misuse of volatile data by hiding it from the public.The class objects are disconnected from the irrelevant data.It isolates objects as the basic concept of OOP.It increases the security against hackers that are unable to access important data. It helps to prevent damage or misuse of volatile data by hiding it from the public. The class objects are disconnected from the irrelevant data. It isolates objects as the basic concept of OOP. It increases the security against hackers that are unable to access important data. It enables programmers to write lengthy code to hide important data from common clients.The linkage between the visible and invisible data makes the objects work faster, but data hiding prevents this linkage. It enables programmers to write lengthy code to hide important data from common clients. The linkage between the visible and invisible data makes the objects work faster, but data hiding prevents this linkage. sooda367 Python-OOP python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 223, "s": 28, "text": "In this article, we will discuss data hiding in Python, starting from data hiding in general to data hiding in Python, along with the advantages and disadvantages of using data hiding in python." }, { "code": null, "e": 887, "s": 223, "text": "Data hiding is a concept which underlines the hiding of data or information from the user. It is one of the key aspects of Object-Oriented programming strategies. It includes object details such as data members, internal work. Data hiding excludes full data entry to class members and defends object integrity by preventing unintended changes. Data hiding also minimizes system complexity for increase robustness by limiting interdependencies between software requirements. Data hiding is also known as information hiding. In class, if we declare the data members as private so that no other class can access the data members, then it is a process of hiding data." }, { "code": null, "e": 910, "s": 887, "text": "Data Hiding in Python:" }, { "code": null, "e": 1656, "s": 910, "text": "The Python document introduces Data Hiding as isolating the user from a part of program implementation. Some objects in the module are kept internal, unseen, and unreachable to the user. Modules in the program are easy enough to understand how to use the application, but the client cannot know how the application functions. Thus, data hiding imparts security, along with discarding dependency. Data hiding in Python is the technique to defend access to specific users in the application. Python is applied in every technical area and has a user-friendly syntax and vast libraries. Data hiding in Python is performed using the __ double underscore before done prefix. This makes the class members non-public and isolated from the other classes." }, { "code": null, "e": 1665, "s": 1656, "text": "Example:" }, { "code": null, "e": 1673, "s": 1665, "text": "Python3" }, { "code": "class Solution: __privateCounter = 0 def sum(self): self.__privateCounter += 1 print(self.__privateCounter) count = Solution()count.sum()count.sum() # Here it will show error because it unable# to access private memberprint(count.__privateCount)", "e": 1941, "s": 1673, "text": null }, { "code": null, "e": 1949, "s": 1941, "text": "Output:" }, { "code": null, "e": 2158, "s": 1949, "text": "Traceback (most recent call last):\n File \"/home/db01b918da68a3747044d44675be8872.py\", line 11, in <module>\n print(count.__privateCount) \nAttributeError: 'Solution' object has no attribute '__privateCount'" }, { "code": null, "e": 2238, "s": 2158, "text": "To rectify the error, we can access the private member through the class name :" }, { "code": null, "e": 2246, "s": 2238, "text": "Python3" }, { "code": "class Solution: __privateCounter = 0 def sum(self): self.__privateCounter += 1 print(self.__privateCounter) count = Solution()count.sum()count.sum() # Here we have accessed the private data# member through class name.print(count._Solution__privateCounter)", "e": 2524, "s": 2246, "text": null }, { "code": null, "e": 2532, "s": 2524, "text": "Output:" }, { "code": null, "e": 2538, "s": 2532, "text": "1\n2\n2" }, { "code": null, "e": 2813, "s": 2538, "text": "It helps to prevent damage or misuse of volatile data by hiding it from the public.The class objects are disconnected from the irrelevant data.It isolates objects as the basic concept of OOP.It increases the security against hackers that are unable to access important data." }, { "code": null, "e": 2897, "s": 2813, "text": "It helps to prevent damage or misuse of volatile data by hiding it from the public." }, { "code": null, "e": 2958, "s": 2897, "text": "The class objects are disconnected from the irrelevant data." }, { "code": null, "e": 3007, "s": 2958, "text": "It isolates objects as the basic concept of OOP." }, { "code": null, "e": 3091, "s": 3007, "text": "It increases the security against hackers that are unable to access important data." }, { "code": null, "e": 3300, "s": 3091, "text": "It enables programmers to write lengthy code to hide important data from common clients.The linkage between the visible and invisible data makes the objects work faster, but data hiding prevents this linkage." }, { "code": null, "e": 3389, "s": 3300, "text": "It enables programmers to write lengthy code to hide important data from common clients." }, { "code": null, "e": 3510, "s": 3389, "text": "The linkage between the visible and invisible data makes the objects work faster, but data hiding prevents this linkage." }, { "code": null, "e": 3519, "s": 3510, "text": "sooda367" }, { "code": null, "e": 3530, "s": 3519, "text": "Python-OOP" }, { "code": null, "e": 3550, "s": 3530, "text": "python-oop-concepts" }, { "code": null, "e": 3557, "s": 3550, "text": "Python" } ]
Python – Surrounding elements to K
12 Nov, 2020 Given Matrix, from each row, get surrounding elements of K, if present. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 6 Output : [[7, 3], [5], [], [1]] Explanation : All elements surrounded by 6 are extracted. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 1 Output : [[], [], [2], [6, 2]] Explanation : All elements surrounded by 1 are removed. Method #1: Using index() + loop + try/except In this, we check for the index of elements using index(), and then get the required surrounding elements by accessing next and previous elements. If the element is not present, an empty list is returned. Python3 # Python3 code to demonstrate working of # Surrounding elements to K# Using index() + loop + try/except # initializing listtest_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 6 res = []for sub in test_list: # getting index try : idx = sub.index(K) except Exception as e : res.append([]) continue # appending Surrounding elements if idx != 0 and idx != len(sub) - 1: res.append([sub[idx - 1], sub[idx + 1]]) elif idx == 0: res.append([sub[idx + 1]]) else : res.append([sub[idx - 1]]) # printing result print("The Surrounding elements : " + str(res)) Output: The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]The Surrounding elements : [[7, 3], [5], [], [1]] Method #2 : Using index() + in operator + loop In this, we check if the element is present in a row before application of index(), to avoid using try/except block. Rest all functionalities are the same as the above method. Python3 # Python3 code to demonstrate working of# Surrounding elements to K# Using index() + in operator + loop # initializing listtest_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 6 res = []for sub in test_list: # getting index # checking for element presence in row if K in sub: idx = sub.index(K) else: res.append([]) continue # appending Surrounding elements if idx != 0 and idx != len(sub) - 1: res.append([sub[idx - 1], sub[idx + 1]]) elif idx == 0: res.append([sub[idx + 1]]) else: res.append([sub[idx - 1]]) # printing resultprint("The Surrounding elements : " + str(res)) Output: The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]The Surrounding elements : [[7, 3], [5], [], [1]] Python list-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": "\n12 Nov, 2020" }, { "code": null, "e": 100, "s": 28, "text": "Given Matrix, from each row, get surrounding elements of K, if present." }, { "code": null, "e": 259, "s": 100, "text": "Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 6 Output : [[7, 3], [5], [], [1]] Explanation : All elements surrounded by 6 are extracted." }, { "code": null, "e": 417, "s": 259, "text": "Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 1 Output : [[], [], [2], [6, 2]] Explanation : All elements surrounded by 1 are removed. " }, { "code": null, "e": 462, "s": 417, "text": "Method #1: Using index() + loop + try/except" }, { "code": null, "e": 667, "s": 462, "text": "In this, we check for the index of elements using index(), and then get the required surrounding elements by accessing next and previous elements. If the element is not present, an empty list is returned." }, { "code": null, "e": 675, "s": 667, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Surrounding elements to K# Using index() + loop + try/except # initializing listtest_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 6 res = []for sub in test_list: # getting index try : idx = sub.index(K) except Exception as e : res.append([]) continue # appending Surrounding elements if idx != 0 and idx != len(sub) - 1: res.append([sub[idx - 1], sub[idx + 1]]) elif idx == 0: res.append([sub[idx + 1]]) else : res.append([sub[idx - 1]]) # printing result print(\"The Surrounding elements : \" + str(res))", "e": 1395, "s": 675, "text": null }, { "code": null, "e": 1403, "s": 1395, "text": "Output:" }, { "code": null, "e": 1517, "s": 1403, "text": "The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]The Surrounding elements : [[7, 3], [5], [], [1]]" }, { "code": null, "e": 1564, "s": 1517, "text": "Method #2 : Using index() + in operator + loop" }, { "code": null, "e": 1740, "s": 1564, "text": "In this, we check if the element is present in a row before application of index(), to avoid using try/except block. Rest all functionalities are the same as the above method." }, { "code": null, "e": 1748, "s": 1740, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Surrounding elements to K# Using index() + in operator + loop # initializing listtest_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 6 res = []for sub in test_list: # getting index # checking for element presence in row if K in sub: idx = sub.index(K) else: res.append([]) continue # appending Surrounding elements if idx != 0 and idx != len(sub) - 1: res.append([sub[idx - 1], sub[idx + 1]]) elif idx == 0: res.append([sub[idx + 1]]) else: res.append([sub[idx - 1]]) # printing resultprint(\"The Surrounding elements : \" + str(res))", "e": 2494, "s": 1748, "text": null }, { "code": null, "e": 2502, "s": 2494, "text": "Output:" }, { "code": null, "e": 2616, "s": 2502, "text": "The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]The Surrounding elements : [[7, 3], [5], [], [1]]" }, { "code": null, "e": 2637, "s": 2616, "text": "Python list-programs" }, { "code": null, "e": 2644, "s": 2637, "text": "Python" }, { "code": null, "e": 2660, "s": 2644, "text": "Python Programs" } ]
Debugging decorators in Python
21 Aug, 2020 Decorators in Python are really a very powerful feature. If you are a web developer and you have used the Django framework or even some other development frameworks you would have already come across decorators. For an overview decorators are wrapper functions that wrap an existing function or a method and modify its features. Let’s take a short example. Consider that you have a speak function that returns a neutral message Python3 def speak(): """Returns a neutral message""" return "Hi, Geeks!" # printing the outputprint(speak()) Output: Hi, Geeks! Suppose that you need to modify the function to return a message in a happy tone. So let’s create a decorator for this. Python3 # decoratordef make_geek_happy(func): def wrapper(): neutral_message = func() happy_message = neutral_message + " You are happy!" return happy_message return wrapper #using the decorator @make_geek_happydef speak(): """Returns a neutral message""" return "Hi, Geeks!" print(speak()) Output: Hi, Geeks! You are happy! In this way, the decorators can also be used to modify different functions and make them more useful. However, there are some drawbacks to this process. When we wrap the original function in a decorator the metadata of the original function gets lost. Consider the below program but this time we use the decorator in another way just to make you understand. If you try to access any of the metadata of the positive_message function it actually returns the metadata of the wrapper inside the decorator. Python3 # decoratordef make_geek_happy(func): def wrapper(): neutral_message = func() happy_message = neutral_message + " You are happy!" return happy_message return wrapper def speak(): """Returns a neutral message""" return "Hi!" # wrapping the function in the decorator# and assigning it to positive_messagepositive_message = make_geek_happy(speak) print(positive_message()) print(speak.__name__) print(speak.__doc__) print(positive_message.__name__)print(positive_message.__doc__) Output: Hi! You are happy! speak Returns a neutral message wrapper None These results make it really very difficult for debugging. But thanks to Python it also has a solution to fix this problem without much effort. We just need to use the functools.wraps() decorator included in the Python standard library. Here’s an example: Python3 # importing the moduleimport functools # decoratordef make_geek_happy(func): @functools.wraps(func) def wrapper(): neutral_message = func() happy_message = neutral_message + " You are happy!" return happy_message return wrapper def speak(): """Returns a neutral message""" return "Hi!" positive_message = make_geek_happy(speak)print(positive_message()) print(speak.__name__) print(speak.__doc__) print(positive_message.__name__)print(positive_message.__doc__) Output: Hi! You are happy! speak Returns a neutral message speak Returns a neutral message Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Aug, 2020" }, { "code": null, "e": 264, "s": 52, "text": "Decorators in Python are really a very powerful feature. If you are a web developer and you have used the Django framework or even some other development frameworks you would have already come across decorators." }, { "code": null, "e": 480, "s": 264, "text": "For an overview decorators are wrapper functions that wrap an existing function or a method and modify its features. Let’s take a short example. Consider that you have a speak function that returns a neutral message" }, { "code": null, "e": 488, "s": 480, "text": "Python3" }, { "code": "def speak(): \"\"\"Returns a neutral message\"\"\" return \"Hi, Geeks!\" # printing the outputprint(speak())", "e": 596, "s": 488, "text": null }, { "code": null, "e": 604, "s": 596, "text": "Output:" }, { "code": null, "e": 616, "s": 604, "text": "Hi, Geeks!\n" }, { "code": null, "e": 736, "s": 616, "text": "Suppose that you need to modify the function to return a message in a happy tone. So let’s create a decorator for this." }, { "code": null, "e": 744, "s": 736, "text": "Python3" }, { "code": "# decoratordef make_geek_happy(func): def wrapper(): neutral_message = func() happy_message = neutral_message + \" You are happy!\" return happy_message return wrapper #using the decorator @make_geek_happydef speak(): \"\"\"Returns a neutral message\"\"\" return \"Hi, Geeks!\" print(speak())", "e": 1062, "s": 744, "text": null }, { "code": null, "e": 1070, "s": 1062, "text": "Output:" }, { "code": null, "e": 1097, "s": 1070, "text": "Hi, Geeks! You are happy!\n" }, { "code": null, "e": 1455, "s": 1097, "text": "In this way, the decorators can also be used to modify different functions and make them more useful. However, there are some drawbacks to this process. When we wrap the original function in a decorator the metadata of the original function gets lost. Consider the below program but this time we use the decorator in another way just to make you understand." }, { "code": null, "e": 1600, "s": 1455, "text": "If you try to access any of the metadata of the positive_message function it actually returns the metadata of the wrapper inside the decorator. " }, { "code": null, "e": 1608, "s": 1600, "text": "Python3" }, { "code": "# decoratordef make_geek_happy(func): def wrapper(): neutral_message = func() happy_message = neutral_message + \" You are happy!\" return happy_message return wrapper def speak(): \"\"\"Returns a neutral message\"\"\" return \"Hi!\" # wrapping the function in the decorator# and assigning it to positive_messagepositive_message = make_geek_happy(speak) print(positive_message()) print(speak.__name__) print(speak.__doc__) print(positive_message.__name__)print(positive_message.__doc__)", "e": 2124, "s": 1608, "text": null }, { "code": null, "e": 2132, "s": 2124, "text": "Output:" }, { "code": null, "e": 2197, "s": 2132, "text": "Hi! You are happy!\nspeak\nReturns a neutral message\nwrapper\nNone\n" }, { "code": null, "e": 2434, "s": 2197, "text": "These results make it really very difficult for debugging. But thanks to Python it also has a solution to fix this problem without much effort. We just need to use the functools.wraps() decorator included in the Python standard library." }, { "code": null, "e": 2453, "s": 2434, "text": "Here’s an example:" }, { "code": null, "e": 2461, "s": 2453, "text": "Python3" }, { "code": "# importing the moduleimport functools # decoratordef make_geek_happy(func): @functools.wraps(func) def wrapper(): neutral_message = func() happy_message = neutral_message + \" You are happy!\" return happy_message return wrapper def speak(): \"\"\"Returns a neutral message\"\"\" return \"Hi!\" positive_message = make_geek_happy(speak)print(positive_message()) print(speak.__name__) print(speak.__doc__) print(positive_message.__name__)print(positive_message.__doc__)", "e": 2961, "s": 2461, "text": null }, { "code": null, "e": 2969, "s": 2961, "text": "Output:" }, { "code": null, "e": 3053, "s": 2969, "text": "Hi! You are happy!\nspeak\nReturns a neutral message\nspeak\nReturns a neutral message\n" }, { "code": null, "e": 3071, "s": 3053, "text": "Python Decorators" }, { "code": null, "e": 3078, "s": 3071, "text": "Python" } ]
MySQL - CAST DECIMAL to INT?
Cast DECIMAL to INT with the help of FLOOR() function. The syntax is as follows − SELECT FLOOR(yourColumnName) from yourTableName where condition; Let us first create a table. The following is the query to create a table. mysql> create table DecimalToIntDemo -> ( -> Amount DECIMAL(3,1) -> ); Query OK, 0 rows affected (0.88 sec) Now you can insert records into the table with the help of insert command. The query is as follows − mysql> insert into DecimalToIntDemo values(12.5); Query OK, 1 row affected (0.23 sec) mysql> insert into DecimalToIntDemo values(50.4); Query OK, 1 row affected (0.18 sec) mysql> insert into DecimalToIntDemo values(48.6); Query OK, 1 row affected (0.10 sec) Display all records with the help of select statement. The query is as follows − mysql> select *from DecimalToIntDemo; Here is the output − +--------+ | Amount | +--------+ | 12.5 | | 50.4 | | 48.6 | +--------+ 3 rows in set (0.00 sec) Apply the above syntax which we discussed in the beginning. The query is as follows − mysql> SELECT FLOOR(Amount) from DecimalToIntDemo -> where Amount > 10; The following is the output that cast decimal to int − +---------------+ | FLOOR(Amount) | +---------------+ | 12 | | 50 | | 48 | +---------------+ 3 rows in set (0.00 sec) Look at the above sample which gives only INT value.
[ { "code": null, "e": 1144, "s": 1062, "text": "Cast DECIMAL to INT with the help of FLOOR() function. The syntax is as follows −" }, { "code": null, "e": 1209, "s": 1144, "text": "SELECT FLOOR(yourColumnName) from yourTableName where condition;" }, { "code": null, "e": 1284, "s": 1209, "text": "Let us first create a table. The following is the query to create a table." }, { "code": null, "e": 1401, "s": 1284, "text": "mysql> create table DecimalToIntDemo\n -> (\n -> Amount DECIMAL(3,1)\n -> );\nQuery OK, 0 rows affected (0.88 sec)" }, { "code": null, "e": 1502, "s": 1401, "text": "Now you can insert records into the table with the help of insert command. The query is as follows −" }, { "code": null, "e": 1760, "s": 1502, "text": "mysql> insert into DecimalToIntDemo values(12.5);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DecimalToIntDemo values(50.4);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DecimalToIntDemo values(48.6);\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1841, "s": 1760, "text": "Display all records with the help of select statement. The query is as follows −" }, { "code": null, "e": 1879, "s": 1841, "text": "mysql> select *from DecimalToIntDemo;" }, { "code": null, "e": 1900, "s": 1879, "text": "Here is the output −" }, { "code": null, "e": 2002, "s": 1900, "text": "+--------+\n| Amount |\n+--------+\n| 12.5 |\n| 50.4 |\n| 48.6 |\n+--------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2088, "s": 2002, "text": "Apply the above syntax which we discussed in the beginning. The query is as follows −" }, { "code": null, "e": 2163, "s": 2088, "text": "mysql> SELECT FLOOR(Amount) from DecimalToIntDemo\n -> where Amount > 10;" }, { "code": null, "e": 2218, "s": 2163, "text": "The following is the output that cast decimal to int −" }, { "code": null, "e": 2369, "s": 2218, "text": "+---------------+\n| FLOOR(Amount) |\n+---------------+\n| 12 |\n| 50 |\n| 48 |\n+---------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2422, "s": 2369, "text": "Look at the above sample which gives only INT value." } ]
Annotator for Object Detection. A tool to generate annotated images for... | by Anuradha Wickramarachchi | Towards Data Science
In computer vision, object detection is an interesting field with numerous application. Like any other supervised machine learning task, we need annotation or labels for this very task as well. However, annotation of images can be a tedious time-consuming task for many of us (lazy ones?). I felt it quite strongly when I was writing my previous article, linked below. towardsdatascience.com So the big question comes; How can we generate annotated images, automatically, with desired backgrounds? Well, the answer is simple, use existing objects and overlay them on some backgrounds! There are several blogs on the internet that would say mostly how to do that. But it was hard for me to find a proper tool that would do everything for me so I can focus on the main problem, Object Detection. So I present, The Object Annotation Maker. What does it do and how does it do them? Well, this article on that very utility. It is rather easy to find images of objects than annotations. This is because capturing object images is easy and less labour. One good source of fruit images is the Fruits 360 dataset in Kaggle. The dataset contains 100x100 images from fruits with labels as to what the fruit is. This step is quite tasks specific. For example, if you were to detect pedestrians in a train station, you are better off with photos from the particular station. Or photos of your room (or a supermarket) if you are locating fruits in the room. This is quite easy to do and requires less effort in doing. You can download the annotator from the following GitHub repository. github.com Running instructions are available in the Readme of the repository. Organize your images as follows; data-Fruits--Banana---img-1.jpg---img-2.jpg--Apple---img-1.jpg---img-2.jpg...-Backgronds--bg-1.jpg--bg-2.jpg--bg-3.jpg The tool can do the following tasks for you; Rescale the images — this is helpful if you want to lower the image size. For example, the most common image size for training is 224x224. So you need to have objects of size roughly 80x80. This option can be set by using the parameter --resize-images 80,80. You can provide both height and width or just height for scaled resizing ( —-resize-images 80). Rescaling the backgrounds — This is similar to the previous step. Usually, background images will be very large. They can be rescaled easily using the parameter --resize-backgrounds 224,224. The number of images per object — This determines the number of images to be generating having a particular object. Use --n-images 10 for example. The number of objects in an image — Currently the tool supports overlaying multiple instances of the same image on the background. For example, 2 apples in the kitchen image. Can be achieved with the parameter --n-objects 2,5. You can give a single value or a range of values for a generation. The program also takes the number of threads and seed as inputs for multi-threading and random generations. The input images can be given as a wild card list. For example, if you were to pick bananas and apple from the Fruit 260 database your command would look like below. I have omitted the above options for clarity. python3 Maker.py -i "fruit260/Training/Banana/*.jpg" "fruit260/Training/Apple/*.jpg" -b "data/Backgrounds/8.jpg" This makes it very easy to select multiple folders. Please note that the images must come from a folder with the label. For example, always have banana images in a folder named Banana. You can have several such folders in different directories. You need to specify an output folder to save the images. For the above dataset, you’ll have the following structure in the output directory you mention. output-tmp (used for temporary data)-images--banana---img-0-banana-1.jpg---img-0-banana-2.jpg--apple---img-0-apple-1.jpg---img-0-apple-1.jpg-annotations--banana---img-0-banana-1.xml---img-0-banana-2.xml--apple---img-0-apple-1.xml---img-0-apple-1.xml The program will automatically generate the VOC format XML for training. Now you can use these images for training your machine learning model. Happy coding!
[ { "code": null, "e": 541, "s": 172, "text": "In computer vision, object detection is an interesting field with numerous application. Like any other supervised machine learning task, we need annotation or labels for this very task as well. However, annotation of images can be a tedious time-consuming task for many of us (lazy ones?). I felt it quite strongly when I was writing my previous article, linked below." }, { "code": null, "e": 564, "s": 541, "text": "towardsdatascience.com" }, { "code": null, "e": 591, "s": 564, "text": "So the big question comes;" }, { "code": null, "e": 670, "s": 591, "text": "How can we generate annotated images, automatically, with desired backgrounds?" }, { "code": null, "e": 966, "s": 670, "text": "Well, the answer is simple, use existing objects and overlay them on some backgrounds! There are several blogs on the internet that would say mostly how to do that. But it was hard for me to find a proper tool that would do everything for me so I can focus on the main problem, Object Detection." }, { "code": null, "e": 1091, "s": 966, "text": "So I present, The Object Annotation Maker. What does it do and how does it do them? Well, this article on that very utility." }, { "code": null, "e": 1287, "s": 1091, "text": "It is rather easy to find images of objects than annotations. This is because capturing object images is easy and less labour. One good source of fruit images is the Fruits 360 dataset in Kaggle." }, { "code": null, "e": 1372, "s": 1287, "text": "The dataset contains 100x100 images from fruits with labels as to what the fruit is." }, { "code": null, "e": 1676, "s": 1372, "text": "This step is quite tasks specific. For example, if you were to detect pedestrians in a train station, you are better off with photos from the particular station. Or photos of your room (or a supermarket) if you are locating fruits in the room. This is quite easy to do and requires less effort in doing." }, { "code": null, "e": 1745, "s": 1676, "text": "You can download the annotator from the following GitHub repository." }, { "code": null, "e": 1756, "s": 1745, "text": "github.com" }, { "code": null, "e": 1824, "s": 1756, "text": "Running instructions are available in the Readme of the repository." }, { "code": null, "e": 1857, "s": 1824, "text": "Organize your images as follows;" }, { "code": null, "e": 1976, "s": 1857, "text": "data-Fruits--Banana---img-1.jpg---img-2.jpg--Apple---img-1.jpg---img-2.jpg...-Backgronds--bg-1.jpg--bg-2.jpg--bg-3.jpg" }, { "code": null, "e": 2021, "s": 1976, "text": "The tool can do the following tasks for you;" }, { "code": null, "e": 2376, "s": 2021, "text": "Rescale the images — this is helpful if you want to lower the image size. For example, the most common image size for training is 224x224. So you need to have objects of size roughly 80x80. This option can be set by using the parameter --resize-images 80,80. You can provide both height and width or just height for scaled resizing ( —-resize-images 80)." }, { "code": null, "e": 2567, "s": 2376, "text": "Rescaling the backgrounds — This is similar to the previous step. Usually, background images will be very large. They can be rescaled easily using the parameter --resize-backgrounds 224,224." }, { "code": null, "e": 2714, "s": 2567, "text": "The number of images per object — This determines the number of images to be generating having a particular object. Use --n-images 10 for example." }, { "code": null, "e": 3008, "s": 2714, "text": "The number of objects in an image — Currently the tool supports overlaying multiple instances of the same image on the background. For example, 2 apples in the kitchen image. Can be achieved with the parameter --n-objects 2,5. You can give a single value or a range of values for a generation." }, { "code": null, "e": 3328, "s": 3008, "text": "The program also takes the number of threads and seed as inputs for multi-threading and random generations. The input images can be given as a wild card list. For example, if you were to pick bananas and apple from the Fruit 260 database your command would look like below. I have omitted the above options for clarity." }, { "code": null, "e": 3441, "s": 3328, "text": "python3 Maker.py -i \"fruit260/Training/Banana/*.jpg\" \"fruit260/Training/Apple/*.jpg\" -b \"data/Backgrounds/8.jpg\"" }, { "code": null, "e": 3493, "s": 3441, "text": "This makes it very easy to select multiple folders." }, { "code": null, "e": 3686, "s": 3493, "text": "Please note that the images must come from a folder with the label. For example, always have banana images in a folder named Banana. You can have several such folders in different directories." }, { "code": null, "e": 3839, "s": 3686, "text": "You need to specify an output folder to save the images. For the above dataset, you’ll have the following structure in the output directory you mention." }, { "code": null, "e": 4089, "s": 3839, "text": "output-tmp (used for temporary data)-images--banana---img-0-banana-1.jpg---img-0-banana-2.jpg--apple---img-0-apple-1.jpg---img-0-apple-1.jpg-annotations--banana---img-0-banana-1.xml---img-0-banana-2.xml--apple---img-0-apple-1.xml---img-0-apple-1.xml" } ]
Program to find the maximum number in rotated list in C++
Suppose there is an array, and that is sorted, consider that array is rotated at some pivot, that is unknown to us. So we have to find the maximum from that rotated array. So if the array is like[3,4,5,1,2], then the output will be 5. To solve this, we will follow these steps − low := 0 and high := last index of array, n := size of array, ans := 0 low := 0 and high := last index of array, n := size of array, ans := 0 while low <= highmid := low + (high - low)/2if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1 while low <= high mid := low + (high - low)/2 mid := low + (high - low)/2 if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1 if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1 else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1 else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1 else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1 else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1 else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1 else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1 return ans return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int search(vector <int>& arr, int low, int high){ if(low == high){ return arr[low]; } int mid = low + (high - low) / 2; int ans = 0; if(arr[low] < arr[mid]){ ans = max(arr[low], search(arr, mid, high)); } else if (arr[high] > arr[mid]){ ans = max(arr[mid], search(arr, low, mid)); } else if(arr[low] == arr[mid]){ ans = max(arr[low], search(arr, low + 1, high)); } else if(arr[high] == arr[mid]){ ans = max(arr[high], search(arr, low, high - 1)); } return ans; } int findMax(vector<int>& nums) { return search(nums, 0, nums.size() - 1); } }; main(){ Solution ob; vector<int> v = {4,5,5,5,6,8,2,3,4}; cout <<(ob.findMax(v)); } [4,5,5,5,6,8,2,3,4] 8
[ { "code": null, "e": 1297, "s": 1062, "text": "Suppose there is an array, and that is sorted, consider that array is rotated at some pivot, that is unknown to us. So we have to find the maximum from that rotated array. So if the array is like[3,4,5,1,2], then the output will be 5." }, { "code": null, "e": 1341, "s": 1297, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1412, "s": 1341, "text": "low := 0 and high := last index of array, n := size of array, ans := 0" }, { "code": null, "e": 1483, "s": 1412, "text": "low := 0 and high := last index of array, n := size of array, ans := 0" }, { "code": null, "e": 1844, "s": 1483, "text": "while low <= highmid := low + (high - low)/2if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1" }, { "code": null, "e": 1862, "s": 1844, "text": "while low <= high" }, { "code": null, "e": 1890, "s": 1862, "text": "mid := low + (high - low)/2" }, { "code": null, "e": 1918, "s": 1890, "text": "mid := low + (high - low)/2" }, { "code": null, "e": 1998, "s": 1918, "text": "if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1" }, { "code": null, "e": 2078, "s": 1998, "text": "if arr[low] < arr[mid], then ans := maximum of ans and arr[low], low := mid + 1" }, { "code": null, "e": 2165, "s": 2078, "text": "else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1" }, { "code": null, "e": 2252, "s": 2165, "text": "else if arr[high] > arr[mid], then ans := maximum of ans and arr[mid], high := mid – 1" }, { "code": null, "e": 2327, "s": 2252, "text": "else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1" }, { "code": null, "e": 2402, "s": 2327, "text": "else if low = mid, then ans := maximum of ans and arr[low], low := mid + 1" }, { "code": null, "e": 2480, "s": 2402, "text": "else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1" }, { "code": null, "e": 2558, "s": 2480, "text": "else if high = mid, then ans := maximum of ans and arr[high], high := mid - 1" }, { "code": null, "e": 2569, "s": 2558, "text": "return ans" }, { "code": null, "e": 2580, "s": 2569, "text": "return ans" }, { "code": null, "e": 2650, "s": 2580, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2661, "s": 2650, "text": " Live Demo" }, { "code": null, "e": 3511, "s": 2661, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int search(vector <int>& arr, int low, int high){\n if(low == high){\n return arr[low];\n }\n int mid = low + (high - low) / 2;\n int ans = 0;\n if(arr[low] < arr[mid]){\n ans = max(arr[low], search(arr, mid, high));\n }\n else if (arr[high] > arr[mid]){\n ans = max(arr[mid], search(arr, low, mid));\n }\n else if(arr[low] == arr[mid]){\n ans = max(arr[low], search(arr, low + 1, high));\n }\n else if(arr[high] == arr[mid]){\n ans = max(arr[high], search(arr, low, high - 1));\n }\n return ans;\n }\n int findMax(vector<int>& nums) {\n return search(nums, 0, nums.size() - 1);\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {4,5,5,5,6,8,2,3,4};\n cout <<(ob.findMax(v));\n}" }, { "code": null, "e": 3531, "s": 3511, "text": "[4,5,5,5,6,8,2,3,4]" }, { "code": null, "e": 3533, "s": 3531, "text": "8" } ]
Java Swing JOptionPane Html Content Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In the previous tutorial, we learn about the basic Swing JOptionPane and saw different types of dialogue boxes. Here we are going to see how to add html content including images to JOptionPane. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.URL; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; class MyJOptionPane extends JFrame { JButton Warning, Message; JPanel ButtonPanel; URL url; MyJOptionPane() { super("JOptionPane Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Warning = new JButton("Warning for U"); Warning.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String Msg = "Brain Draining has become a serious "; Msg = Msg + " problem which needs immediate attention"; Msg = Msg + " What do u think "; JOptionPane.showMessageDialog(ButtonPanel, Msg, "HTML Message", JOptionPane.WARNING_MESSAGE); } }); Message = new JButton("Click me.."); Message.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { url = new URL( "file:\\C:\\Desktop\\images\\fox.png"); } catch (Exception e) { System.out.println("File not Loaded" + e); } String ImageSrc = ""; JOptionPane.showMessageDialog(ButtonPanel, "" + ImageSrc + " How is the Message ", "HTML Message with Image", JOptionPane.INFORMATION_MESSAGE); } }); ButtonPanel = new JPanel(); ButtonPanel.add(Warning); ButtonPanel.add(Message); getContentPane().add(ButtonPanel); setSize(300, 300); setVisible(true); } } class JOptionPane_HTML { public static void main(String args[]) { MyJOptionPane frame = new MyJOptionPane(); } } Output : JOptionPane HTML Content : JOptionPane with Images: Happy Learning 🙂 How to change Look and Feel of Swing setLookAndFeel Java JList Multiple Selection Example Java JColorChooser Example How to add dynamic files to JTree Java Swing JOptionPane Example Java Swing JLabel Example Java Swing Login Example Java Swing JSplitPane Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing Advanced JTable Example Java Swing JTabbedPane Example Java Swing JMenu Example Java Swing JToolBar Example Java Swing JTree Example How to change Look and Feel of Swing setLookAndFeel Java JList Multiple Selection Example Java JColorChooser Example How to add dynamic files to JTree Java Swing JOptionPane Example Java Swing JLabel Example Java Swing Login Example Java Swing JSplitPane Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing Advanced JTable Example Java Swing JTabbedPane Example Java Swing JMenu Example Java Swing JToolBar Example Java Swing JTree Example Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 593, "s": 398, "text": "In the previous tutorial, we learn about the basic Swing JOptionPane and saw different types of dialogue boxes. Here we are going to see how to add html content including images to JOptionPane." }, { "code": null, "e": 2681, "s": 593, "text": "import java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.net.URL;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\nclass MyJOptionPane extends JFrame {\n JButton Warning, Message;\n JPanel ButtonPanel;\n URL url;\n\n MyJOptionPane() {\n super(\"JOptionPane Demo\");\n\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n Warning = new JButton(\"Warning for U\");\n Warning.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n String Msg = \"Brain Draining has become a serious \";\n Msg = Msg\n + \" problem which needs immediate attention\";\n Msg = Msg + \" What do u think \";\n JOptionPane.showMessageDialog(ButtonPanel, Msg, \"HTML Message\",\n JOptionPane.WARNING_MESSAGE);\n }\n });\n\n Message = new JButton(\"Click me..\");\n Message.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n try {\n url = new URL(\n \"file:\\\\C:\\\\Desktop\\\\images\\\\fox.png\");\n } catch (Exception e) {\n System.out.println(\"File not Loaded\" + e);\n }\n String ImageSrc = \"\";\n JOptionPane.showMessageDialog(ButtonPanel, \"\" + ImageSrc\n + \" How is the Message \",\n \"HTML Message with Image\",\n JOptionPane.INFORMATION_MESSAGE);\n\n }\n });\n\n ButtonPanel = new JPanel();\n ButtonPanel.add(Warning);\n ButtonPanel.add(Message);\n\n getContentPane().add(ButtonPanel);\n setSize(300, 300);\n setVisible(true);\n }\n}\n\nclass JOptionPane_HTML {\n public static void main(String args[]) {\n MyJOptionPane frame = new MyJOptionPane();\n }\n}" }, { "code": null, "e": 2690, "s": 2681, "text": "Output :" }, { "code": null, "e": 2717, "s": 2690, "text": "JOptionPane HTML Content :" }, { "code": null, "e": 2742, "s": 2717, "text": "JOptionPane with Images:" }, { "code": null, "e": 2759, "s": 2742, "text": "Happy Learning 🙂" }, { "code": null, "e": 3225, "s": 2759, "text": "\nHow to change Look and Feel of Swing setLookAndFeel\nJava JList Multiple Selection Example\nJava JColorChooser Example\nHow to add dynamic files to JTree\nJava Swing JOptionPane Example\nJava Swing JLabel Example\nJava Swing Login Example\nJava Swing JSplitPane Example\nJava Swing ProgressBar Example\nJava Swing JTable Example\nJava Swing Advanced JTable Example\nJava Swing JTabbedPane Example\nJava Swing JMenu Example\nJava Swing JToolBar Example\nJava Swing JTree Example\n" }, { "code": null, "e": 3277, "s": 3225, "text": "How to change Look and Feel of Swing setLookAndFeel" }, { "code": null, "e": 3315, "s": 3277, "text": "Java JList Multiple Selection Example" }, { "code": null, "e": 3342, "s": 3315, "text": "Java JColorChooser Example" }, { "code": null, "e": 3376, "s": 3342, "text": "How to add dynamic files to JTree" }, { "code": null, "e": 3407, "s": 3376, "text": "Java Swing JOptionPane Example" }, { "code": null, "e": 3433, "s": 3407, "text": "Java Swing JLabel Example" }, { "code": null, "e": 3458, "s": 3433, "text": "Java Swing Login Example" }, { "code": null, "e": 3488, "s": 3458, "text": "Java Swing JSplitPane Example" }, { "code": null, "e": 3519, "s": 3488, "text": "Java Swing ProgressBar Example" }, { "code": null, "e": 3545, "s": 3519, "text": "Java Swing JTable Example" }, { "code": null, "e": 3580, "s": 3545, "text": "Java Swing Advanced JTable Example" }, { "code": null, "e": 3611, "s": 3580, "text": "Java Swing JTabbedPane Example" }, { "code": null, "e": 3636, "s": 3611, "text": "Java Swing JMenu Example" }, { "code": null, "e": 3664, "s": 3636, "text": "Java Swing JToolBar Example" }, { "code": null, "e": 3689, "s": 3664, "text": "Java Swing JTree Example" }, { "code": null, "e": 3695, "s": 3693, "text": "Δ" }, { "code": null, "e": 3719, "s": 3695, "text": " Install Java on Mac OS" }, { "code": null, "e": 3747, "s": 3719, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3776, "s": 3747, "text": " Install Minikube on Windows" }, { "code": null, "e": 3811, "s": 3776, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3838, "s": 3811, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3865, "s": 3838, "text": " Install Gradle on Windows" }, { "code": null, "e": 3894, "s": 3865, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3920, "s": 3894, "text": " Install PuTTY on windows" }, { "code": null, "e": 3946, "s": 3920, "text": " Install Mysql on Windows" }, { "code": null, "e": 3982, "s": 3946, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 4016, "s": 3982, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 4042, "s": 4016, "text": " Install Maven on Windows" }, { "code": null, "e": 4067, "s": 4042, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 4101, "s": 4067, "text": " Install Maven on Windows Command" }, { "code": null, "e": 4136, "s": 4101, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 4160, "s": 4136, "text": " Install Ant on Windows" }, { "code": null, "e": 4189, "s": 4160, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 4221, "s": 4189, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 4254, "s": 4221, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 4279, "s": 4254, "text": " Java8 – Install Windows" }, { "code": null, "e": 4296, "s": 4279, "text": " Java8 – foreach" }, { "code": null, "e": 4324, "s": 4296, "text": " Java8 – forEach with index" }, { "code": null, "e": 4355, "s": 4324, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 4387, "s": 4355, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 4407, "s": 4387, "text": " Java8 – GroupingBy" }, { "code": null, "e": 4427, "s": 4407, "text": " Java8 – SummingInt" }, { "code": null, "e": 4451, "s": 4427, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 4481, "s": 4451, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 4513, "s": 4481, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 4549, "s": 4513, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 4593, "s": 4549, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 4625, "s": 4593, "text": " Howto – Convert List to String" }, { "code": null, "e": 4666, "s": 4625, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 4703, "s": 4666, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4743, "s": 4703, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 4772, "s": 4743, "text": " Howto – Convert List to Map" }, { "code": null, "e": 4804, "s": 4772, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 4824, "s": 4804, "text": " Howto – Sort a Map" }, { "code": null, "e": 4846, "s": 4824, "text": " Howto – Filter a Map" }, { "code": null, "e": 4876, "s": 4846, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 4927, "s": 4876, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 4963, "s": 4927, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 4995, "s": 4963, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 5030, "s": 4995, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 5053, "s": 5030, "text": " Howto – Merge Streams" }, { "code": null, "e": 5100, "s": 5053, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 5125, "s": 5100, "text": " Howto -Get Stream count" }, { "code": null, "e": 5169, "s": 5125, "text": " Howto – Get Min and Max values in a Stream" } ]
DirectX - Buffers
For the GPU to access an array of vertices, they need to be placed in a special resource structure called a buffer, which is represented by the ID3D11Buffer interface. A buffer that stores vertices is called a vertex buffer. Direct3D buffers not only store data, but also describe how the data will be accessed and where it will be bound to the rendering pipeline. Because indices need to be accessed by the GPU, they need to be placed in a special resource structure — an index buffer. Creating an index buffer is very similar to creating a vertex buffer, except that the index buffer stores indices instead of vertices. Therefore, rather than repeating a discussion similar to the one carried out for vertex buffers, we just show an example of creating an index buffer − UINT indices[24] = { 0, 1, 2, // Triangle 0 0, 2, 3, // Triangle 1 0, 3, 4, // Triangle 2 0, 4, 5, // Triangle 3 0, 5, 6, // Triangle 4 0, 6, 7, // Triangle 5 0, 7, 8, // Triangle 6 0, 8, 1 // Triangle 7 }; // Describe the index buffer we are going to create. Observe the // D3D11_BIND_INDEX_BUFFER bind flag D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * 24; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; ibd.StructureByteStride = 0; // Specify the data to initialize the index buffer. D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = indices; // Create the index buffer. ID3D11Buffer* mIB; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB)); As with vertex buffers, and other Direct3D resources for that matter, before we can use it, we need to bind it to the pipeline. An index buffer is bound to the input assembler stage with theID3D11DeviceContext::IASetIndexBuffer method. Following is an example call − md3dImmediateContext->IASetIndexBuffer(mIB, DXGI_FORMAT_R32_UINT, 0); Print Add Notes Bookmark this page
[ { "code": null, "e": 2466, "s": 2298, "text": "For the GPU to access an array of vertices, they need to be placed in a special resource structure called a buffer, which is represented by the ID3D11Buffer interface." }, { "code": null, "e": 2663, "s": 2466, "text": "A buffer that stores vertices is called a vertex buffer. Direct3D buffers not only store data, but also describe how the data will be accessed and where it will be bound to the rendering pipeline." }, { "code": null, "e": 3071, "s": 2663, "text": "Because indices need to be accessed by the GPU, they need to be placed in a special resource structure — an index buffer. Creating an index buffer is very similar to creating a vertex buffer, except that the index buffer stores indices instead of vertices. Therefore, rather than repeating a discussion similar to the one carried out for vertex buffers, we just show an example of creating an index buffer −" }, { "code": null, "e": 3826, "s": 3071, "text": "UINT indices[24] = {\n 0, 1, 2, // Triangle 0\n 0, 2, 3, // Triangle 1\n 0, 3, 4, // Triangle 2\n 0, 4, 5, // Triangle 3\n 0, 5, 6, // Triangle 4\n 0, 6, 7, // Triangle 5\n 0, 7, 8, // Triangle 6\n 0, 8, 1 // Triangle 7\n};\n// Describe the index buffer we are going to create. Observe the\n// D3D11_BIND_INDEX_BUFFER bind flag\nD3D11_BUFFER_DESC ibd;\nibd.Usage = D3D11_USAGE_IMMUTABLE;\nibd.ByteWidth = sizeof(UINT) * 24;\nibd.BindFlags = D3D11_BIND_INDEX_BUFFER;\nibd.CPUAccessFlags = 0;\nibd.MiscFlags = 0;\nibd.StructureByteStride = 0;\n// Specify the data to initialize the index buffer.\nD3D11_SUBRESOURCE_DATA iinitData;\niinitData.pSysMem = indices;\n// Create the index buffer.\nID3D11Buffer* mIB;\nHR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB));" }, { "code": null, "e": 4062, "s": 3826, "text": "As with vertex buffers, and other Direct3D resources for that matter, before we can use it, we need to bind it to the pipeline. An index buffer is bound to the input assembler stage with theID3D11DeviceContext::IASetIndexBuffer method." }, { "code": null, "e": 4093, "s": 4062, "text": "Following is an example call −" }, { "code": null, "e": 4164, "s": 4093, "text": "md3dImmediateContext->IASetIndexBuffer(mIB, DXGI_FORMAT_R32_UINT, 0);\n" }, { "code": null, "e": 4171, "s": 4164, "text": " Print" }, { "code": null, "e": 4182, "s": 4171, "text": " Add Notes" } ]
Anomaly Detection in IoT Enabled Smart Battery Management Systems | by Manoj Kukreja | Towards Data Science
We are living in the world of electric mobility. Globally, the adoption of electric cars and two-wheeler is steeply on the rise. Electric mobility devices rely on expensive rechargeable lithium-ion batteries for power. These batteries are integral for the fight against the bad effects of fossil fuels such as pollution and rising costs. But the lithium-ion technology does come with some drawbacks such as: Fire hazard and explosions resulting from temperature increases and short-circuits Decreased life-span due to over/under charging Decreased performance over time due to aging The global Lithium-Ion battery market size is estimated to more than double in a few years — $44 billion in 2020 to $94 Billion by 2025 Right now the costs related to the procurement of the physical batteries and their maintenance is a major hurdle in the adoption of this technology. Several lithium-ion battery manufacturing companies are now coming up with Smart Battery Management Systems that help monitor and track the health of lithium-ion batteries. There are several goals of a battery management system: Preventative Analysis— Monitoring Layer — Continuously monitor threats related to fire and explosionsPredictive Analysis — Analytics Layer— Predict failures to prevent damage to the battery, therefore increasing the life of the battery Preventative Analysis— Monitoring Layer — Continuously monitor threats related to fire and explosions Predictive Analysis — Analytics Layer— Predict failures to prevent damage to the battery, therefore increasing the life of the battery Recently, I got a chance to create such a smart battery management system for a company who manufactures batteries for electric scooters. Following is the high level architecture of the solution: Each battery pack is fitted with an electronic IoT sensor that measures voltage, current and temperature of the battery Sensor data is sent to Azure cloud (Azure Event Hubs or Azure IoT Hub) using Wi-Fi or Bluetooth Streaming data from Azure Event Hubs /Azure IoT Hub is computed using Azure Stream Analytics Azure Stream Analytics jobs performs anomaly detection. If an anomaly is detected an alert is generated and sent to the user using Azure Notification Hubs In the following section I will show you how we managed to perform anomaly detection using a machine learning based operators — AnomalyDetection_SpikeAndDip and AnomalyDetection_ChangePoint provided by Azure. AnomalyDetection_SpikeAndDip is capable of detecting temporary anomalies in a time series event. AnomalyDetection_ChangePoint is capable of detecting persistent anomalies in a time series event stream For this demonstration I used Aqueouss 48V 25Ah Li-Ion Battery. Following are the technical specifications of the battery. For this battery following are the recommended watermarks. Upper point voltage — 54.6 V— Anything higher could cause an explosion or fireLower point voltage — 39 V — Anything lower impacts the health of the battery A key function of the battery management system is to monitor these key values are in the recommended range. For the purpose of this demo I will concentrate on the Upper point voltage. After all who wants an explosion or fire. Now lets get started on the implementation. Assuming you already have a Azure account feel free to follow along by following the steps below: Open a cloud shell https://portal.azure.com/#cloudshell/ Invoke the command below to clone the code repository Azure> git clone https://github.com/mkukreja1/blogsCloning into ‘blogs’...remote: Enumerating objects: 149, done.remote: Counting objects: 100% (149/149), done.remote: Compressing objects: 100% (90/90), done.remote: Total 149 (delta 54), reused 135 (delta 40), pack-reused 0Receiving objects: 100% (149/149), 1.67 MiB | 41.71 MiB/s, done.Resolving deltas: 100% (54/54), done. Now lets create an Azure Event Hub. You may want to edit the name of the RESOURCEGROUPNAME and LOCATION as per your preferences. RESOURCEGROUPNAME="training_rg"LOCATION="eastus"TOPIC="iotbattery"EVENTHUB_NAMESPACE="iotbatteryspace"EVENTHUB_NAME="iotbatteryhub"EVENT_SUBSCRIPTION="iotbatteryevent"az provider register --namespace Microsoft.EventGridaz provider show --namespace Microsoft.EventGrid --query "registrationState"az eventgrid topic create --name $TOPIC -l $LOCATION -g $RESOURCEGROUPNAMEaz eventhubs namespace create --name $EVENTHUB_NAMESPACE --resource-group $RESOURCEGROUPNAMEaz eventhubs eventhub create --name $EVENTHUB_NAME --namespace-name $EVENTHUB_NAMESPACE --resource-group $RESOURCEGROUPNAME To verify the newly created Azure Event Hub navigate to Home > All Resources > iotbatteryspace. On the left menu click on Event Hubs. Now click on the newly created event hub iotbatteryhub. Click on Process Data followed by Explore. You should now be in a Query Editor window. We need to create a shared access policy for previewing data in Azure event hubs. Click on Create. At this point we are ready to send some events to the newly created Azure event hub. Since you will not have an actual IoT sensor we can use commands below to emulate 100 events from five batteries sent to Azure event hubs. Invoke commands below in cloud shell. RESOURCEGROUPNAME="training_rg"TOPIC="iotbattery"EVENTHUB_NAMESPACE="iotbatteryspace"EVENTHUB_NAME="iotbatteryhub"EVENTHUB_CONN_STR=$(az eventhubs namespace authorization-rule keys list --resource-group $RESOURCEGROUPNAME --namespace-name $EVENTHUB_NAMESPACE --name RootManageSharedAccessKey --query "primaryConnectionString" --output tsv)for VARIABLE in {1..100}do echo "Sending event $VARIABLE" python ~/blogs/eventhubs/iot/send_battery_events_normal_reading.py --EVENTHUB_NAME $EVENTHUB_NAME --EVENTHUB_CONN_STR $EVENTHUB_CONN_STRdone We can now verify if the event data appears in the Azure event hub. Go back to the Azure portal query editor. In the Input preview tab, press Refresh. You should now see the newly sent events in the query window. Check the readings received from IoT events. Invoke SQL below in query editor. SELECT data.Timestamp, data."Battery Pack", data."Terminal Voltage", data."Charging Current", data."Discharging Current",data."SoC", data."Charge Capacity", data."Charging Power", data."Discharging Power", data."Cycle Count"FROM [iotbatteryhub] We are now ready to implement anomaly detection. Remember we want to monitor battery voltage for spikes os volatage because they could be dangerous. Invoke the SQL below to check how many spike were received. WITH batteryAnomalyDetection AS( SELECT data.Timestamp AS time, CAST(data."Terminal Voltage" AS float) AS Voltage, AnomalyDetection_SpikeAndDip(CAST(data."Terminal Voltage" AS float), 70, 90, 'spikes') OVER(LIMIT DURATION(second, 120)) AS Spikes FROM [iotbatteryhub])SELECT time, Voltage, CAST(GetRecordPropertyValue(Spikes, 'Score') AS float) AS SpikeAndDipScore, CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint) AS IsSpikeAnomalyINTO batteryFROM batteryAnomalyDetectionWHERE CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint)=1 In the SQL above we checked the anomaly using a confidence of 70%. AnomalyDetection_SpikeAndDip(CAST(data."Terminal Voltage" AS float), 70, 90, 'spikes') The image above shows us that the machine learning operator flagged 17 events as spikes. Let’s retest the model but this time for a 90% confidence. WITH batteryAnomalyDetection AS( SELECT data.Timestamp AS time, CAST(data."Terminal Voltage" AS float) AS Voltage, AnomalyDetection_SpikeAndDip(CAST(data."Terminal Voltage" AS float), 90, 95, 'spikes') OVER(LIMIT DURATION(second, 120)) AS Spikes FROM [iotbatteryhub])SELECT time, Voltage, CAST(GetRecordPropertyValue(Spikes, 'Score') AS float) AS SpikeAndDipScore, CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint) AS IsSpikeAnomalyINTO batteryFROM batteryAnomalyDetectionWHERE CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint)=1 The image above shows us that the machine learning operator flagged 15 events as spikes. For Preventative Analysis we can implement code that will send an alert for each spike recived. This can be done easily using Azure functions. Now lets do something even more fun. We will now covert this to a Stream Analytics Job. The benefit of converting this query to a job is that data can be collected unattended. The collected data will help us with further analysis that can be used for dashboarding and decision making. WITH batteryAnomalyDetection AS( SELECT data.Timestamp AS time, CAST(data."Terminal Voltage" AS float) AS Voltage, AnomalyDetection_SpikeAndDip(CAST(data."Terminal Voltage" AS float), 90, 95, 'spikes') OVER(LIMIT DURATION(second, 120)) AS Spikes FROM [iotbatteryhub])SELECT time, Voltage, CAST(GetRecordPropertyValue(Spikes, 'Score') AS float) AS SpikeAndDipScore, CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint) AS IsSpikeAnomalyINTO batteryFROM batteryAnomalyDetection Click on Create Stream Analytics Job. Fill in the details as below and click on Create. You will now be in window that looks like this. We need an output for data collection. Click on + Add and choose Azure Blob storage/ADLS Gen2. Now that the output of the job has been created we are ready to start the job. Click on Start. Once you recieve the “Streaming job started successfully” message send some more events to the event hub. Invoke commands below in cloud shell. RESOURCEGROUPNAME="training_rg"TOPIC="iotbattery"EVENTHUB_NAMESPACE="iotbatteryspace"EVENTHUB_NAME="iotbatteryhub"EVENTHUB_CONN_STR=$(az eventhubs namespace authorization-rule keys list --resource-group $RESOURCEGROUPNAME --namespace-name $EVENTHUB_NAMESPACE --name RootManageSharedAccessKey --query "primaryConnectionString" --output tsv)for VARIABLE in {1..100}do echo "Sending event $VARIABLE" python ~/blogs/eventhubs/iot/send_battery_events_normal_reading.py --EVENTHUB_NAME $EVENTHUB_NAME --EVENTHUB_CONN_STR $EVENTHUB_CONN_STRdone If everything worked well the stream analytic job will out events to storage below in JSON format. Navigate to Home > All Resources > traininglakehouse > battery But how do we perform analysis on the events data. For this we can use Azure Synapse. Invoke commands below in cloud shell to create a new Synape workspace. STORAGEACCOUNTNAME="traininglakehouse"BATTERYDATALAYER="battery"SYSNAPSEWORKSPACENAME="batterytracking"RESOURCEGROUPNAME="training_rg"LOCATION="eastus"SQLUSER="sqladminuser"SQLPASSWORD="*********"az synapse workspace create \ --name $SYSNAPSEWORKSPACENAME \ --resource-group $RESOURCEGROUPNAME \ --storage-account $STORAGEACCOUNTNAME \ --file-system $BATTERYDATALAYER \ --sql-admin-login-user $SQLUSER \ --sql-admin-login-password $SQLPASSWORD \ --location $LOCATIONaz synapse workspace firewall-rule create --name allowAll --workspace-name $SYSNAPSEWORKSPACENAME --resource-group $RESOURCEGROUPNAME --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255 Now navigate to Home > All Resources > batterytracking and click on Open in the Open Synapse Studio section In the Synapse workspace window click on Data using menus on left pane. Enter details as below and click Create Once the database has been created open a new SQL script window. Paste the SQL below in the newly opened SQL window. This SQL will create a view over the battery events data. CREATE view batteryASSELECT JSON_VALUE(doc, '$.time') AS time, JSON_VALUE(doc, '$.BatteryPack') AS BatteryPack, JSON_VALUE(doc, '$.Voltage') AS Voltage, JSON_VALUE(doc, '$.SpikeAndDipScore') AS SpikeAndDipScore, JSON_VALUE(doc, '$.IsSpikeAnomaly') AS IsSpikeAnomalyFROM openrowset( BULK 'https://traininglakehouse.blob.core.windows.net/battery/', FORMAT= 'csv', FIELDTERMINATOR='0x0b', FIELDQUOTE= '0x0b') WITH(doc nvarchar(max)) as rowGOSELECT CONVERT(TIME,DATEADD(s,cast(time as int),'19700101 0:00:00')) as time, BatteryPack, Voltage, IsSpikeAnomaly FROM batteryGO As you can see we can now vizualize events data as it flows in to storage. This chart below shows us the spikes in events over time. This information is critical is critical for Predictive Analysis. I hope this article was helpful. The topic is covered in greater detail as part of the Azure Data Analytics course offered by Datafence Cloud Academy. The course is taught online by myself on weekends.
[ { "code": null, "e": 579, "s": 171, "text": "We are living in the world of electric mobility. Globally, the adoption of electric cars and two-wheeler is steeply on the rise. Electric mobility devices rely on expensive rechargeable lithium-ion batteries for power. These batteries are integral for the fight against the bad effects of fossil fuels such as pollution and rising costs. But the lithium-ion technology does come with some drawbacks such as:" }, { "code": null, "e": 662, "s": 579, "text": "Fire hazard and explosions resulting from temperature increases and short-circuits" }, { "code": null, "e": 709, "s": 662, "text": "Decreased life-span due to over/under charging" }, { "code": null, "e": 754, "s": 709, "text": "Decreased performance over time due to aging" }, { "code": null, "e": 890, "s": 754, "text": "The global Lithium-Ion battery market size is estimated to more than double in a few years — $44 billion in 2020 to $94 Billion by 2025" }, { "code": null, "e": 1268, "s": 890, "text": "Right now the costs related to the procurement of the physical batteries and their maintenance is a major hurdle in the adoption of this technology. Several lithium-ion battery manufacturing companies are now coming up with Smart Battery Management Systems that help monitor and track the health of lithium-ion batteries. There are several goals of a battery management system:" }, { "code": null, "e": 1504, "s": 1268, "text": "Preventative Analysis— Monitoring Layer — Continuously monitor threats related to fire and explosionsPredictive Analysis — Analytics Layer— Predict failures to prevent damage to the battery, therefore increasing the life of the battery" }, { "code": null, "e": 1606, "s": 1504, "text": "Preventative Analysis— Monitoring Layer — Continuously monitor threats related to fire and explosions" }, { "code": null, "e": 1741, "s": 1606, "text": "Predictive Analysis — Analytics Layer— Predict failures to prevent damage to the battery, therefore increasing the life of the battery" }, { "code": null, "e": 1937, "s": 1741, "text": "Recently, I got a chance to create such a smart battery management system for a company who manufactures batteries for electric scooters. Following is the high level architecture of the solution:" }, { "code": null, "e": 2057, "s": 1937, "text": "Each battery pack is fitted with an electronic IoT sensor that measures voltage, current and temperature of the battery" }, { "code": null, "e": 2153, "s": 2057, "text": "Sensor data is sent to Azure cloud (Azure Event Hubs or Azure IoT Hub) using Wi-Fi or Bluetooth" }, { "code": null, "e": 2246, "s": 2153, "text": "Streaming data from Azure Event Hubs /Azure IoT Hub is computed using Azure Stream Analytics" }, { "code": null, "e": 2401, "s": 2246, "text": "Azure Stream Analytics jobs performs anomaly detection. If an anomaly is detected an alert is generated and sent to the user using Azure Notification Hubs" }, { "code": null, "e": 2610, "s": 2401, "text": "In the following section I will show you how we managed to perform anomaly detection using a machine learning based operators — AnomalyDetection_SpikeAndDip and AnomalyDetection_ChangePoint provided by Azure." }, { "code": null, "e": 2707, "s": 2610, "text": "AnomalyDetection_SpikeAndDip is capable of detecting temporary anomalies in a time series event." }, { "code": null, "e": 2811, "s": 2707, "text": "AnomalyDetection_ChangePoint is capable of detecting persistent anomalies in a time series event stream" }, { "code": null, "e": 2934, "s": 2811, "text": "For this demonstration I used Aqueouss 48V 25Ah Li-Ion Battery. Following are the technical specifications of the battery." }, { "code": null, "e": 2993, "s": 2934, "text": "For this battery following are the recommended watermarks." }, { "code": null, "e": 3149, "s": 2993, "text": "Upper point voltage — 54.6 V— Anything higher could cause an explosion or fireLower point voltage — 39 V — Anything lower impacts the health of the battery" }, { "code": null, "e": 3376, "s": 3149, "text": "A key function of the battery management system is to monitor these key values are in the recommended range. For the purpose of this demo I will concentrate on the Upper point voltage. After all who wants an explosion or fire." }, { "code": null, "e": 3518, "s": 3376, "text": "Now lets get started on the implementation. Assuming you already have a Azure account feel free to follow along by following the steps below:" }, { "code": null, "e": 3575, "s": 3518, "text": "Open a cloud shell https://portal.azure.com/#cloudshell/" }, { "code": null, "e": 3629, "s": 3575, "text": "Invoke the command below to clone the code repository" }, { "code": null, "e": 4005, "s": 3629, "text": "Azure> git clone https://github.com/mkukreja1/blogsCloning into ‘blogs’...remote: Enumerating objects: 149, done.remote: Counting objects: 100% (149/149), done.remote: Compressing objects: 100% (90/90), done.remote: Total 149 (delta 54), reused 135 (delta 40), pack-reused 0Receiving objects: 100% (149/149), 1.67 MiB | 41.71 MiB/s, done.Resolving deltas: 100% (54/54), done." }, { "code": null, "e": 4134, "s": 4005, "text": "Now lets create an Azure Event Hub. You may want to edit the name of the RESOURCEGROUPNAME and LOCATION as per your preferences." }, { "code": null, "e": 4719, "s": 4134, "text": "RESOURCEGROUPNAME=\"training_rg\"LOCATION=\"eastus\"TOPIC=\"iotbattery\"EVENTHUB_NAMESPACE=\"iotbatteryspace\"EVENTHUB_NAME=\"iotbatteryhub\"EVENT_SUBSCRIPTION=\"iotbatteryevent\"az provider register --namespace Microsoft.EventGridaz provider show --namespace Microsoft.EventGrid --query \"registrationState\"az eventgrid topic create --name $TOPIC -l $LOCATION -g $RESOURCEGROUPNAMEaz eventhubs namespace create --name $EVENTHUB_NAMESPACE --resource-group $RESOURCEGROUPNAMEaz eventhubs eventhub create --name $EVENTHUB_NAME --namespace-name $EVENTHUB_NAMESPACE --resource-group $RESOURCEGROUPNAME" }, { "code": null, "e": 4909, "s": 4719, "text": "To verify the newly created Azure Event Hub navigate to Home > All Resources > iotbatteryspace. On the left menu click on Event Hubs. Now click on the newly created event hub iotbatteryhub." }, { "code": null, "e": 5095, "s": 4909, "text": "Click on Process Data followed by Explore. You should now be in a Query Editor window. We need to create a shared access policy for previewing data in Azure event hubs. Click on Create." }, { "code": null, "e": 5357, "s": 5095, "text": "At this point we are ready to send some events to the newly created Azure event hub. Since you will not have an actual IoT sensor we can use commands below to emulate 100 events from five batteries sent to Azure event hubs. Invoke commands below in cloud shell." }, { "code": null, "e": 5895, "s": 5357, "text": "RESOURCEGROUPNAME=\"training_rg\"TOPIC=\"iotbattery\"EVENTHUB_NAMESPACE=\"iotbatteryspace\"EVENTHUB_NAME=\"iotbatteryhub\"EVENTHUB_CONN_STR=$(az eventhubs namespace authorization-rule keys list --resource-group $RESOURCEGROUPNAME --namespace-name $EVENTHUB_NAMESPACE --name RootManageSharedAccessKey --query \"primaryConnectionString\" --output tsv)for VARIABLE in {1..100}do echo \"Sending event $VARIABLE\" python ~/blogs/eventhubs/iot/send_battery_events_normal_reading.py --EVENTHUB_NAME $EVENTHUB_NAME --EVENTHUB_CONN_STR $EVENTHUB_CONN_STRdone" }, { "code": null, "e": 6108, "s": 5895, "text": "We can now verify if the event data appears in the Azure event hub. Go back to the Azure portal query editor. In the Input preview tab, press Refresh. You should now see the newly sent events in the query window." }, { "code": null, "e": 6187, "s": 6108, "text": "Check the readings received from IoT events. Invoke SQL below in query editor." }, { "code": null, "e": 6432, "s": 6187, "text": "SELECT data.Timestamp, data.\"Battery Pack\", data.\"Terminal Voltage\", data.\"Charging Current\", data.\"Discharging Current\",data.\"SoC\", data.\"Charge Capacity\", data.\"Charging Power\", data.\"Discharging Power\", data.\"Cycle Count\"FROM [iotbatteryhub]" }, { "code": null, "e": 6641, "s": 6432, "text": "We are now ready to implement anomaly detection. Remember we want to monitor battery voltage for spikes os volatage because they could be dangerous. Invoke the SQL below to check how many spike were received." }, { "code": null, "e": 7249, "s": 6641, "text": "WITH batteryAnomalyDetection AS( SELECT data.Timestamp AS time, CAST(data.\"Terminal Voltage\" AS float) AS Voltage, AnomalyDetection_SpikeAndDip(CAST(data.\"Terminal Voltage\" AS float), 70, 90, 'spikes') OVER(LIMIT DURATION(second, 120)) AS Spikes FROM [iotbatteryhub])SELECT time, Voltage, CAST(GetRecordPropertyValue(Spikes, 'Score') AS float) AS SpikeAndDipScore, CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint) AS IsSpikeAnomalyINTO batteryFROM batteryAnomalyDetectionWHERE CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint)=1" }, { "code": null, "e": 7403, "s": 7249, "text": "In the SQL above we checked the anomaly using a confidence of 70%. AnomalyDetection_SpikeAndDip(CAST(data.\"Terminal Voltage\" AS float), 70, 90, 'spikes')" }, { "code": null, "e": 7492, "s": 7403, "text": "The image above shows us that the machine learning operator flagged 17 events as spikes." }, { "code": null, "e": 7551, "s": 7492, "text": "Let’s retest the model but this time for a 90% confidence." }, { "code": null, "e": 8159, "s": 7551, "text": "WITH batteryAnomalyDetection AS( SELECT data.Timestamp AS time, CAST(data.\"Terminal Voltage\" AS float) AS Voltage, AnomalyDetection_SpikeAndDip(CAST(data.\"Terminal Voltage\" AS float), 90, 95, 'spikes') OVER(LIMIT DURATION(second, 120)) AS Spikes FROM [iotbatteryhub])SELECT time, Voltage, CAST(GetRecordPropertyValue(Spikes, 'Score') AS float) AS SpikeAndDipScore, CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint) AS IsSpikeAnomalyINTO batteryFROM batteryAnomalyDetectionWHERE CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint)=1" }, { "code": null, "e": 8248, "s": 8159, "text": "The image above shows us that the machine learning operator flagged 15 events as spikes." }, { "code": null, "e": 8391, "s": 8248, "text": "For Preventative Analysis we can implement code that will send an alert for each spike recived. This can be done easily using Azure functions." }, { "code": null, "e": 8676, "s": 8391, "text": "Now lets do something even more fun. We will now covert this to a Stream Analytics Job. The benefit of converting this query to a job is that data can be collected unattended. The collected data will help us with further analysis that can be used for dashboarding and decision making." }, { "code": null, "e": 9217, "s": 8676, "text": "WITH batteryAnomalyDetection AS( SELECT data.Timestamp AS time, CAST(data.\"Terminal Voltage\" AS float) AS Voltage, AnomalyDetection_SpikeAndDip(CAST(data.\"Terminal Voltage\" AS float), 90, 95, 'spikes') OVER(LIMIT DURATION(second, 120)) AS Spikes FROM [iotbatteryhub])SELECT time, Voltage, CAST(GetRecordPropertyValue(Spikes, 'Score') AS float) AS SpikeAndDipScore, CAST(GetRecordPropertyValue(Spikes, 'IsAnomaly') AS bigint) AS IsSpikeAnomalyINTO batteryFROM batteryAnomalyDetection" }, { "code": null, "e": 9305, "s": 9217, "text": "Click on Create Stream Analytics Job. Fill in the details as below and click on Create." }, { "code": null, "e": 9353, "s": 9305, "text": "You will now be in window that looks like this." }, { "code": null, "e": 9448, "s": 9353, "text": "We need an output for data collection. Click on + Add and choose Azure Blob storage/ADLS Gen2." }, { "code": null, "e": 9543, "s": 9448, "text": "Now that the output of the job has been created we are ready to start the job. Click on Start." }, { "code": null, "e": 9687, "s": 9543, "text": "Once you recieve the “Streaming job started successfully” message send some more events to the event hub. Invoke commands below in cloud shell." }, { "code": null, "e": 10225, "s": 9687, "text": "RESOURCEGROUPNAME=\"training_rg\"TOPIC=\"iotbattery\"EVENTHUB_NAMESPACE=\"iotbatteryspace\"EVENTHUB_NAME=\"iotbatteryhub\"EVENTHUB_CONN_STR=$(az eventhubs namespace authorization-rule keys list --resource-group $RESOURCEGROUPNAME --namespace-name $EVENTHUB_NAMESPACE --name RootManageSharedAccessKey --query \"primaryConnectionString\" --output tsv)for VARIABLE in {1..100}do echo \"Sending event $VARIABLE\" python ~/blogs/eventhubs/iot/send_battery_events_normal_reading.py --EVENTHUB_NAME $EVENTHUB_NAME --EVENTHUB_CONN_STR $EVENTHUB_CONN_STRdone" }, { "code": null, "e": 10387, "s": 10225, "text": "If everything worked well the stream analytic job will out events to storage below in JSON format. Navigate to Home > All Resources > traininglakehouse > battery" }, { "code": null, "e": 10544, "s": 10387, "text": "But how do we perform analysis on the events data. For this we can use Azure Synapse. Invoke commands below in cloud shell to create a new Synape workspace." }, { "code": null, "e": 11211, "s": 10544, "text": "STORAGEACCOUNTNAME=\"traininglakehouse\"BATTERYDATALAYER=\"battery\"SYSNAPSEWORKSPACENAME=\"batterytracking\"RESOURCEGROUPNAME=\"training_rg\"LOCATION=\"eastus\"SQLUSER=\"sqladminuser\"SQLPASSWORD=\"*********\"az synapse workspace create \\ --name $SYSNAPSEWORKSPACENAME \\ --resource-group $RESOURCEGROUPNAME \\ --storage-account $STORAGEACCOUNTNAME \\ --file-system $BATTERYDATALAYER \\ --sql-admin-login-user $SQLUSER \\ --sql-admin-login-password $SQLPASSWORD \\ --location $LOCATIONaz synapse workspace firewall-rule create --name allowAll --workspace-name $SYSNAPSEWORKSPACENAME --resource-group $RESOURCEGROUPNAME --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255" }, { "code": null, "e": 11319, "s": 11211, "text": "Now navigate to Home > All Resources > batterytracking and click on Open in the Open Synapse Studio section" }, { "code": null, "e": 11391, "s": 11319, "text": "In the Synapse workspace window click on Data using menus on left pane." }, { "code": null, "e": 11431, "s": 11391, "text": "Enter details as below and click Create" }, { "code": null, "e": 11496, "s": 11431, "text": "Once the database has been created open a new SQL script window." }, { "code": null, "e": 11606, "s": 11496, "text": "Paste the SQL below in the newly opened SQL window. This SQL will create a view over the battery events data." }, { "code": null, "e": 12182, "s": 11606, "text": "CREATE view batteryASSELECT JSON_VALUE(doc, '$.time') AS time, JSON_VALUE(doc, '$.BatteryPack') AS BatteryPack, JSON_VALUE(doc, '$.Voltage') AS Voltage, JSON_VALUE(doc, '$.SpikeAndDipScore') AS SpikeAndDipScore, JSON_VALUE(doc, '$.IsSpikeAnomaly') AS IsSpikeAnomalyFROM openrowset( BULK 'https://traininglakehouse.blob.core.windows.net/battery/', FORMAT= 'csv', FIELDTERMINATOR='0x0b', FIELDQUOTE= '0x0b') WITH(doc nvarchar(max)) as rowGOSELECT CONVERT(TIME,DATEADD(s,cast(time as int),'19700101 0:00:00')) as time, BatteryPack, Voltage, IsSpikeAnomaly FROM batteryGO" }, { "code": null, "e": 12381, "s": 12182, "text": "As you can see we can now vizualize events data as it flows in to storage. This chart below shows us the spikes in events over time. This information is critical is critical for Predictive Analysis." } ]
A Beginner’s Guide to Discrete Time Markov Chains | by Sachin Date | Towards Data Science
A Discrete Time Markov Chain can be used to describe the behavior of a system that jumps from one state to another state with a certain probability, and this probability of transition to the next state depends only on what state the system is in currently, i.e. it does not depend on which states the system was in prior to the current state. The above definition pretty much sums up the long and short of what is a Discrete Time Markov Process or a Markov Chain as it’s often called. But the above description is deceptively simple. As we’ll see, even the simplest of Markov Chains can create richly interesting patterns of system behavior. In this article, we’ll use the terms Markov process and Markov chain interchangeably. The Markov chain shown above has two states, or regimes as they are sometimes called: +1 and -1. There are four types of state transitions possible between the two states: State +1 to state +1: This transition happens with probability p_11 State +1 to State -1 with transition probability p_12 State -1 to State +1 with transition probability p_21 State -1 to State -1 with transition probability p_22 The above figure is known as the state transition diagram of the Markov process. The following diagram shows another way to represent this Markov process. The X-axis is the time axis. The bubbles represent the different possible states that the process could be in at each time step. In reality, at each time step, the process will be in exactly one of the many possible states. In the following diagram, the black bubbles depict one such realization of the Markov process across 4 successive time steps: There are many such realizations possible. In a 2-state Markov process, there are 2^N possible realizations of the Markov chain over N time steps. By illustrating the march of a Markov process along the time axis, we glean the following important property of a Markov process: A realization of a Markov chain along the time dimension is a time series. In a 2-state Markov chain, there are four possible state transitions and the corresponding transition probabilities. We can represent them in a state transition matrix P as follows: For a Markov chain over n-states (1,2,3,...,n), the transition matrix looks like this: The state transition matrix has the following two important properties: Since each element p_ij is a probability, 0 ≤ p_ij ≤ 1 Each row of P sums to 1.0 i.e. This is because the row index represents the source state at time t and the column index represents the destination state at time (t+1). If the process is in source state i at time t, at (t+1), it has to be in one of the allowed set of states (1,2,3,...,n). Thus, we can restate the transition matrix of a 2-state Markov process as follows: We will now introduce a random variable X_t. The suffix t in X_t denotes the time step. At each time step t, X_t takes a value from the state space [1,2,3,...,n] as per some probability distribution. One possible sequence of values that X_t could take is {X_0=1, X_1=3, X_2=4, X_3=0,...,X_t=k}. At time t, the probability that X_t takes some value j given that X_t had taken a value i at the previous time step (t-1) is given by the following conditional probability: Indeed, this is the transition probability p_ij. The Markov property states that p_ij is independent of the state in which the system was at times (t-2), (t-3),...,0. The Markov property is stated as follows: The state transition matrix P has this nice property by which if you multiply it with itself k times, then the matrix P^k contains the probabilities of all transitions that are k-steps long, i.e. the probability that system will be in state j after hopping through k number of transitions starting from state i, for i, j, in [1,2,3,...,n]. For example, consider the following transition probabilities matrix for a 2-step Markov process: The 2-step transition probabilities are calculated as follows: In P2, p_11=0.625 is the probability of returning to state 1 after having traversed through two states starting from state 1. Similarly, p_12=0.375 is the probability of reaching state 2 in exactly two time steps starting from state 1. These probabilities have factored in all possible ways of going from state 1 to state 1 (or state 1 to state 2, and so on) that are 2 steps long. We could continue multiplying P with itself forever to see how the n-step probabilities change over time. What would be more interesting is if we could know what is the unconditional probability distribution of X_t at each time step t. For example, in our 2-step Markov process example, at each time step t, what is the probability with which X_t could be +1 or -1? These probabilities constitute what is known as the state probability distribution of the Markov variable X_t at time t and it is denoted by π_t, (or δ_t). For example, for the 2-state Markov process consisting of states +1 and -1, the state distribution is given as follows: An n-state Markov process that operates over the states [1,2,3,...,n] could be in any one of those n states at time t, so π_t is a vector of length n as follows: In general, each element of π_t can be referenced using the notation π_jt. π_jt is indexed using two variables j and t, indicating the unconditional probability π of the process being in state j at time t: Since π_t is a probability distribution, its elements always sum up to 1.0: Typically, one assumes a certain value for π_0 which is the probability vector for state 0. And given π_0, it can be shown that π_t can be calculated as follows: The idea behind computing π_t is to matrix-multiply the state transition matrix with itself t number of times to get the t-step transition probabilities, and multiply the t-step transition probabilities with the unconditional probability distribution π_0 at t=0. Notice the following two things about the above equation: The state probability distribution of a Markov process at time t depends on: The initial probability distribution π_0 at time t=0, andIt depends on time step t. The initial probability distribution π_0 at time t=0, and It depends on time step t. Thus, The probability distribution of a Markov distributed random variable evolves over time. Let’s work through all the concepts learnt so far using an example. Suppose the stock of Acme Corporation increases or decreases as per the following rules: As compared to the previous day’s closing price, the current day’s closing price is either higher or lower by some percentage points. For, e.g. on some day, Acme’s stock closes 2.3% higher than the previous day. On other days, it might close 0.8% lower than the previous day’s closing price. Given any sequence of 3 days denoted by ‘day before’, ‘yesterday’ and ‘today’, if Acme has closed higher yesterday than the day before, it will close higher today than yesterday with a probability p_11. Consequently, it would close lower today than yesterday with a probability (1 — p_11). Let’s also assume that if Acme has closed lower yesterday than the day before, the probability that it would once again close lower today is p_22. And therefore, the probability that it would close higher today than it did yesterday is (1 — p22). You may have guessed that Acme’s stock price can be modeled using a 2-state Markov process. It’s state transition diagram looks like this: And it’s transition probabilities matrix P looks like this: Now let’s pin down some sample values for these probabilities. Suppose the probability of Acme’s price’s moving up two days in a row is 0.6 and the chances of the price moving down for two days in a row is 0.25. Thus, p_11=0.6 and p_22=0.25 And therefore, we have: p_12=1 — p_11 = 0.4, and, p_21=1 — p22 = 0.75 The state transition matrix for Acme’s stock is as follows: The state transition diagram of the Markov process model for Acme’s stock is as follows: We would now like to calculate the following unconditional probability distribution: Let’s assume an initial value of π_0=[0.5,0.5], i.e. an equal probability of it’s closing higher (+1 state) or lower ( — 1 state) on listing day, as compared to the IPO price. If we repeatedly apply the formula for π_t=π_0*P^t, we will get the probability distribution vector π_t for each time step t. The following Python code calculates π_t: import numpy as npfrom matplotlib import pyplot as plt#initialize the transition matrix PP=np.array([[0.6,0.4],[0.75,0.25]])#initialize pi_0pi_0=np.array([0.5, 0.5])#set up the array to accumulate the state probabilities at times t=1 to 10pi=[]pi.append(pi_0)P_mul=P.copy()#calculate the state probability for each t and store it away for i in range(10): P_mul=np.matmul(P_mul,P) pi_t = np.matmul(pi_0,P_mul) pi.append(pi_t)pi = np.array(pi) The above code stores all the calculated π_t vectors in the array π. Let’s separately plot the components π_1t and π_2t of π_t= [ π_1t, π_2t] for t=1 through 10. #plot pi_1t = P(X_t = +1) versus tfig = plt.figure()fig.suptitle('Probability of closing higher than previous day\'s close')plt.plot(range(len(pi)), pi[:,0])plt.show()#plot pi_2t = P(X_t = -1) versus tfig.suptitle('Probability of closing lower than previous day\'s close')plt.plot(range(len(pi)), pi[:,1])plt.show() We get the following two plots: We see that in just a few time steps, the unconditional probabilities vector π_t= [ π_1t, π_2t] settles down into the steady state value [0.65217391, 0.34782609]. In fact, it can be shown that if a two state Markov process with the following transition matrix is run for ‘long time’: Then the state probability distribution π_t steady-states to the following constant (limiting) probability distribution that is independent of both t and the initial probability distribution π_0: Let’s simulate Acme Corp’s stock price movement at each time step t using the probability distribution π_t at time t. The simulation procedure goes like this: Assume Acme’s IPO price to be $100. Set the initial probability distribution:π_0=[P(X_t = +1)=0.5, P(X_t = -1) = 0.5]. Map the +1 Markov state to the action of increasing Acme’s previous day’s closing price by a random percentage in the interval [0.0%, 2.0%]. Map the -1 Markov state to reducing Acme’s previous day’s closing price by a similar random percentage in the interval [0.0%, 2.0%]. At each time step t, calculate the state probability distribution π_t=[P(X_t = +1), P(X_t = -1) = 0.5], by using the formula π_t = π_0*P^t. Generate a uniformly distributed random number in the interval [0, 1.0]. If this number is less than or equal to π_1t = P(X_t = +1), increase the closing price from the previous time step by a random percentage in the interval [0.0%, 2.0%], else decrease the previous closing price by the same random percentage. Repeat this procedure for as many time steps as needed. Here is the plot of Acme’s stock price changes over 365 trading days: Here is the source code for generating the above plot: #Simulate the closing price of a companyclosing_price = 100.0#initialize pi_0pi_0=np.array([0.5, 0.5])#create a random delta in the range [0, 2.0]delta = random.random() * 2#generate a random number in the range [0.0, 1.0]r = random.random()#if r <= P(X_t = +1), increase the closing price by delta,#else decrease the closing price by deltaif r <= pi_0[0]: closing_price = closing_price*(100+delta)/100else: closing_price = math.max(closing_price*(100-delta)/100,1.0)#accumulate the new closing priceclosing_prices = [closing_price]P_mul=P.copy()T=365#now repeat this procedure 365 timesfor i in range(T): #calculate the i-step transition matrix P^i P_mul=np.matmul(P_mul,P) #multiply it by pi_0 to get the state probability for time i pi_t = np.matmul(pi_0,P_mul) # create a random delta in the range [0, 2.0] delta = random.random() * 2 # generate a random number in the range [0.0, 1.0] r = random.random() # if r <= P(X_t = +1), increase the closing price by delta, # else decrease the closing price by delta if r <= pi_t[0]: closing_price = math.max(closing_price*(100+delta)/100,1.0) else: closing_price = closing_price*(100-delta)/100 # accumulate the new closing price closing_prices.append(closing_price)#plot all the accumulated closing pricesfig = plt.figure()fig.suptitle('Closing price of Acme corporation simulated using a Markov process')plt.xlabel('time t')plt.ylabel('Closing price')plt.plot(range(T+1), closing_prices)plt.show() Here is the complete source code used in this article: All images in this article are copyright Sachin Date under CC-BY-NC-SA, unless a different source and copyright are mentioned underneath the image. Thanks for reading! If you liked this article, please follow me to receive tips, how-tos and programming advice on regression and time series analysis. Some rights reserved
[ { "code": null, "e": 515, "s": 172, "text": "A Discrete Time Markov Chain can be used to describe the behavior of a system that jumps from one state to another state with a certain probability, and this probability of transition to the next state depends only on what state the system is in currently, i.e. it does not depend on which states the system was in prior to the current state." }, { "code": null, "e": 657, "s": 515, "text": "The above definition pretty much sums up the long and short of what is a Discrete Time Markov Process or a Markov Chain as it’s often called." }, { "code": null, "e": 814, "s": 657, "text": "But the above description is deceptively simple. As we’ll see, even the simplest of Markov Chains can create richly interesting patterns of system behavior." }, { "code": null, "e": 900, "s": 814, "text": "In this article, we’ll use the terms Markov process and Markov chain interchangeably." }, { "code": null, "e": 1072, "s": 900, "text": "The Markov chain shown above has two states, or regimes as they are sometimes called: +1 and -1. There are four types of state transitions possible between the two states:" }, { "code": null, "e": 1140, "s": 1072, "text": "State +1 to state +1: This transition happens with probability p_11" }, { "code": null, "e": 1194, "s": 1140, "text": "State +1 to State -1 with transition probability p_12" }, { "code": null, "e": 1248, "s": 1194, "text": "State -1 to State +1 with transition probability p_21" }, { "code": null, "e": 1302, "s": 1248, "text": "State -1 to State -1 with transition probability p_22" }, { "code": null, "e": 1383, "s": 1302, "text": "The above figure is known as the state transition diagram of the Markov process." }, { "code": null, "e": 1586, "s": 1383, "text": "The following diagram shows another way to represent this Markov process. The X-axis is the time axis. The bubbles represent the different possible states that the process could be in at each time step." }, { "code": null, "e": 1807, "s": 1586, "text": "In reality, at each time step, the process will be in exactly one of the many possible states. In the following diagram, the black bubbles depict one such realization of the Markov process across 4 successive time steps:" }, { "code": null, "e": 1954, "s": 1807, "text": "There are many such realizations possible. In a 2-state Markov process, there are 2^N possible realizations of the Markov chain over N time steps." }, { "code": null, "e": 2084, "s": 1954, "text": "By illustrating the march of a Markov process along the time axis, we glean the following important property of a Markov process:" }, { "code": null, "e": 2159, "s": 2084, "text": "A realization of a Markov chain along the time dimension is a time series." }, { "code": null, "e": 2341, "s": 2159, "text": "In a 2-state Markov chain, there are four possible state transitions and the corresponding transition probabilities. We can represent them in a state transition matrix P as follows:" }, { "code": null, "e": 2428, "s": 2341, "text": "For a Markov chain over n-states (1,2,3,...,n), the transition matrix looks like this:" }, { "code": null, "e": 2500, "s": 2428, "text": "The state transition matrix has the following two important properties:" }, { "code": null, "e": 2555, "s": 2500, "text": "Since each element p_ij is a probability, 0 ≤ p_ij ≤ 1" }, { "code": null, "e": 2586, "s": 2555, "text": "Each row of P sums to 1.0 i.e." }, { "code": null, "e": 2844, "s": 2586, "text": "This is because the row index represents the source state at time t and the column index represents the destination state at time (t+1). If the process is in source state i at time t, at (t+1), it has to be in one of the allowed set of states (1,2,3,...,n)." }, { "code": null, "e": 2927, "s": 2844, "text": "Thus, we can restate the transition matrix of a 2-state Markov process as follows:" }, { "code": null, "e": 3222, "s": 2927, "text": "We will now introduce a random variable X_t. The suffix t in X_t denotes the time step. At each time step t, X_t takes a value from the state space [1,2,3,...,n] as per some probability distribution. One possible sequence of values that X_t could take is {X_0=1, X_1=3, X_2=4, X_3=0,...,X_t=k}." }, { "code": null, "e": 3395, "s": 3222, "text": "At time t, the probability that X_t takes some value j given that X_t had taken a value i at the previous time step (t-1) is given by the following conditional probability:" }, { "code": null, "e": 3444, "s": 3395, "text": "Indeed, this is the transition probability p_ij." }, { "code": null, "e": 3604, "s": 3444, "text": "The Markov property states that p_ij is independent of the state in which the system was at times (t-2), (t-3),...,0. The Markov property is stated as follows:" }, { "code": null, "e": 3944, "s": 3604, "text": "The state transition matrix P has this nice property by which if you multiply it with itself k times, then the matrix P^k contains the probabilities of all transitions that are k-steps long, i.e. the probability that system will be in state j after hopping through k number of transitions starting from state i, for i, j, in [1,2,3,...,n]." }, { "code": null, "e": 4041, "s": 3944, "text": "For example, consider the following transition probabilities matrix for a 2-step Markov process:" }, { "code": null, "e": 4104, "s": 4041, "text": "The 2-step transition probabilities are calculated as follows:" }, { "code": null, "e": 4230, "s": 4104, "text": "In P2, p_11=0.625 is the probability of returning to state 1 after having traversed through two states starting from state 1." }, { "code": null, "e": 4340, "s": 4230, "text": "Similarly, p_12=0.375 is the probability of reaching state 2 in exactly two time steps starting from state 1." }, { "code": null, "e": 4486, "s": 4340, "text": "These probabilities have factored in all possible ways of going from state 1 to state 1 (or state 1 to state 2, and so on) that are 2 steps long." }, { "code": null, "e": 4722, "s": 4486, "text": "We could continue multiplying P with itself forever to see how the n-step probabilities change over time. What would be more interesting is if we could know what is the unconditional probability distribution of X_t at each time step t." }, { "code": null, "e": 5128, "s": 4722, "text": "For example, in our 2-step Markov process example, at each time step t, what is the probability with which X_t could be +1 or -1? These probabilities constitute what is known as the state probability distribution of the Markov variable X_t at time t and it is denoted by π_t, (or δ_t). For example, for the 2-state Markov process consisting of states +1 and -1, the state distribution is given as follows:" }, { "code": null, "e": 5290, "s": 5128, "text": "An n-state Markov process that operates over the states [1,2,3,...,n] could be in any one of those n states at time t, so π_t is a vector of length n as follows:" }, { "code": null, "e": 5496, "s": 5290, "text": "In general, each element of π_t can be referenced using the notation π_jt. π_jt is indexed using two variables j and t, indicating the unconditional probability π of the process being in state j at time t:" }, { "code": null, "e": 5572, "s": 5496, "text": "Since π_t is a probability distribution, its elements always sum up to 1.0:" }, { "code": null, "e": 5734, "s": 5572, "text": "Typically, one assumes a certain value for π_0 which is the probability vector for state 0. And given π_0, it can be shown that π_t can be calculated as follows:" }, { "code": null, "e": 5997, "s": 5734, "text": "The idea behind computing π_t is to matrix-multiply the state transition matrix with itself t number of times to get the t-step transition probabilities, and multiply the t-step transition probabilities with the unconditional probability distribution π_0 at t=0." }, { "code": null, "e": 6055, "s": 5997, "text": "Notice the following two things about the above equation:" }, { "code": null, "e": 6132, "s": 6055, "text": "The state probability distribution of a Markov process at time t depends on:" }, { "code": null, "e": 6216, "s": 6132, "text": "The initial probability distribution π_0 at time t=0, andIt depends on time step t." }, { "code": null, "e": 6274, "s": 6216, "text": "The initial probability distribution π_0 at time t=0, and" }, { "code": null, "e": 6301, "s": 6274, "text": "It depends on time step t." }, { "code": null, "e": 6307, "s": 6301, "text": "Thus," }, { "code": null, "e": 6395, "s": 6307, "text": "The probability distribution of a Markov distributed random variable evolves over time." }, { "code": null, "e": 6463, "s": 6395, "text": "Let’s work through all the concepts learnt so far using an example." }, { "code": null, "e": 6552, "s": 6463, "text": "Suppose the stock of Acme Corporation increases or decreases as per the following rules:" }, { "code": null, "e": 6844, "s": 6552, "text": "As compared to the previous day’s closing price, the current day’s closing price is either higher or lower by some percentage points. For, e.g. on some day, Acme’s stock closes 2.3% higher than the previous day. On other days, it might close 0.8% lower than the previous day’s closing price." }, { "code": null, "e": 7134, "s": 6844, "text": "Given any sequence of 3 days denoted by ‘day before’, ‘yesterday’ and ‘today’, if Acme has closed higher yesterday than the day before, it will close higher today than yesterday with a probability p_11. Consequently, it would close lower today than yesterday with a probability (1 — p_11)." }, { "code": null, "e": 7381, "s": 7134, "text": "Let’s also assume that if Acme has closed lower yesterday than the day before, the probability that it would once again close lower today is p_22. And therefore, the probability that it would close higher today than it did yesterday is (1 — p22)." }, { "code": null, "e": 7520, "s": 7381, "text": "You may have guessed that Acme’s stock price can be modeled using a 2-state Markov process. It’s state transition diagram looks like this:" }, { "code": null, "e": 7580, "s": 7520, "text": "And it’s transition probabilities matrix P looks like this:" }, { "code": null, "e": 7798, "s": 7580, "text": "Now let’s pin down some sample values for these probabilities. Suppose the probability of Acme’s price’s moving up two days in a row is 0.6 and the chances of the price moving down for two days in a row is 0.25. Thus," }, { "code": null, "e": 7821, "s": 7798, "text": "p_11=0.6 and p_22=0.25" }, { "code": null, "e": 7845, "s": 7821, "text": "And therefore, we have:" }, { "code": null, "e": 7891, "s": 7845, "text": "p_12=1 — p_11 = 0.4, and, p_21=1 — p22 = 0.75" }, { "code": null, "e": 7951, "s": 7891, "text": "The state transition matrix for Acme’s stock is as follows:" }, { "code": null, "e": 8040, "s": 7951, "text": "The state transition diagram of the Markov process model for Acme’s stock is as follows:" }, { "code": null, "e": 8125, "s": 8040, "text": "We would now like to calculate the following unconditional probability distribution:" }, { "code": null, "e": 8427, "s": 8125, "text": "Let’s assume an initial value of π_0=[0.5,0.5], i.e. an equal probability of it’s closing higher (+1 state) or lower ( — 1 state) on listing day, as compared to the IPO price. If we repeatedly apply the formula for π_t=π_0*P^t, we will get the probability distribution vector π_t for each time step t." }, { "code": null, "e": 8469, "s": 8427, "text": "The following Python code calculates π_t:" }, { "code": null, "e": 8920, "s": 8469, "text": "import numpy as npfrom matplotlib import pyplot as plt#initialize the transition matrix PP=np.array([[0.6,0.4],[0.75,0.25]])#initialize pi_0pi_0=np.array([0.5, 0.5])#set up the array to accumulate the state probabilities at times t=1 to 10pi=[]pi.append(pi_0)P_mul=P.copy()#calculate the state probability for each t and store it away for i in range(10): P_mul=np.matmul(P_mul,P) pi_t = np.matmul(pi_0,P_mul) pi.append(pi_t)pi = np.array(pi)" }, { "code": null, "e": 9082, "s": 8920, "text": "The above code stores all the calculated π_t vectors in the array π. Let’s separately plot the components π_1t and π_2t of π_t= [ π_1t, π_2t] for t=1 through 10." }, { "code": null, "e": 9398, "s": 9082, "text": "#plot pi_1t = P(X_t = +1) versus tfig = plt.figure()fig.suptitle('Probability of closing higher than previous day\\'s close')plt.plot(range(len(pi)), pi[:,0])plt.show()#plot pi_2t = P(X_t = -1) versus tfig.suptitle('Probability of closing lower than previous day\\'s close')plt.plot(range(len(pi)), pi[:,1])plt.show()" }, { "code": null, "e": 9430, "s": 9398, "text": "We get the following two plots:" }, { "code": null, "e": 9593, "s": 9430, "text": "We see that in just a few time steps, the unconditional probabilities vector π_t= [ π_1t, π_2t] settles down into the steady state value [0.65217391, 0.34782609]." }, { "code": null, "e": 9714, "s": 9593, "text": "In fact, it can be shown that if a two state Markov process with the following transition matrix is run for ‘long time’:" }, { "code": null, "e": 9910, "s": 9714, "text": "Then the state probability distribution π_t steady-states to the following constant (limiting) probability distribution that is independent of both t and the initial probability distribution π_0:" }, { "code": null, "e": 10069, "s": 9910, "text": "Let’s simulate Acme Corp’s stock price movement at each time step t using the probability distribution π_t at time t. The simulation procedure goes like this:" }, { "code": null, "e": 10105, "s": 10069, "text": "Assume Acme’s IPO price to be $100." }, { "code": null, "e": 10188, "s": 10105, "text": "Set the initial probability distribution:π_0=[P(X_t = +1)=0.5, P(X_t = -1) = 0.5]." }, { "code": null, "e": 10329, "s": 10188, "text": "Map the +1 Markov state to the action of increasing Acme’s previous day’s closing price by a random percentage in the interval [0.0%, 2.0%]." }, { "code": null, "e": 10462, "s": 10329, "text": "Map the -1 Markov state to reducing Acme’s previous day’s closing price by a similar random percentage in the interval [0.0%, 2.0%]." }, { "code": null, "e": 10602, "s": 10462, "text": "At each time step t, calculate the state probability distribution π_t=[P(X_t = +1), P(X_t = -1) = 0.5], by using the formula π_t = π_0*P^t." }, { "code": null, "e": 10971, "s": 10602, "text": "Generate a uniformly distributed random number in the interval [0, 1.0]. If this number is less than or equal to π_1t = P(X_t = +1), increase the closing price from the previous time step by a random percentage in the interval [0.0%, 2.0%], else decrease the previous closing price by the same random percentage. Repeat this procedure for as many time steps as needed." }, { "code": null, "e": 11041, "s": 10971, "text": "Here is the plot of Acme’s stock price changes over 365 trading days:" }, { "code": null, "e": 11096, "s": 11041, "text": "Here is the source code for generating the above plot:" }, { "code": null, "e": 12605, "s": 11096, "text": "#Simulate the closing price of a companyclosing_price = 100.0#initialize pi_0pi_0=np.array([0.5, 0.5])#create a random delta in the range [0, 2.0]delta = random.random() * 2#generate a random number in the range [0.0, 1.0]r = random.random()#if r <= P(X_t = +1), increase the closing price by delta,#else decrease the closing price by deltaif r <= pi_0[0]: closing_price = closing_price*(100+delta)/100else: closing_price = math.max(closing_price*(100-delta)/100,1.0)#accumulate the new closing priceclosing_prices = [closing_price]P_mul=P.copy()T=365#now repeat this procedure 365 timesfor i in range(T): #calculate the i-step transition matrix P^i P_mul=np.matmul(P_mul,P) #multiply it by pi_0 to get the state probability for time i pi_t = np.matmul(pi_0,P_mul) # create a random delta in the range [0, 2.0] delta = random.random() * 2 # generate a random number in the range [0.0, 1.0] r = random.random() # if r <= P(X_t = +1), increase the closing price by delta, # else decrease the closing price by delta if r <= pi_t[0]: closing_price = math.max(closing_price*(100+delta)/100,1.0) else: closing_price = closing_price*(100-delta)/100 # accumulate the new closing price closing_prices.append(closing_price)#plot all the accumulated closing pricesfig = plt.figure()fig.suptitle('Closing price of Acme corporation simulated using a Markov process')plt.xlabel('time t')plt.ylabel('Closing price')plt.plot(range(T+1), closing_prices)plt.show()" }, { "code": null, "e": 12660, "s": 12605, "text": "Here is the complete source code used in this article:" }, { "code": null, "e": 12808, "s": 12660, "text": "All images in this article are copyright Sachin Date under CC-BY-NC-SA, unless a different source and copyright are mentioned underneath the image." }, { "code": null, "e": 12960, "s": 12808, "text": "Thanks for reading! If you liked this article, please follow me to receive tips, how-tos and programming advice on regression and time series analysis." } ]
JavaScript RegExp - [^a-zA-Z]
[^a-zA-Z] matches any string not containing any of the characters ranging from a through z and A through Z. Following example shows usage of RegExp expression. <html> <head> <title>JavaScript RegExp</title> </head> <body> <script type = "text/javascript"> var str = "1323pabc"; var pattern = /[^a-zA-Z]/g; var result = str.match(pattern); document.write("Test 1 - returned value : " + result); str = "abc"; result = str.match(pattern); document.write("<br/>Test 2 - returned value : " + result); </script> </body> </html> Test 1 - returned value : 1,3,2,3 Test 2 - returned value : null 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 3189, "s": 3081, "text": "[^a-zA-Z] matches any string not containing any of the characters ranging from a through z and A through Z." }, { "code": null, "e": 3241, "s": 3189, "text": "Following example shows usage of RegExp expression." }, { "code": null, "e": 3705, "s": 3241, "text": "<html>\n <head>\n <title>JavaScript RegExp</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n\t\t var str = \"1323pabc\";\n var pattern = /[^a-zA-Z]/g;\n\n var result = str.match(pattern);\n document.write(\"Test 1 - returned value : \" + result); \n\n str = \"abc\";\n result = str.match(pattern);\n document.write(\"<br/>Test 2 - returned value : \" + result); \t \t\t \n </script>\n </body>\n</html>" }, { "code": null, "e": 3771, "s": 3705, "text": "Test 1 - returned value : 1,3,2,3\nTest 2 - returned value : null\n" }, { "code": null, "e": 3806, "s": 3771, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3820, "s": 3806, "text": " Anadi Sharma" }, { "code": null, "e": 3854, "s": 3820, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3868, "s": 3854, "text": " Lets Kode It" }, { "code": null, "e": 3903, "s": 3868, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3920, "s": 3903, "text": " Frahaan Hussain" }, { "code": null, "e": 3955, "s": 3920, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3972, "s": 3955, "text": " Frahaan Hussain" }, { "code": null, "e": 4005, "s": 3972, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4033, "s": 4005, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4067, "s": 4033, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4095, "s": 4067, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4102, "s": 4095, "text": " Print" }, { "code": null, "e": 4113, "s": 4102, "text": " Add Notes" } ]
C++ Program to Calculate Average of Numbers Using Arrays
Average of numbers is calculated by adding all the numbers and then dividing the sum by count of numbers available. An example of this is as follows. The numbers whose average is to be calculated are: 10, 5, 32, 4, 9 Sum of numbers = 60 Average of numbers = 60/5 = 12 A program that calculates average of numbers using arrays is as follows. Live Demo #include <iostream> using namespace std; int main() { int n, i; float sum = 0.0, avg; float num[] = {12, 76, 23, 9, 5}; n = sizeof(num) / sizeof(num[0]); for(i = 0; i < n; i++) sum += num[i]; avg = sum / n; cout<<"Average of all array elements is "<<avg; return 0; } Average of all array elements is 25 In the above program, the numbers whose average is needed are stored in an array num[]. First the size of the array is found. This is done as shown below − n = sizeof(num) / sizeof(num[0]); Now a for loop is started from 0 to n-1. This loop adds all the elements of the array. The code snippet demonstrating this is as follows. for(i = 0; i < n; i++) sum += num[i]; The average of the numbers is obtained by dividing the sum by n i.e amount of numbers. This is shown below − avg = sum / n; Finally the average is displayed. This is given as follows. cout<<"Average of all array elements is "<<avg;
[ { "code": null, "e": 1178, "s": 1062, "text": "Average of numbers is calculated by adding all the numbers and then dividing the sum by count of numbers available." }, { "code": null, "e": 1212, "s": 1178, "text": "An example of this is as follows." }, { "code": null, "e": 1330, "s": 1212, "text": "The numbers whose average is to be calculated are:\n10, 5, 32, 4, 9\nSum of numbers = 60\nAverage of numbers = 60/5 = 12" }, { "code": null, "e": 1403, "s": 1330, "text": "A program that calculates average of numbers using arrays is as follows." }, { "code": null, "e": 1414, "s": 1403, "text": " Live Demo" }, { "code": null, "e": 1708, "s": 1414, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int n, i;\n float sum = 0.0, avg;\n float num[] = {12, 76, 23, 9, 5};\n n = sizeof(num) / sizeof(num[0]);\n for(i = 0; i < n; i++)\n sum += num[i];\n avg = sum / n;\n cout<<\"Average of all array elements is \"<<avg;\n return 0;\n}" }, { "code": null, "e": 1744, "s": 1708, "text": "Average of all array elements is 25" }, { "code": null, "e": 1900, "s": 1744, "text": "In the above program, the numbers whose average is needed are stored in an array num[]. First the size of the array is found. This is done as shown below −" }, { "code": null, "e": 1934, "s": 1900, "text": "n = sizeof(num) / sizeof(num[0]);" }, { "code": null, "e": 2072, "s": 1934, "text": "Now a for loop is started from 0 to n-1. This loop adds all the elements of the array. The code snippet demonstrating this is as follows." }, { "code": null, "e": 2110, "s": 2072, "text": "for(i = 0; i < n; i++)\nsum += num[i];" }, { "code": null, "e": 2219, "s": 2110, "text": "The average of the numbers is obtained by dividing the sum by n i.e amount of numbers. This is shown below −" }, { "code": null, "e": 2234, "s": 2219, "text": "avg = sum / n;" }, { "code": null, "e": 2294, "s": 2234, "text": "Finally the average is displayed. This is given as follows." }, { "code": null, "e": 2342, "s": 2294, "text": "cout<<\"Average of all array elements is \"<<avg;" } ]
Terminal Control Functions in Python
To change the terminal controls in the Unix system, we can use the tty related methods in Python. Using the tty module, we can set two different modes of the terminal. The raw Mode and the cbreak mode. To use the tty module, we should import it using − import tty There are some modules of the tty module, these are − This method is used to change the terminal mode to raw mode. In the raw mode, the cursor moves to new line but the carriage return operation is not performed. Also we do not need to press Return key to send the input into the system, it automatically sends after writing it. This method is used to change the terminal mode to cbreak mode. In this mode, the cursor moves to new line we do not need to press Return key to send the input into the system, it automatically sends after writing it. import sys import tty import termios file_desc = sys.stdin.fileno() old_setting = termios.tcgetattr(file_desc) tty.setraw(sys.stdin) for i in range(5): char = sys.stdin.read(1) print("Char: " + str(char)) termios.tcsetattr(file_desc, termios.TCSADRAIN, old_setting) $ python3 example.py Char: K Char: E Char: 5 Char: 2 Char: @
[ { "code": null, "e": 1264, "s": 1062, "text": "To change the terminal controls in the Unix system, we can use the tty related methods in Python. Using the tty module, we can set two different modes of the terminal. The raw Mode and the cbreak mode." }, { "code": null, "e": 1315, "s": 1264, "text": "To use the tty module, we should import it using −" }, { "code": null, "e": 1327, "s": 1315, "text": "import tty\n" }, { "code": null, "e": 1381, "s": 1327, "text": "There are some modules of the tty module, these are −" }, { "code": null, "e": 1656, "s": 1381, "text": "This method is used to change the terminal mode to raw mode. In the raw mode, the cursor moves to new line but the carriage return operation is not performed. Also we do not need to press Return key to send the input into the system, it automatically sends after writing it." }, { "code": null, "e": 1874, "s": 1656, "text": "This method is used to change the terminal mode to cbreak mode. In this mode, the cursor moves to new line we do not need to press Return key to send the input into the system, it automatically sends after writing it." }, { "code": null, "e": 2146, "s": 1874, "text": "import sys\nimport tty\nimport termios\nfile_desc = sys.stdin.fileno()\nold_setting = termios.tcgetattr(file_desc)\ntty.setraw(sys.stdin)\nfor i in range(5):\n char = sys.stdin.read(1)\n print(\"Char: \" + str(char))\ntermios.tcsetattr(file_desc, termios.TCSADRAIN, old_setting)" }, { "code": null, "e": 2272, "s": 2146, "text": "$ python3 example.py\nChar: K\n \n Char: E\n \n Char: 5\n \n Char: 2\n \n Char: @\n" } ]
C++ Program to Find Number of Articulation points in a Graph
Articulation Points (or Cut Vertices) in a Graph is a point iff removing it (and edges through it) disconnects the graph. An articulation point for a disconnected undirected graph, is a vertex removing which increases number of connected components. Begin We use dfs here to find articulation point: In DFS, a vertex w is articulation point if one of the following two conditions is satisfied. 1) w is root of DFS tree and it has at least two children. 2) w is not root of DFS tree and it has a child x such that no vertex in subtree rooted with w has a back edge to one of the ancestors of w in the tree. End #include<iostream> #include <list> #define N -1 using namespace std; class G { int n; list<int> *adj; //declaration of functions void APT(int v, bool visited[], int dis[], int low[], int par[], bool ap[]); public: G(int n); //constructor void addEd(int w, int x); void AP(); }; G::G(int n) { this->n = n; adj = new list<int>[n]; } //add edges to the graph void G::addEd(int w, int x) { adj[x].push_back(w); //add u to v's list adj[w].push_back(x); //add v to u's list } void G::APT(int w, bool visited[], int dis[], int low[], int par[], bool ap[]) { static int t=0; int child = 0; //initialize child count of dfs tree is 0. //mark current node as visited visited[w] = true; dis[w] = low[w] = ++t; list<int>::iterator i; //Go through all adjacent vertices for (i = adj[w].begin(); i != adj[w].end(); ++i) { int x = *i; //x is current adjacent if (!visited[x]) { child++; par[x] = w; APT(x, visited, dis, low, par, ap); low[w] = min(low[w], low[x]); // w is an articulation point in following cases : // w is root of DFS tree and has two or more chilren. if (par[w] == N && child> 1) ap[w] = true; // If w is not root and low value of one of its child is more than discovery value of w. if (par[w] != N && low[x] >= dis[w]) ap[w] = true; } else if (x != par[w]) //update low value low[w] = min(low[w], dis[x]); } } void G::AP() { // Mark all the vertices as unvisited bool *visited = new bool[n]; int *dis = new int[n]; int *low = new int[n]; int *par = new int[n]; bool *ap = new bool[n]; for (int i = 0; i < n; i++) { par[i] = N; visited[i] = false; ap[i] = false; } // Call the APT() function to find articulation points in DFS tree rooted with vertex 'i' for (int i = 0; i < n; i++) if (visited[i] == false) APT(i, visited, dis, low, par, ap); //print the articulation points for (int i = 0; i < n; i++) if (ap[i] == true) cout << i << " "; } int main() { cout << "\nArticulation points in first graph \n"; G g1(5); g1.addEd(1, 2); g1.addEd(3, 1); g1.addEd(0, 2); g1.addEd(2, 3); g1.addEd(0, 4); g1.AP(); return 0; } Articulation points in first graph 0 2
[ { "code": null, "e": 1312, "s": 1062, "text": "Articulation Points (or Cut Vertices) in a Graph is a point iff removing it (and edges through it) disconnects the graph. An articulation point for a disconnected undirected graph, is a vertex removing which increases number of connected components." }, { "code": null, "e": 1691, "s": 1312, "text": "Begin\n We use dfs here to find articulation point:\n In DFS, a vertex w is articulation point if one of the following two conditions is satisfied.\n 1) w is root of DFS tree and it has at least two children.\n 2) w is not root of DFS tree and it has a child x such that no vertex in subtree rooted with\n w has a back edge to one of the ancestors of w in the tree.\nEnd" }, { "code": null, "e": 4041, "s": 1691, "text": "#include<iostream>\n#include <list>\n#define N -1\nusing namespace std;\nclass G {\n int n;\n list<int> *adj;\n //declaration of functions\n void APT(int v, bool visited[], int dis[], int low[],\n int par[], bool ap[]);\n public:\n G(int n); //constructor\n void addEd(int w, int x);\n void AP();\n};\nG::G(int n) {\n this->n = n;\n adj = new list<int>[n];\n}\n//add edges to the graph\nvoid G::addEd(int w, int x) {\n adj[x].push_back(w); //add u to v's list\n adj[w].push_back(x); //add v to u's list\n}\nvoid G::APT(int w, bool visited[], int dis[], int low[], int par[], bool ap[]) {\n static int t=0;\n int child = 0; //initialize child count of dfs tree is 0.\n //mark current node as visited\n visited[w] = true;\n dis[w] = low[w] = ++t;\n list<int>::iterator i;\n //Go through all adjacent vertices\n for (i = adj[w].begin(); i != adj[w].end(); ++i) {\n int x = *i; //x is current adjacent\n if (!visited[x]) {\n child++;\n par[x] = w;\n APT(x, visited, dis, low, par, ap);\n low[w] = min(low[w], low[x]);\n // w is an articulation point in following cases :\n // w is root of DFS tree and has two or more chilren.\n if (par[w] == N && child> 1)\n ap[w] = true;\n // If w is not root and low value of one of its child is more than discovery value of w.\n if (par[w] != N && low[x] >= dis[w])\n ap[w] = true;\n } else if (x != par[w]) //update low value\n low[w] = min(low[w], dis[x]);\n }\n}\nvoid G::AP() {\n // Mark all the vertices as unvisited\n bool *visited = new bool[n];\n int *dis = new int[n];\n int *low = new int[n];\n int *par = new int[n];\n bool *ap = new bool[n];\n for (int i = 0; i < n; i++) {\n par[i] = N;\n visited[i] = false;\n ap[i] = false;\n }\n // Call the APT() function to find articulation points in DFS tree rooted with vertex 'i'\n for (int i = 0; i < n; i++)\n if (visited[i] == false)\n APT(i, visited, dis, low, par, ap);\n //print the articulation points\n for (int i = 0; i < n; i++)\n if (ap[i] == true)\n cout << i << \" \";\n}\nint main() {\n cout << \"\\nArticulation points in first graph \\n\";\n G g1(5);\n g1.addEd(1, 2);\n g1.addEd(3, 1);\n g1.addEd(0, 2);\n g1.addEd(2, 3);\n g1.addEd(0, 4);\n g1.AP();\n return 0;\n}" }, { "code": null, "e": 4080, "s": 4041, "text": "Articulation points in first graph\n0 2" } ]
Mockito - Verifying Behavior
Mockito can ensure whether a mock method is being called with reequired arguments or not. It is done using the verify() method. Take a look at the following code snippet. //test the add functionality Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not with same arguments. verify(calcService).add(10.0, 20.0); Step 1 − Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2 − Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ //return calcService.add(input1, input2); return input1 + input2; } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3 − Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito. File: MathApplicationTester.java import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00); //test the add functionality Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0); //verify the behavior verify(calcService).add(10.0, 20.0); } } Step 4 − Execute test cases Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5 − Verify the Result Compile the classes using javac compiler as follows − C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java Now run the Test Runner to see the result C:\Mockito_WORKSPACE>java TestRunner Verify the output. true Step 1 − Create an interface CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2 − Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ //return calcService.add(input1, input2); return input1 + input2; } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3 − Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito. File: MathApplicationTester.java import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00); //test the add functionality Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0); //verify the behavior verify(calcService).add(20.0, 30.0); } } Step 4 − Execute test cases Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5 − Verify the Result Compile the classes using javac compiler as follows − C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java Now run the Test Runner to see the result − C:\Mockito_WORKSPACE>java TestRunner Verify the output. testAdd(MathApplicationTester): Argument(s) are different! Wanted: calcService.add(20.0, 30.0); -> at MathApplicationTester.testAdd(MathApplicationTester.java:32) Actual invocation has different arguments: calcService.add(10.0, 20.0); -> at MathApplication.add(MathApplication.java:10) false 31 Lectures 43 mins Abhinav Manchanda Print Add Notes Bookmark this page
[ { "code": null, "e": 2151, "s": 1980, "text": "Mockito can ensure whether a mock method is being called with reequired arguments or not. It is done using the verify() method. Take a look at the following code snippet." }, { "code": null, "e": 2341, "s": 2151, "text": "//test the add functionality\nAssert.assertEquals(calcService.add(10.0, 20.0),30.0,0);\n\n//verify call to calcService is made or not with same arguments.\nverify(calcService).add(10.0, 20.0);\n" }, { "code": null, "e": 2429, "s": 2341, "text": "Step 1 − Create an interface called CalculatorService to provide mathematical functions" }, { "code": null, "e": 2458, "s": 2429, "text": "File: CalculatorService.java" }, { "code": null, "e": 2718, "s": 2458, "text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}" }, { "code": null, "e": 2776, "s": 2718, "text": "Step 2 − Create a JAVA class to represent MathApplication" }, { "code": null, "e": 2803, "s": 2776, "text": "File: MathApplication.java" }, { "code": null, "e": 3476, "s": 2803, "text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n //return calcService.add(input1, input2);\n return input1 + input2;\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}" }, { "code": null, "e": 3516, "s": 3476, "text": "Step 3 − Test the MathApplication class" }, { "code": null, "e": 3635, "s": 3516, "text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito." }, { "code": null, "e": 3668, "s": 3635, "text": "File: MathApplicationTester.java" }, { "code": null, "e": 4696, "s": 3668, "text": "import static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoJUnitRunner.class)\npublic class MathApplicationTester {\n\t\n //@InjectMocks annotation is used to create and inject the mock object\n @InjectMocks \n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test\n public void testAdd(){\n //add the behavior of calc service to add two numbers\n when(calcService.add(10.0,20.0)).thenReturn(30.00);\n\t\t\n //test the add functionality\n Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0);\n \n //verify the behavior\n verify(calcService).add(10.0, 20.0);\n }\n}" }, { "code": null, "e": 4724, "s": 4696, "text": "Step 4 − Execute test cases" }, { "code": null, "e": 4817, "s": 4724, "text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)." }, { "code": null, "e": 4839, "s": 4817, "text": "File: TestRunner.java" }, { "code": null, "e": 5280, "s": 4839, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 5307, "s": 5280, "text": "Step 5 − Verify the Result" }, { "code": null, "e": 5361, "s": 5307, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 5480, "s": 5361, "text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n" }, { "code": null, "e": 5522, "s": 5480, "text": "Now run the Test Runner to see the result" }, { "code": null, "e": 5560, "s": 5522, "text": "C:\\Mockito_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 5579, "s": 5560, "text": "Verify the output." }, { "code": null, "e": 5585, "s": 5579, "text": "true\n" }, { "code": null, "e": 5666, "s": 5585, "text": "Step 1 − Create an interface CalculatorService to provide mathematical functions" }, { "code": null, "e": 5695, "s": 5666, "text": "File: CalculatorService.java" }, { "code": null, "e": 5955, "s": 5695, "text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}" }, { "code": null, "e": 6013, "s": 5955, "text": "Step 2 − Create a JAVA class to represent MathApplication" }, { "code": null, "e": 6040, "s": 6013, "text": "File: MathApplication.java" }, { "code": null, "e": 6713, "s": 6040, "text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n //return calcService.add(input1, input2);\n return input1 + input2;\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}" }, { "code": null, "e": 6753, "s": 6713, "text": "Step 3 − Test the MathApplication class" }, { "code": null, "e": 6872, "s": 6753, "text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito." }, { "code": null, "e": 6905, "s": 6872, "text": "File: MathApplicationTester.java" }, { "code": null, "e": 7933, "s": 6905, "text": "import static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoJUnitRunner.class)\npublic class MathApplicationTester {\n\t\n //@InjectMocks annotation is used to create and inject the mock object\n @InjectMocks \n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test\n public void testAdd(){\n //add the behavior of calc service to add two numbers\n when(calcService.add(10.0,20.0)).thenReturn(30.00);\n\t\t\n //test the add functionality\n Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0);\n \n //verify the behavior\n verify(calcService).add(20.0, 30.0);\n }\n}" }, { "code": null, "e": 7961, "s": 7933, "text": "Step 4 − Execute test cases" }, { "code": null, "e": 8054, "s": 7961, "text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)." }, { "code": null, "e": 8076, "s": 8054, "text": "File: TestRunner.java" }, { "code": null, "e": 8517, "s": 8076, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 8544, "s": 8517, "text": "Step 5 − Verify the Result" }, { "code": null, "e": 8598, "s": 8544, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 8717, "s": 8598, "text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n" }, { "code": null, "e": 8761, "s": 8717, "text": "Now run the Test Runner to see the result −" }, { "code": null, "e": 8799, "s": 8761, "text": "C:\\Mockito_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 8818, "s": 8799, "text": "Verify the output." }, { "code": null, "e": 9113, "s": 8818, "text": "testAdd(MathApplicationTester): \nArgument(s) are different! Wanted:\ncalcService.add(20.0, 30.0);\n-> at MathApplicationTester.testAdd(MathApplicationTester.java:32)\nActual invocation has different arguments:\ncalcService.add(10.0, 20.0);\n-> at MathApplication.add(MathApplication.java:10)\n\nfalse\n" }, { "code": null, "e": 9145, "s": 9113, "text": "\n 31 Lectures \n 43 mins\n" }, { "code": null, "e": 9164, "s": 9145, "text": " Abhinav Manchanda" }, { "code": null, "e": 9171, "s": 9164, "text": " Print" }, { "code": null, "e": 9182, "s": 9171, "text": " Add Notes" } ]
Difference between find Element and find Elements in Selenium
There are differences between findElement and findElements method in Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method returns a list of matching elements. The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is thrown by the findElement, however an empty list is returned by the findElements method. A good usage of findElements method usage is counting the total number of images or accessing each of images by iterating with a loop. WebElement i = driver.findElement(By.id("img-loc")); List<WebElement> s = driver.findElements(By.tagName("img")); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class FindElementFindElementMthds{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java \\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm"); //identify single element WebElement elm = driver.findElement(By.tagName("h2")); String s = elm.getText(); System.out.println("Get text on element: " + s); //identify all elements with tagname List<WebElement> i = driver.findElements(By.tagName("img")); //count int c = i.size(); System.out.println("Number of images: " + c); //browser close driver.close(); } }
[ { "code": null, "e": 1320, "s": 1062, "text": "There are differences between findElement and findElements method in Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method returns a list of matching elements." }, { "code": null, "e": 1564, "s": 1320, "text": "The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is\nthrown by the findElement, however an empty list is returned by the findElements method." }, { "code": null, "e": 1699, "s": 1564, "text": "A good usage of findElements method usage is counting the total number of images or accessing each of images by iterating with a loop." }, { "code": null, "e": 1813, "s": 1699, "text": "WebElement i = driver.findElement(By.id(\"img-loc\"));\nList<WebElement> s =\ndriver.findElements(By.tagName(\"img\"));" }, { "code": null, "e": 2888, "s": 1813, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class FindElementFindElementMthds{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java \\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/upsc_ias_exams.htm\");\n //identify single element\n WebElement elm = driver.findElement(By.tagName(\"h2\"));\n String s = elm.getText();\n System.out.println(\"Get text on element: \" + s);\n //identify all elements with tagname\n List<WebElement> i = driver.findElements(By.tagName(\"img\"));\n //count\n int c = i.size();\n System.out.println(\"Number of images: \" + c);\n //browser close\n driver.close();\n }\n}" } ]
Return Array from Functions in C++
C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index. If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example − int * myFunction() { . . . } Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable. Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows − #include <iostream> #include <ctime> using namespace std; // function to generate and retrun random numbers. int * getRandom( ) { static int r[10]; // set the seed srand( (unsigned)time( NULL ) ); for (int i = 0; i < 10; ++i) { r[i] = rand(); cout << r[i] << endl; } return r; } // main function to call above defined function. int main () { // a pointer to an int. int *p; p = getRandom(); for ( int i = 0; i < 10; i++ ) { cout << "*(p + " << i << ") : "; cout << *(p + i) << endl; } return 0; } When the above code is compiled together and executed, it produces result something as follows − 624723190 1468735695 807113585 976495677 613357504 1377296355 1530315259 1778906708 1820354158 667126415 *(p + 0) : 624723190 *(p + 1) : 1468735695 *(p + 2) : 807113585 *(p + 3) : 976495677 *(p + 4) : 613357504 *(p + 5) : 1377296355 *(p + 6) : 1530315259 *(p + 7) : 1778906708 *(p + 8) : 1820354158 *(p + 9) : 667126415 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2318, "text": "C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index." }, { "code": null, "e": 2639, "s": 2488, "text": "If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example −" }, { "code": null, "e": 2678, "s": 2639, "text": "int * myFunction() {\n .\n .\n .\n}\n" }, { "code": null, "e": 2869, "s": 2678, "text": "Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable." }, { "code": null, "e": 3012, "s": 2869, "text": "Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows −" }, { "code": null, "e": 3587, "s": 3012, "text": "#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\n// function to generate and retrun random numbers.\nint * getRandom( ) {\n\n static int r[10];\n\n // set the seed\n srand( (unsigned)time( NULL ) );\n \n for (int i = 0; i < 10; ++i) {\n r[i] = rand();\n cout << r[i] << endl;\n }\n\n return r;\n}\n\n// main function to call above defined function.\nint main () {\n\n // a pointer to an int.\n int *p;\n\n p = getRandom();\n \n for ( int i = 0; i < 10; i++ ) {\n cout << \"*(p + \" << i << \") : \";\n cout << *(p + i) << endl;\n }\n\n return 0;\n}" }, { "code": null, "e": 3684, "s": 3587, "text": "When the above code is compiled together and executed, it produces result something as follows −" }, { "code": null, "e": 4005, "s": 3684, "text": "624723190\n1468735695\n807113585\n976495677\n613357504\n1377296355\n1530315259\n1778906708\n1820354158\n667126415\n*(p + 0) : 624723190\n*(p + 1) : 1468735695\n*(p + 2) : 807113585\n*(p + 3) : 976495677\n*(p + 4) : 613357504\n*(p + 5) : 1377296355\n*(p + 6) : 1530315259\n*(p + 7) : 1778906708\n*(p + 8) : 1820354158\n*(p + 9) : 667126415\n" }, { "code": null, "e": 4042, "s": 4005, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4061, "s": 4042, "text": " Arnab Chakraborty" }, { "code": null, "e": 4093, "s": 4061, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4116, "s": 4093, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4152, "s": 4116, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4169, "s": 4152, "text": " Frahaan Hussain" }, { "code": null, "e": 4204, "s": 4169, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4221, "s": 4204, "text": " Frahaan Hussain" }, { "code": null, "e": 4256, "s": 4221, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4273, "s": 4256, "text": " Frahaan Hussain" }, { "code": null, "e": 4308, "s": 4273, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4325, "s": 4308, "text": " Frahaan Hussain" }, { "code": null, "e": 4332, "s": 4325, "text": " Print" }, { "code": null, "e": 4343, "s": 4332, "text": " Add Notes" } ]
Repeating only even numbers inside an array in JavaScript
We are required to write a JavaScript function that should repeat the even number inside the same array. For example, given the following array − const arr = [1, 2, 5, 6, 8]; We should get the output − const output = [1, 2, 2, 5, 6, 6, 8, 8]; Therefore, let’s write the code for this function − The code for this will be − const arr = [1, 2, 5, 6, 8]; const repeatEvenNumbers = arr => { let end = arr.length -1; for(let i = end; i > 0; i--){ if(arr[i] % 2 === 0){ arr.splice(i, 0, arr[i]); }; }; return arr; }; console.log(repeatEvenNumbers(arr)); The output in the console will be − [ 1, 2, 2, 5, 6, 6, 8, 8 ]
[ { "code": null, "e": 1167, "s": 1062, "text": "We are required to write a JavaScript function that should repeat the even number inside the\nsame array." }, { "code": null, "e": 1208, "s": 1167, "text": "For example, given the following array −" }, { "code": null, "e": 1237, "s": 1208, "text": "const arr = [1, 2, 5, 6, 8];" }, { "code": null, "e": 1264, "s": 1237, "text": "We should get the output −" }, { "code": null, "e": 1305, "s": 1264, "text": "const output = [1, 2, 2, 5, 6, 6, 8, 8];" }, { "code": null, "e": 1357, "s": 1305, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1385, "s": 1357, "text": "The code for this will be −" }, { "code": null, "e": 1643, "s": 1385, "text": "const arr = [1, 2, 5, 6, 8];\nconst repeatEvenNumbers = arr => {\n let end = arr.length -1;\n for(let i = end; i > 0; i--){\n if(arr[i] % 2 === 0){\n arr.splice(i, 0, arr[i]);\n };\n };\n return arr;\n};\nconsole.log(repeatEvenNumbers(arr));" }, { "code": null, "e": 1679, "s": 1643, "text": "The output in the console will be −" }, { "code": null, "e": 1712, "s": 1679, "text": "[\n 1, 2, 2, 5,\n 6, 6, 8, 8\n]" } ]
HTML <area> coords Attribute
The cords attribute of the <area> element is used to set the coordinates of area in image map. Use the attribute with shape attribute and set the size & shape of an area. Following is the syntax <area coords="value"> Under the value above, you can set the following coordinates with different parameters − Let us now see an example to implement the cords attribute of the <area> element − Live Demo <!DOCTYPE html> <html> <body> <h2>Learning</h2> <p>Learn these technologies with ease....</p> <img src = /images/usemap.gif alt = "usemap" border = "0" usemap = "#tutorials"/> <map name = "tutorials"> <area shape = "poly" coords = "74,0,113,29,98,72,52,72,38,27" href = "/perl/index.htm" alt = "Perl Tutorial" target = "_blank" /> <area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial" href = "/html/index.htm" target = "_blank" /> <area shape = "circle" coords = "73,168,32" alt = "PHP Tutorial" href = "/php/index.htm" target = "_blank" /> </map> </body> </html> In the above example, we have set the map on the following image − <img src = /images/usemap.gif alt = "usemap" border = "0" usemap = "#tutorials"/> Now, we have set the map and area within it for shape − <map name = "tutorials"> <area shape = "poly" coords = "74,0,113,29,98,72,52,72,38,27" href = "/perl/index.htm" alt = "Perl Tutorial" target = "_blank" /> <area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial" href = "/html/index.htm" target = "_blank" /> <area shape = "circle" coords = "73,168,32" alt = "PHP Tutorial" href = "/php/index.htm" target = "_blank" /> </map> While setting the area, we have set the coordinates of the area with the cords attribute − <area shape = "rect" coords = "22,83,126,125" alt = "HTML Tutorial" href = "/html/index.htm" target = "_blank" />
[ { "code": null, "e": 1233, "s": 1062, "text": "The cords attribute of the <area> element is used to set the coordinates of area in image map. Use the attribute with shape attribute and set the size & shape of an area." }, { "code": null, "e": 1257, "s": 1233, "text": "Following is the syntax" }, { "code": null, "e": 1279, "s": 1257, "text": "<area coords=\"value\">" }, { "code": null, "e": 1368, "s": 1279, "text": "Under the value above, you can set the following coordinates with different parameters −" }, { "code": null, "e": 1451, "s": 1368, "text": "Let us now see an example to implement the cords attribute of the <area> element −" }, { "code": null, "e": 1462, "s": 1451, "text": " Live Demo" }, { "code": null, "e": 2067, "s": 1462, "text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Learning</h2>\n<p>Learn these technologies with ease....</p>\n<img src = /images/usemap.gif alt = \"usemap\" border = \"0\" usemap = \"#tutorials\"/>\n<map name = \"tutorials\">\n <area shape = \"poly\" coords = \"74,0,113,29,98,72,52,72,38,27\"\n href = \"/perl/index.htm\" alt = \"Perl Tutorial\" target = \"_blank\" />\n <area shape = \"rect\" coords = \"22,83,126,125\" alt = \"HTML Tutorial\"\n href = \"/html/index.htm\" target = \"_blank\" />\n <area shape = \"circle\" coords = \"73,168,32\" alt = \"PHP Tutorial\"\n href = \"/php/index.htm\" target = \"_blank\" />\n</map>\n</body>\n</html>" }, { "code": null, "e": 2134, "s": 2067, "text": "In the above example, we have set the map on the following image −" }, { "code": null, "e": 2216, "s": 2134, "text": "<img src = /images/usemap.gif alt = \"usemap\" border = \"0\" usemap = \"#tutorials\"/>" }, { "code": null, "e": 2272, "s": 2216, "text": "Now, we have set the map and area within it for shape −" }, { "code": null, "e": 2685, "s": 2272, "text": "<map name = \"tutorials\">\n <area shape = \"poly\" coords = \"74,0,113,29,98,72,52,72,38,27\"\n href = \"/perl/index.htm\" alt = \"Perl Tutorial\" target = \"_blank\" />\n <area shape = \"rect\" coords = \"22,83,126,125\" alt = \"HTML Tutorial\"\n href = \"/html/index.htm\" target = \"_blank\" />\n <area shape = \"circle\" coords = \"73,168,32\" alt = \"PHP Tutorial\"\n href = \"/php/index.htm\" target = \"_blank\" />\n</map>" }, { "code": null, "e": 2776, "s": 2685, "text": "While setting the area, we have set the coordinates of the area with the cords attribute −" }, { "code": null, "e": 2893, "s": 2776, "text": "<area shape = \"rect\" coords = \"22,83,126,125\" alt = \"HTML Tutorial\"\n href = \"/html/index.htm\" target = \"_blank\" />" } ]
Balanced expression with replacement - GeeksforGeeks
10 Jun, 2021 Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Prerequisite: Balanced Parenthesis Expression Examples: Input : S = "{(X[X])}" Output : Balanced The balanced expression after replacing X with suitable bracket is: {([[]])}. Input : [{X}(X)] Output : Not balanced No substitution of X with any bracket results in a balanced expression. Approach: We have discussed a solution on verifying whether given parenthesis expression is balanced or not. Following the same approach described in the article, a stack data structure is used for verifying whether given expression is balanced or not. For each type of character in string, the operations to be performed on stack are: ‘{‘ or ‘(‘ or ‘[‘ : When current element of string is an opening bracket, push the element in stack.‘}’ or ‘]’ or ‘)’ : When current element of string is a closing bracket, pop the top element of the stack and check if it is a matching opening bracket for the closing bracket or not. If it is matching, then move to next element of string. If it is not, then current string is not balanced. It is also possible that the element popped from stack is ‘X’. In that case ‘X’ is a matching opening bracket because it is pushed in stack only when it is assumed to be an opening bracket as described in next step.‘X’ : When current element is X then it can either be a starting bracket or a closing bracket. First assume that it is a starting bracket and recursively call for next element by pushing X in stack. If the result of recursion is false then X is a closing bracket which matches the bracket at top of the stack (If stack is non-empty). So pop the top element and recursively call for next element. If the result of recursion is again false, then the expression is not balanced. ‘{‘ or ‘(‘ or ‘[‘ : When current element of string is an opening bracket, push the element in stack. ‘}’ or ‘]’ or ‘)’ : When current element of string is a closing bracket, pop the top element of the stack and check if it is a matching opening bracket for the closing bracket or not. If it is matching, then move to next element of string. If it is not, then current string is not balanced. It is also possible that the element popped from stack is ‘X’. In that case ‘X’ is a matching opening bracket because it is pushed in stack only when it is assumed to be an opening bracket as described in next step. ‘X’ : When current element is X then it can either be a starting bracket or a closing bracket. First assume that it is a starting bracket and recursively call for next element by pushing X in stack. If the result of recursion is false then X is a closing bracket which matches the bracket at top of the stack (If stack is non-empty). So pop the top element and recursively call for next element. If the result of recursion is again false, then the expression is not balanced. Also check for the case when stack is empty and current element is a closing bracket. In that case, the expression is not balanced. Implementation: C++ Java Python3 C# Javascript // C++ program to determine whether given// expression is balanced/ parenthesis// expression or not.#include <bits/stdc++.h>using namespace std; // Function to check if two brackets are matching// or not.int isMatching(char a, char b){ if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0;} // Recursive function to check if given expression// is balanced or not.int isBalanced(string s, stack<char> ele, int ind){ // Base case. // If the string is balanced then all the opening // brackets had been popped and stack should be // empty after string is traversed completely. if (ind == s.length()) return ele.empty(); // variable to store element at the top of the stack. char topEle; // variable to store result of recursive call. int res; // Case 1: When current element is an opening bracket // then push that element in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element is a closing bracket // then check for matching bracket at the top of the // stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there is no matching opening // bracket for current closing bracket and the // expression is not balanced. if (ele.empty()) return 0; topEle = ele.top(); ele.pop(); // Check bracket is matching or not. if (!isMatching(topEle, s[ind])) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element is 'X' then check // for both the cases when 'X' could be opening // or closing bracket. else if (s[ind] == 'X') { stack<char> tmp = ele; tmp.push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res) return 1; if (ele.empty()) return 0; ele.pop(); return isBalanced(s, ele, ind + 1); }} int main(){ string s = "{(X}[]"; stack<char> ele; if (isBalanced(s, ele, 0)) cout << "Balanced"; else cout << "Not Balanced"; return 0;} // Java program to determine// whether given expression// is balanced/ parenthesis// expression or not.import java.util.Stack; class GFG { // Function to check if two // brackets are matching or not. static int isMatching(char a, char b) { if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') { return 1; } return 0; } // Recursive function to // check if given expression // is balanced or not. static int isBalanced(String s, Stack<Character> ele, int ind) { // Base case. // If the string is balanced // then all the opening brackets // had been popped and stack // should be empty after string // is traversed completely. if (ind == s.length()) { if (ele.size() == 0) { return 1; } else { return 0; } } // variable to store element // at the top of the stack. char topEle; // variable to store result // of recursive call. int res; // Case 1: When current element // is an opening bracket // then push that element // in the stack. if (s.charAt(ind) == '{' || s.charAt(ind) == '(' || s.charAt(ind) == '[') { ele.push(s.charAt(ind)); return isBalanced(s, ele, ind + 1); } // Case 2: When current element // is a closing bracket then // check for matching bracket // at the top of the stack. else if (s.charAt(ind) == '}' || s.charAt(ind) == ')' || s.charAt(ind) == ']') { // If stack is empty then there // is no matching opening bracket // for current closing bracket and // the expression is not balanced. if (ele.size() == 0) { return 0; } topEle = ele.peek(); ele.pop(); // Check bracket is // matching or not. if (isMatching(topEle, s.charAt(ind)) == 0) { return 0; } return isBalanced(s, ele, ind + 1); } // Case 3: If current element // is 'X' then check for both // the cases when 'X' could be // opening or closing bracket. else if (s.charAt(ind) == 'X') { Stack<Character> tmp = new Stack<>(); //because in java, direct assignment copies only reference and not the whole object tmp.addAll(ele); tmp.push(s.charAt(ind)); res = isBalanced(s, tmp, ind + 1); if (res == 1) { return 1; } if (ele.size() == 0) { return 0; } ele.pop(); return isBalanced(s, ele, ind + 1); } return 1; } // Driver Code public static void main(String[] args) { String s = "{(X}[]"; Stack<Character> ele = new Stack<Character>(); if (isBalanced(s, ele, 0) != 0) { System.out.println("Balanced"); } else { System.out.println("Not Balanced"); } }} # Python3 program to determine whether# given expression is balanced/ parenthesis# expression or not. # Function to check if two brackets are# matching or not.def isMatching(a, b): if ((a == '{' and b == '}') or (a == '[' and b == ']') or (a == '(' and b == ')') or a == 'X'): return 1 return 0 # Recursive function to check if given# expression is balanced or not.def isBalanced(s, ele, ind): # Base case. # If the string is balanced then all the # opening brackets had been popped and # stack should be empty after string is # traversed completely. if (ind == len(s)): if len(ele) == 0: return True else: return False # Variable to store element at the top # of the stack. # char topEle; # Variable to store result of # recursive call. # int res; # Case 1: When current element is an # opening bracket then push that # element in the stack. if (s[ind] == '{' or s[ind] == '(' or s[ind] == '['): ele.append(s[ind]) return isBalanced(s, ele, ind + 1) # Case 2: When current element is a closing # bracket then check for matching bracket # at the top of the stack. elif (s[ind] == '}' or s[ind] == ')' or s[ind] == ']'): # If stack is empty then there is no matching # opening bracket for current closing bracket # and the expression is not balanced. if (len(ele) == 0): return 0 topEle = ele[-1] ele.pop() # Check bracket is matching or not. if (isMatching(topEle, s[ind]) == 0): return 0 return isBalanced(s, ele, ind + 1) # Case 3: If current element is 'X' then check # for both the cases when 'X' could be opening # or closing bracket. elif (s[ind] == 'X'): tmp = ele tmp.append(s[ind]) res = isBalanced(s, tmp, ind + 1) if (res): return 1 if (len(ele) == 0): return 0 ele.pop() return isBalanced(s, ele, ind + 1) # Driver Codes = "{(X}[]"ele = [] if (isBalanced(s, ele, 0)): print("Balanced")else: print("Not Balanced") # This code is contributed by divyeshrabadiya07 // C# program to determine// whether given expression// is balanced/ parenthesis// expression or not.using System;using System.Collections.Generic; class GFG{ // Function to check if two // brackets are matching or not. static int isMatching(char a, char b) { if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0; } // Recursive function to // check if given expression // is balanced or not. static int isBalanced(string s, Stack<char> ele, int ind) { // Base case. // If the string is balanced // then all the opening brackets // had been popped and stack // should be empty after string // is traversed completely. if (ind == s.Length) { if (ele.Count == 0) return 1; else return 0; } // variable to store element // at the top of the stack. char topEle; // variable to store result // of recursive call. int res; // Case 1: When current element // is an opening bracket // then push that element // in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.Push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element // is a closing bracket then // check for matching bracket // at the top of the stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there // is no matching opening bracket // for current closing bracket and // the expression is not balanced. if (ele.Count == 0) return 0; topEle = ele.Peek(); ele.Pop(); // Check bracket is // matching or not. if (isMatching(topEle, s[ind]) == 0) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element // is 'X' then check for both // the cases when 'X' could be // opening or closing bracket. else if (s[ind] == 'X') { Stack<char> tmp = ele; tmp.Push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res == 1) return 1; if (ele.Count == 0) return 0; ele.Pop(); return isBalanced(s, ele, ind + 1); } return 1; } // Driver Code static void Main() { string s = "{(X}[]"; Stack<char> ele = new Stack<char>(); if (isBalanced(s, ele, 0) != 0) Console.Write("Balanced"); else Console.Write("Not Balanced"); }} // This code is contributed by// Manish Shaw(manishshaw1) <script> // JavaScript program to determine whether given// expression is balanced/ parenthesis// expression or not. // Function to check if two brackets are matching// or not.function isMatching(a, b){ if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0;} // Recursive function to check if given expression// is balanced or not.function isBalanced(s, ele, ind){ // Base case. // If the string is balanced then all the opening // brackets had been popped and stack should be // empty after string is traversed completely. if (ind == s.length) return ele.length==0; // variable to store element at the top of the stack. var topEle; // variable to store result of recursive call. var res; // Case 1: When current element is an opening bracket // then push that element in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element is a closing bracket // then check for matching bracket at the top of the // stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there is no matching opening // bracket for current closing bracket and the // expression is not balanced. if (ele.length==0) return 0; topEle = ele[ele.length-1]; ele.pop(); // Check bracket is matching or not. if (!isMatching(topEle, s[ind])) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element is 'X' then check // for both the cases when 'X' could be opening // or closing bracket. else if (s[ind] == 'X') { var tmp = ele; tmp.push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res) return 1; if (ele.length==0) return 0; ele.pop(); return isBalanced(s, ele, ind + 1); }} var s = "{(X}[]";var ele = [];if (isBalanced(s, ele, 0)) document.write( "Balanced"); else document.write( "Not Balanced"); </script> Balanced Time Complexity: O((2^n)*n) Auxiliary Space: O(N) manishshaw1 princiraj1992 msvsk divyeshrabadiya07 rutvik_56 Stack Strings Technical Scripter Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Real-time application of Data Structures Sort a stack using a temporary stack Iterative Tower of Hanoi Reverse individual words ZigZag Tree Traversal Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 24686, "s": 24658, "text": "\n10 Jun, 2021" }, { "code": null, "e": 24935, "s": 24686, "text": "Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence." }, { "code": null, "e": 24981, "s": 24935, "text": "Prerequisite: Balanced Parenthesis Expression" }, { "code": null, "e": 24992, "s": 24981, "text": "Examples: " }, { "code": null, "e": 25224, "s": 24992, "text": "Input : S = \"{(X[X])}\"\nOutput : Balanced\nThe balanced expression after \nreplacing X with suitable bracket is:\n{([[]])}.\n\nInput : [{X}(X)]\nOutput : Not balanced\nNo substitution of X with any bracket\nresults in a balanced expression." }, { "code": null, "e": 25561, "s": 25224, "text": "Approach: We have discussed a solution on verifying whether given parenthesis expression is balanced or not. Following the same approach described in the article, a stack data structure is used for verifying whether given expression is balanced or not. For each type of character in string, the operations to be performed on stack are: " }, { "code": null, "e": 26643, "s": 25561, "text": "‘{‘ or ‘(‘ or ‘[‘ : When current element of string is an opening bracket, push the element in stack.‘}’ or ‘]’ or ‘)’ : When current element of string is a closing bracket, pop the top element of the stack and check if it is a matching opening bracket for the closing bracket or not. If it is matching, then move to next element of string. If it is not, then current string is not balanced. It is also possible that the element popped from stack is ‘X’. In that case ‘X’ is a matching opening bracket because it is pushed in stack only when it is assumed to be an opening bracket as described in next step.‘X’ : When current element is X then it can either be a starting bracket or a closing bracket. First assume that it is a starting bracket and recursively call for next element by pushing X in stack. If the result of recursion is false then X is a closing bracket which matches the bracket at top of the stack (If stack is non-empty). So pop the top element and recursively call for next element. If the result of recursion is again false, then the expression is not balanced." }, { "code": null, "e": 26744, "s": 26643, "text": "‘{‘ or ‘(‘ or ‘[‘ : When current element of string is an opening bracket, push the element in stack." }, { "code": null, "e": 27251, "s": 26744, "text": "‘}’ or ‘]’ or ‘)’ : When current element of string is a closing bracket, pop the top element of the stack and check if it is a matching opening bracket for the closing bracket or not. If it is matching, then move to next element of string. If it is not, then current string is not balanced. It is also possible that the element popped from stack is ‘X’. In that case ‘X’ is a matching opening bracket because it is pushed in stack only when it is assumed to be an opening bracket as described in next step." }, { "code": null, "e": 27727, "s": 27251, "text": "‘X’ : When current element is X then it can either be a starting bracket or a closing bracket. First assume that it is a starting bracket and recursively call for next element by pushing X in stack. If the result of recursion is false then X is a closing bracket which matches the bracket at top of the stack (If stack is non-empty). So pop the top element and recursively call for next element. If the result of recursion is again false, then the expression is not balanced." }, { "code": null, "e": 27859, "s": 27727, "text": "Also check for the case when stack is empty and current element is a closing bracket. In that case, the expression is not balanced." }, { "code": null, "e": 27876, "s": 27859, "text": "Implementation: " }, { "code": null, "e": 27880, "s": 27876, "text": "C++" }, { "code": null, "e": 27885, "s": 27880, "text": "Java" }, { "code": null, "e": 27893, "s": 27885, "text": "Python3" }, { "code": null, "e": 27896, "s": 27893, "text": "C#" }, { "code": null, "e": 27907, "s": 27896, "text": "Javascript" }, { "code": "// C++ program to determine whether given// expression is balanced/ parenthesis// expression or not.#include <bits/stdc++.h>using namespace std; // Function to check if two brackets are matching// or not.int isMatching(char a, char b){ if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0;} // Recursive function to check if given expression// is balanced or not.int isBalanced(string s, stack<char> ele, int ind){ // Base case. // If the string is balanced then all the opening // brackets had been popped and stack should be // empty after string is traversed completely. if (ind == s.length()) return ele.empty(); // variable to store element at the top of the stack. char topEle; // variable to store result of recursive call. int res; // Case 1: When current element is an opening bracket // then push that element in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element is a closing bracket // then check for matching bracket at the top of the // stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there is no matching opening // bracket for current closing bracket and the // expression is not balanced. if (ele.empty()) return 0; topEle = ele.top(); ele.pop(); // Check bracket is matching or not. if (!isMatching(topEle, s[ind])) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element is 'X' then check // for both the cases when 'X' could be opening // or closing bracket. else if (s[ind] == 'X') { stack<char> tmp = ele; tmp.push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res) return 1; if (ele.empty()) return 0; ele.pop(); return isBalanced(s, ele, ind + 1); }} int main(){ string s = \"{(X}[]\"; stack<char> ele; if (isBalanced(s, ele, 0)) cout << \"Balanced\"; else cout << \"Not Balanced\"; return 0;}", "e": 30168, "s": 27907, "text": null }, { "code": "// Java program to determine// whether given expression// is balanced/ parenthesis// expression or not.import java.util.Stack; class GFG { // Function to check if two // brackets are matching or not. static int isMatching(char a, char b) { if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') { return 1; } return 0; } // Recursive function to // check if given expression // is balanced or not. static int isBalanced(String s, Stack<Character> ele, int ind) { // Base case. // If the string is balanced // then all the opening brackets // had been popped and stack // should be empty after string // is traversed completely. if (ind == s.length()) { if (ele.size() == 0) { return 1; } else { return 0; } } // variable to store element // at the top of the stack. char topEle; // variable to store result // of recursive call. int res; // Case 1: When current element // is an opening bracket // then push that element // in the stack. if (s.charAt(ind) == '{' || s.charAt(ind) == '(' || s.charAt(ind) == '[') { ele.push(s.charAt(ind)); return isBalanced(s, ele, ind + 1); } // Case 2: When current element // is a closing bracket then // check for matching bracket // at the top of the stack. else if (s.charAt(ind) == '}' || s.charAt(ind) == ')' || s.charAt(ind) == ']') { // If stack is empty then there // is no matching opening bracket // for current closing bracket and // the expression is not balanced. if (ele.size() == 0) { return 0; } topEle = ele.peek(); ele.pop(); // Check bracket is // matching or not. if (isMatching(topEle, s.charAt(ind)) == 0) { return 0; } return isBalanced(s, ele, ind + 1); } // Case 3: If current element // is 'X' then check for both // the cases when 'X' could be // opening or closing bracket. else if (s.charAt(ind) == 'X') { Stack<Character> tmp = new Stack<>(); //because in java, direct assignment copies only reference and not the whole object tmp.addAll(ele); tmp.push(s.charAt(ind)); res = isBalanced(s, tmp, ind + 1); if (res == 1) { return 1; } if (ele.size() == 0) { return 0; } ele.pop(); return isBalanced(s, ele, ind + 1); } return 1; } // Driver Code public static void main(String[] args) { String s = \"{(X}[]\"; Stack<Character> ele = new Stack<Character>(); if (isBalanced(s, ele, 0) != 0) { System.out.println(\"Balanced\"); } else { System.out.println(\"Not Balanced\"); } }}", "e": 33426, "s": 30168, "text": null }, { "code": "# Python3 program to determine whether# given expression is balanced/ parenthesis# expression or not. # Function to check if two brackets are# matching or not.def isMatching(a, b): if ((a == '{' and b == '}') or (a == '[' and b == ']') or (a == '(' and b == ')') or a == 'X'): return 1 return 0 # Recursive function to check if given# expression is balanced or not.def isBalanced(s, ele, ind): # Base case. # If the string is balanced then all the # opening brackets had been popped and # stack should be empty after string is # traversed completely. if (ind == len(s)): if len(ele) == 0: return True else: return False # Variable to store element at the top # of the stack. # char topEle; # Variable to store result of # recursive call. # int res; # Case 1: When current element is an # opening bracket then push that # element in the stack. if (s[ind] == '{' or s[ind] == '(' or s[ind] == '['): ele.append(s[ind]) return isBalanced(s, ele, ind + 1) # Case 2: When current element is a closing # bracket then check for matching bracket # at the top of the stack. elif (s[ind] == '}' or s[ind] == ')' or s[ind] == ']'): # If stack is empty then there is no matching # opening bracket for current closing bracket # and the expression is not balanced. if (len(ele) == 0): return 0 topEle = ele[-1] ele.pop() # Check bracket is matching or not. if (isMatching(topEle, s[ind]) == 0): return 0 return isBalanced(s, ele, ind + 1) # Case 3: If current element is 'X' then check # for both the cases when 'X' could be opening # or closing bracket. elif (s[ind] == 'X'): tmp = ele tmp.append(s[ind]) res = isBalanced(s, tmp, ind + 1) if (res): return 1 if (len(ele) == 0): return 0 ele.pop() return isBalanced(s, ele, ind + 1) # Driver Codes = \"{(X}[]\"ele = [] if (isBalanced(s, ele, 0)): print(\"Balanced\")else: print(\"Not Balanced\") # This code is contributed by divyeshrabadiya07", "e": 35709, "s": 33426, "text": null }, { "code": "// C# program to determine// whether given expression// is balanced/ parenthesis// expression or not.using System;using System.Collections.Generic; class GFG{ // Function to check if two // brackets are matching or not. static int isMatching(char a, char b) { if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0; } // Recursive function to // check if given expression // is balanced or not. static int isBalanced(string s, Stack<char> ele, int ind) { // Base case. // If the string is balanced // then all the opening brackets // had been popped and stack // should be empty after string // is traversed completely. if (ind == s.Length) { if (ele.Count == 0) return 1; else return 0; } // variable to store element // at the top of the stack. char topEle; // variable to store result // of recursive call. int res; // Case 1: When current element // is an opening bracket // then push that element // in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.Push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element // is a closing bracket then // check for matching bracket // at the top of the stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there // is no matching opening bracket // for current closing bracket and // the expression is not balanced. if (ele.Count == 0) return 0; topEle = ele.Peek(); ele.Pop(); // Check bracket is // matching or not. if (isMatching(topEle, s[ind]) == 0) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element // is 'X' then check for both // the cases when 'X' could be // opening or closing bracket. else if (s[ind] == 'X') { Stack<char> tmp = ele; tmp.Push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res == 1) return 1; if (ele.Count == 0) return 0; ele.Pop(); return isBalanced(s, ele, ind + 1); } return 1; } // Driver Code static void Main() { string s = \"{(X}[]\"; Stack<char> ele = new Stack<char>(); if (isBalanced(s, ele, 0) != 0) Console.Write(\"Balanced\"); else Console.Write(\"Not Balanced\"); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 38825, "s": 35709, "text": null }, { "code": "<script> // JavaScript program to determine whether given// expression is balanced/ parenthesis// expression or not. // Function to check if two brackets are matching// or not.function isMatching(a, b){ if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0;} // Recursive function to check if given expression// is balanced or not.function isBalanced(s, ele, ind){ // Base case. // If the string is balanced then all the opening // brackets had been popped and stack should be // empty after string is traversed completely. if (ind == s.length) return ele.length==0; // variable to store element at the top of the stack. var topEle; // variable to store result of recursive call. var res; // Case 1: When current element is an opening bracket // then push that element in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element is a closing bracket // then check for matching bracket at the top of the // stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there is no matching opening // bracket for current closing bracket and the // expression is not balanced. if (ele.length==0) return 0; topEle = ele[ele.length-1]; ele.pop(); // Check bracket is matching or not. if (!isMatching(topEle, s[ind])) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element is 'X' then check // for both the cases when 'X' could be opening // or closing bracket. else if (s[ind] == 'X') { var tmp = ele; tmp.push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res) return 1; if (ele.length==0) return 0; ele.pop(); return isBalanced(s, ele, ind + 1); }} var s = \"{(X}[]\";var ele = [];if (isBalanced(s, ele, 0)) document.write( \"Balanced\"); else document.write( \"Not Balanced\"); </script>", "e": 41012, "s": 38825, "text": null }, { "code": null, "e": 41021, "s": 41012, "text": "Balanced" }, { "code": null, "e": 41074, "s": 41023, "text": "Time Complexity: O((2^n)*n) Auxiliary Space: O(N) " }, { "code": null, "e": 41086, "s": 41074, "text": "manishshaw1" }, { "code": null, "e": 41100, "s": 41086, "text": "princiraj1992" }, { "code": null, "e": 41106, "s": 41100, "text": "msvsk" }, { "code": null, "e": 41124, "s": 41106, "text": "divyeshrabadiya07" }, { "code": null, "e": 41134, "s": 41124, "text": "rutvik_56" }, { "code": null, "e": 41140, "s": 41134, "text": "Stack" }, { "code": null, "e": 41148, "s": 41140, "text": "Strings" }, { "code": null, "e": 41167, "s": 41148, "text": "Technical Scripter" }, { "code": null, "e": 41175, "s": 41167, "text": "Strings" }, { "code": null, "e": 41181, "s": 41175, "text": "Stack" }, { "code": null, "e": 41279, "s": 41181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41288, "s": 41279, "text": "Comments" }, { "code": null, "e": 41301, "s": 41288, "text": "Old Comments" }, { "code": null, "e": 41342, "s": 41301, "text": "Real-time application of Data Structures" }, { "code": null, "e": 41379, "s": 41342, "text": "Sort a stack using a temporary stack" }, { "code": null, "e": 41404, "s": 41379, "text": "Iterative Tower of Hanoi" }, { "code": null, "e": 41429, "s": 41404, "text": "Reverse individual words" }, { "code": null, "e": 41451, "s": 41429, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 41476, "s": 41451, "text": "Reverse a string in Java" }, { "code": null, "e": 41522, "s": 41476, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 41556, "s": 41522, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 41571, "s": 41556, "text": "C++ Data Types" } ]
Using Data Science to Predict Negative Customer Reviews | by Chuck Utterback | Towards Data Science
If you could confidently predict that a customer was going to leave a negative review, what would your business do differently? Proactively intervene to improve customer experience and hopefully divert them from leaving bad public review scores? Learn from important features in your predictive model to fix the root causes of poor customer experiences? The answer is “yes” to both, with careful consideration of the cost-benefit tradeoff and the company’s ability to implement corrective actions. “Negative reviews have convinced 94 percent of consumers to avoid a business” — Review Trackers Brazil’s leading e-commerce marketplace for small businesses is Olist. Olist Store enables merchants from all over Brazil to sell and ship products to customers using Olist logistics partners. After delivery, customers receive an email satisfaction survey using a scale of 1 (unhappy) to 5 (pleased). Olist has kindly released anonymized customer review and order details for over 100K transactions from 2017–2018. This popular data set has been downloaded by data scientists over 76K times. Let’s build a predictive model for “bad customer reviews” as defined by receiving a score of either 1 or 2 on the scale of 5. In our large sample of delivered orders, 13.2% of review scores were bad (negative). We will solve for a binary target variable: review_bad = 1. Our goal is to find a supervised machine learning classification model that can predict bad customer reviews with the best precision. High precision indicates that when our model predicts a bad review, it’s usually correct. This minimizes company risk of taking incorrect action on predicted negative customer reviews. Olist provided data from 8 relational tables which had excellent referential integrity. The diagram below shows a familiar data model with unique order IDs facilitating joins to multiple items and payments per order. Master data tables include products, customers and sellers. Customer reviews are linked to an overall order that can include multiple products or sellers on an order. Raw data across the 8 tables includes 52 distinct columns. Predictive features I developed can be grouped by these domains. In the interest of brevity, I’m not including the full code used on this project. For full details, please refer to my Jupyter notebook on GitHub. Data transformations that were used to prepare predictive features: Filtered out records from 2016 and non-delivered orders (less than 1%) Filled in just a handful of records where nulls were present Aggregated metrics on orders, payments, products and sellers as depicted Calculated days interval metrics using lifecycle dates from the orders Estimated delivery distance in kilometers between seller and customer zip codes using median latitude and longitude in a haversine function Created one-hot encoding variables (flags) for payment methods, customer states, day-of-week and time-of-day buckets (morning, afternoon, etc.) Purged multiple reviews for any order, keeping only the final rating; this affected less than 1% of orders During data analysis, I usually export the final merged data frame from Jupyter notebook out to Tableau for faster visual inspection. Let’s take a look at the most interesting views for insight. Delivered Days Late: Olist provides customers with an estimated delivery date at time of order which averages 24 expected processing/transit days. The actual delivery performance matters greatly as shown above. For orders that were delivered late (negative variances to estimated date), customer bad reviews averaged 55% versus 10% on non-late deliveries. The greater the number of days late, the higher proportion of bad reviews. Seller-Product Quality: The scatter plot depicts a linear trend between late deliveries and bad reviews with each observation being a seller’s average performance across all customers. Late orders don’t explain the whole story as many sellers with above average delivery performance (circled) but are seeing higher bad review rates. Variety in Products: Using the tree map, we can see variation in bad review rates by product category. Drilling into some individual products we can see some “dogs” with higher than 50% bad reviews where customer expectations are clearly not met. The average bad review rate for a product is a significant feature in the final model. Geographic Breakdown: There are 26 states and 1 federal district in Brazil. We can definitely see variations in bad reviews amongst the states. Sáo Paulo — representing 42% of orders in our data, this state significantly out-performed on each metric. Rio de Janeiro — this nearby state, representing 13% of orders, significantly under-performed on each metric. Both states are each home to one of the two largest cities in Brazil, with high population density and relative proximity to each other. Rio de Janeiro should be a target for deeper digging into delivery performance and product mix. Why do customers on average order products with a high index of bad reviews relative to average? (a 148 product index means the products purchased on average had 48% worse bad review rates than the average product in Brazil overall). Running Pearson correlations against our review_bad target variable in Python largely confirms associations we’ve seen in prior plots. When looking at single feature correlations, we see moderate positive correlations on all forms of delivery intervals (is_late, act_delivery_days, days_late, and days_variance). We also see positive 0.23 and 0.17 correlations on products and sellers overall bad review rates, respectively. Lastly we see some other minor influences on order/seller item counts, freight/order values, and delivery distance. The only 2 states of 27 with correlations greater than 0.03 are indeed Rio de Janeiro (+0.07) and Sáo Paulo (-0.06), supporting our state map graphic above. Seven supervised learning classification models were optimized on the “precision” metric but looking for a reasonable “recall” (proportion of bad reviews our model correctly predicts). For each model I used grid search on 80% training data with stratified 5-fold cross-validation to explore a variety of parameter combinations. Models compared included Random Forest, AdaBoost, Gradient Boost, XG Boost, Logistic Regression, SGD Classifier and Gaussian Naive Bayes. Relevant features were scaled using StandardScaler so I had consistent training features as input to each model (even though most models did not require scaling). The resulting “best model” for each classifier was then run on previously unseen 20% scaled test data with comparative model results shown above. I’ve recommended the Gradient Boost model which had the following performance: Precision of 84%, Recall of 29%, Accuracy 88%, AUC 64%. Parameters from the best estimator were: 'learning_rate': 0.01, 'max_depth': 8, 'min_samples_leaf': 25, 'n_estimators': 100 Using this model with the standard 0.50 probability decision threshold results in predicting about 1/3rd of bad reviews (recall) while only being wrong 1 out of 6 times (precision, false positives). This would be a start to take action, and we would want to continue to refine the model with experience and broader data. The most important features in the Gradient Boost model included: Strong: Delivered Days Late, Days Variance, Product Bad Review %, Count of Items on Order Moderate: Count of Sellers on Order, Seller Bad Review % Weak: Actual Delivery Days, Total Orders for Product, Total Orders for Seller, Freight Amount on Order, Delivery Distance (km) In summary, bad reviews are most sensitive to late deliveries, products/seller histories, and coordination of multiple sellers/products. Olist should try to fix the root causes for poor delivery performance. Olist might also try a randomized cost-benefit trial to see if proactive communications, acknowledgment or customer concessions might prevent bad reviews from being posted. Ultimately, a negative review is a gift. It shows that your customers care enough about your brand to take the time to leave you feedback. Even the worst reviews can turn into positive experiences, if handled correctly. — Emily Heaslip A few observations on data quality and assumptions inherent in this project. Sample vs. Population: The sample of 100K orders, each with an associated review rating, is great for building a model but not representative of the population. Given only 5–10% of customers write reviews, and not every time, we’d have some work to translate our model to generalize against the full population of Olist orders. Need Additional Features: While 84% precision predicting 29% of bad reviews is a start, we need to do better. Additional data I’d recommend that Olist acquire for further feature development: full database of orders, customer returns, customer web logs, customer service interactions, customer personas, demographics, brand/product/seller social sentiment, and data from sellers. Marketing Funnel: Olist also released a marketing funnel dataset on Kaggle which contains 2 upstream tables from the seller qualification process. This data was unusable when joined to the order schema since it contained only sellers signed-up between 2017–2018, representing a small fraction of actual orders during this period (most were by established sellers).
[ { "code": null, "e": 300, "s": 172, "text": "If you could confidently predict that a customer was going to leave a negative review, what would your business do differently?" }, { "code": null, "e": 418, "s": 300, "text": "Proactively intervene to improve customer experience and hopefully divert them from leaving bad public review scores?" }, { "code": null, "e": 526, "s": 418, "text": "Learn from important features in your predictive model to fix the root causes of poor customer experiences?" }, { "code": null, "e": 670, "s": 526, "text": "The answer is “yes” to both, with careful consideration of the cost-benefit tradeoff and the company’s ability to implement corrective actions." }, { "code": null, "e": 766, "s": 670, "text": "“Negative reviews have convinced 94 percent of consumers to avoid a business” — Review Trackers" }, { "code": null, "e": 1067, "s": 766, "text": "Brazil’s leading e-commerce marketplace for small businesses is Olist. Olist Store enables merchants from all over Brazil to sell and ship products to customers using Olist logistics partners. After delivery, customers receive an email satisfaction survey using a scale of 1 (unhappy) to 5 (pleased)." }, { "code": null, "e": 1258, "s": 1067, "text": "Olist has kindly released anonymized customer review and order details for over 100K transactions from 2017–2018. This popular data set has been downloaded by data scientists over 76K times." }, { "code": null, "e": 1469, "s": 1258, "text": "Let’s build a predictive model for “bad customer reviews” as defined by receiving a score of either 1 or 2 on the scale of 5. In our large sample of delivered orders, 13.2% of review scores were bad (negative)." }, { "code": null, "e": 1529, "s": 1469, "text": "We will solve for a binary target variable: review_bad = 1." }, { "code": null, "e": 1663, "s": 1529, "text": "Our goal is to find a supervised machine learning classification model that can predict bad customer reviews with the best precision." }, { "code": null, "e": 1848, "s": 1663, "text": "High precision indicates that when our model predicts a bad review, it’s usually correct. This minimizes company risk of taking incorrect action on predicted negative customer reviews." }, { "code": null, "e": 2232, "s": 1848, "text": "Olist provided data from 8 relational tables which had excellent referential integrity. The diagram below shows a familiar data model with unique order IDs facilitating joins to multiple items and payments per order. Master data tables include products, customers and sellers. Customer reviews are linked to an overall order that can include multiple products or sellers on an order." }, { "code": null, "e": 2356, "s": 2232, "text": "Raw data across the 8 tables includes 52 distinct columns. Predictive features I developed can be grouped by these domains." }, { "code": null, "e": 2503, "s": 2356, "text": "In the interest of brevity, I’m not including the full code used on this project. For full details, please refer to my Jupyter notebook on GitHub." }, { "code": null, "e": 2571, "s": 2503, "text": "Data transformations that were used to prepare predictive features:" }, { "code": null, "e": 2642, "s": 2571, "text": "Filtered out records from 2016 and non-delivered orders (less than 1%)" }, { "code": null, "e": 2703, "s": 2642, "text": "Filled in just a handful of records where nulls were present" }, { "code": null, "e": 2776, "s": 2703, "text": "Aggregated metrics on orders, payments, products and sellers as depicted" }, { "code": null, "e": 2847, "s": 2776, "text": "Calculated days interval metrics using lifecycle dates from the orders" }, { "code": null, "e": 2987, "s": 2847, "text": "Estimated delivery distance in kilometers between seller and customer zip codes using median latitude and longitude in a haversine function" }, { "code": null, "e": 3131, "s": 2987, "text": "Created one-hot encoding variables (flags) for payment methods, customer states, day-of-week and time-of-day buckets (morning, afternoon, etc.)" }, { "code": null, "e": 3238, "s": 3131, "text": "Purged multiple reviews for any order, keeping only the final rating; this affected less than 1% of orders" }, { "code": null, "e": 3433, "s": 3238, "text": "During data analysis, I usually export the final merged data frame from Jupyter notebook out to Tableau for faster visual inspection. Let’s take a look at the most interesting views for insight." }, { "code": null, "e": 3864, "s": 3433, "text": "Delivered Days Late: Olist provides customers with an estimated delivery date at time of order which averages 24 expected processing/transit days. The actual delivery performance matters greatly as shown above. For orders that were delivered late (negative variances to estimated date), customer bad reviews averaged 55% versus 10% on non-late deliveries. The greater the number of days late, the higher proportion of bad reviews." }, { "code": null, "e": 4197, "s": 3864, "text": "Seller-Product Quality: The scatter plot depicts a linear trend between late deliveries and bad reviews with each observation being a seller’s average performance across all customers. Late orders don’t explain the whole story as many sellers with above average delivery performance (circled) but are seeing higher bad review rates." }, { "code": null, "e": 4531, "s": 4197, "text": "Variety in Products: Using the tree map, we can see variation in bad review rates by product category. Drilling into some individual products we can see some “dogs” with higher than 50% bad reviews where customer expectations are clearly not met. The average bad review rate for a product is a significant feature in the final model." }, { "code": null, "e": 4675, "s": 4531, "text": "Geographic Breakdown: There are 26 states and 1 federal district in Brazil. We can definitely see variations in bad reviews amongst the states." }, { "code": null, "e": 4783, "s": 4675, "text": "Sáo Paulo — representing 42% of orders in our data, this state significantly out-performed on each metric." }, { "code": null, "e": 4893, "s": 4783, "text": "Rio de Janeiro — this nearby state, representing 13% of orders, significantly under-performed on each metric." }, { "code": null, "e": 5360, "s": 4893, "text": "Both states are each home to one of the two largest cities in Brazil, with high population density and relative proximity to each other. Rio de Janeiro should be a target for deeper digging into delivery performance and product mix. Why do customers on average order products with a high index of bad reviews relative to average? (a 148 product index means the products purchased on average had 48% worse bad review rates than the average product in Brazil overall)." }, { "code": null, "e": 5495, "s": 5360, "text": "Running Pearson correlations against our review_bad target variable in Python largely confirms associations we’ve seen in prior plots." }, { "code": null, "e": 5673, "s": 5495, "text": "When looking at single feature correlations, we see moderate positive correlations on all forms of delivery intervals (is_late, act_delivery_days, days_late, and days_variance)." }, { "code": null, "e": 5785, "s": 5673, "text": "We also see positive 0.23 and 0.17 correlations on products and sellers overall bad review rates, respectively." }, { "code": null, "e": 6059, "s": 5785, "text": "Lastly we see some other minor influences on order/seller item counts, freight/order values, and delivery distance. The only 2 states of 27 with correlations greater than 0.03 are indeed Rio de Janeiro (+0.07) and Sáo Paulo (-0.06), supporting our state map graphic above." }, { "code": null, "e": 6387, "s": 6059, "text": "Seven supervised learning classification models were optimized on the “precision” metric but looking for a reasonable “recall” (proportion of bad reviews our model correctly predicts). For each model I used grid search on 80% training data with stratified 5-fold cross-validation to explore a variety of parameter combinations." }, { "code": null, "e": 6525, "s": 6387, "text": "Models compared included Random Forest, AdaBoost, Gradient Boost, XG Boost, Logistic Regression, SGD Classifier and Gaussian Naive Bayes." }, { "code": null, "e": 6688, "s": 6525, "text": "Relevant features were scaled using StandardScaler so I had consistent training features as input to each model (even though most models did not require scaling)." }, { "code": null, "e": 6834, "s": 6688, "text": "The resulting “best model” for each classifier was then run on previously unseen 20% scaled test data with comparative model results shown above." }, { "code": null, "e": 7010, "s": 6834, "text": "I’ve recommended the Gradient Boost model which had the following performance: Precision of 84%, Recall of 29%, Accuracy 88%, AUC 64%. Parameters from the best estimator were:" }, { "code": null, "e": 7093, "s": 7010, "text": "'learning_rate': 0.01, 'max_depth': 8, 'min_samples_leaf': 25, 'n_estimators': 100" }, { "code": null, "e": 7414, "s": 7093, "text": "Using this model with the standard 0.50 probability decision threshold results in predicting about 1/3rd of bad reviews (recall) while only being wrong 1 out of 6 times (precision, false positives). This would be a start to take action, and we would want to continue to refine the model with experience and broader data." }, { "code": null, "e": 7480, "s": 7414, "text": "The most important features in the Gradient Boost model included:" }, { "code": null, "e": 7570, "s": 7480, "text": "Strong: Delivered Days Late, Days Variance, Product Bad Review %, Count of Items on Order" }, { "code": null, "e": 7627, "s": 7570, "text": "Moderate: Count of Sellers on Order, Seller Bad Review %" }, { "code": null, "e": 7754, "s": 7627, "text": "Weak: Actual Delivery Days, Total Orders for Product, Total Orders for Seller, Freight Amount on Order, Delivery Distance (km)" }, { "code": null, "e": 8135, "s": 7754, "text": "In summary, bad reviews are most sensitive to late deliveries, products/seller histories, and coordination of multiple sellers/products. Olist should try to fix the root causes for poor delivery performance. Olist might also try a randomized cost-benefit trial to see if proactive communications, acknowledgment or customer concessions might prevent bad reviews from being posted." }, { "code": null, "e": 8371, "s": 8135, "text": "Ultimately, a negative review is a gift. It shows that your customers care enough about your brand to take the time to leave you feedback. Even the worst reviews can turn into positive experiences, if handled correctly. — Emily Heaslip" }, { "code": null, "e": 8448, "s": 8371, "text": "A few observations on data quality and assumptions inherent in this project." }, { "code": null, "e": 8776, "s": 8448, "text": "Sample vs. Population: The sample of 100K orders, each with an associated review rating, is great for building a model but not representative of the population. Given only 5–10% of customers write reviews, and not every time, we’d have some work to translate our model to generalize against the full population of Olist orders." }, { "code": null, "e": 9156, "s": 8776, "text": "Need Additional Features: While 84% precision predicting 29% of bad reviews is a start, we need to do better. Additional data I’d recommend that Olist acquire for further feature development: full database of orders, customer returns, customer web logs, customer service interactions, customer personas, demographics, brand/product/seller social sentiment, and data from sellers." } ]